2020-09-10 13:23:23 +08:00
|
|
|
/*
|
|
|
|
* DS18B20 温度传感器(Debian jessie)
|
2018-09-11 22:35:16 +08:00
|
|
|
*
|
|
|
|
*/
|
|
|
|
|
2018-03-29 20:06:23 +08:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <dirent.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <time.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
2020-09-10 13:23:23 +08:00
|
|
|
#define BUF 270
|
2018-07-02 10:13:22 +08:00
|
|
|
|
2020-09-10 13:23:23 +08:00
|
|
|
int _read_ds18b20(char *device)
|
2018-03-29 20:06:23 +08:00
|
|
|
{
|
|
|
|
char path[50] = "/sys/bus/w1/devices/";
|
|
|
|
char rom[20];
|
2020-09-10 13:23:23 +08:00
|
|
|
char buffer[BUF + 1];
|
2018-03-29 20:06:23 +08:00
|
|
|
DIR *dirp;
|
|
|
|
struct dirent *direntp;
|
|
|
|
FILE *fp;
|
|
|
|
char *temp;
|
|
|
|
float value;
|
2020-09-10 13:23:23 +08:00
|
|
|
|
2018-03-29 20:06:23 +08:00
|
|
|
system("sudo modprobe w1-gpio");
|
|
|
|
system("sudo modprobe w1-therm");
|
2020-09-10 13:23:23 +08:00
|
|
|
if ((dirp = opendir(path)) == NULL) {
|
2018-03-29 20:06:23 +08:00
|
|
|
exit(0);
|
|
|
|
}
|
|
|
|
|
2020-09-10 13:23:23 +08:00
|
|
|
while ((direntp = readdir(dirp)) != NULL) {
|
|
|
|
if (strstr(direntp->d_name, device)) {
|
2018-03-29 20:06:23 +08:00
|
|
|
strcpy(rom, direntp->d_name);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
closedir(dirp);
|
|
|
|
|
|
|
|
strcat(path, rom);
|
|
|
|
strcat(path, "/w1_slave");
|
|
|
|
//printf("%s\n", path);
|
|
|
|
|
|
|
|
if ((fp = fopen(path, "r")) < 0) {
|
2020-09-10 13:23:23 +08:00
|
|
|
exit(0); /* 文件不存在,则退出. */
|
2018-03-29 20:06:23 +08:00
|
|
|
}
|
2020-09-10 13:23:23 +08:00
|
|
|
while (fgets(buffer, BUF, fp) != NULL) {
|
2018-03-29 20:06:23 +08:00
|
|
|
;
|
|
|
|
}
|
|
|
|
|
|
|
|
temp = strchr(buffer, 't');
|
|
|
|
sscanf(temp, "t=%s", temp);
|
|
|
|
value = atof(temp) / 1000;
|
|
|
|
printf("%.0f\n", value);
|
|
|
|
|
|
|
|
fclose(fp);
|
2018-09-11 22:35:16 +08:00
|
|
|
return value;
|
2018-03-29 20:06:23 +08:00
|
|
|
}
|
2020-09-10 13:23:23 +08:00
|
|
|
|
|
|
|
int main(int argc, char *argv[])
|
|
|
|
{
|
|
|
|
int ch;
|
|
|
|
opterr = 0;
|
|
|
|
while ((ch = getopt(argc, argv, "d:h?")) != -1)
|
|
|
|
switch (ch) {
|
|
|
|
case 'd':
|
|
|
|
_read_ds18b20(optarg);
|
|
|
|
break;
|
|
|
|
case 'h': case '?':
|
|
|
|
printf("wind -d device\n");
|
|
|
|
exit(0);
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
;
|
|
|
|
}
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|