#include使能树莓派内核的单总线协议驱动模块(1-Wire)#include #include #include #include #include #include #include #include #include int Get_FilePath(char *path); // 获取文件路径 int Get_DS18B20_Temp(double *temp, char *path); // 获取温度数值 int main(void) { double temp; char path[50] = "/sys/bus/w1/devices/"; // DS18B20是利用单总线协议进行通讯的,设备都是以文件形式存在 Get_FilePath(path); // 获取DS18B20存放温度数据的文件/sys/bus/w1/devices/28-xxxxxx/w1_slave' “28-”后面的DS18B20的序号。 while(1){ if (Get_DS18B20_Temp(&temp, path) < 0) { printf("ERROR: DS18B20 Get Temperature Failuren"); //return -1; } printf("Temperature is: %.3f Cn", temp); delay(1000); delay(1000); delay(1000); } return 0; } int Get_FilePath(char *path){ char dir_name[20]; int found = -1; DIR *dirp; struct dirent *direntp; //清空dir_name内存空间的值,避免随机值产生乱码 memset(dir_name, 0, sizeof(dir_name)); //打开文件夹"/sys/bus/w1/devices/" if ((dirp = opendir(path)) == NULL) { printf("ERROR: Open Directory '%s' Failure: %sn", path, strerror(errno)); return -1; } printf("Open Directory '%s' Successfullyn", path); //在文件夹中找DS18B20的文件夹28-xx while ((direntp = readdir(dirp)) != NULL) { if (strstr(direntp->d_name, "28-") == NULL) continue; strncpy(dir_name, direntp->d_name, strlen(direntp->d_name)); printf("Find file: %sn", dir_name); found = 1; break; } closedir(dirp); //找不到该文件夹 if (found == -1) { printf("ERROR: Can not find DS18B20 in %sn", path); return -2; } //将文件夹名和文件名分别拼接到path上 strncat(path, dir_name, strlen(dir_name)); strncat(path, "/w1_slave", sizeof(path)-strlen(path)); return 1; } int Get_DS18B20_Temp(double *temp, char *path) { int fd = -1; int rv = -1; char *ptr; char buf[128]; //清空buf内存空间的值,避免随机值产生乱码 memset(buf, 0, sizeof(buf)); //打开w1_slave文件 if ((fd = open(path, O_RDONLY)) < 0) { printf("ERROR: Open file '%s' Failure: %sn", path, strerror(errno)); return -3; } printf("Open file '%s' fd[%d] Successfullyn", path, fd); //从w1_slave中读取内容 if ((rv = read(fd, buf, sizeof(buf))) < 0) { printf("ERROR: Read data from file '%s' Failure: %sn", path, strerror(errno)); rv = -4; goto cleanup; } printf("Read %dB data from file '%s'n", rv, path); //从buf里匹配"t=",并将ptr移到数据的首地址上 if ((ptr = strstr(buf, "t=") + 2) == NULL) { printf("ERROR: Find data Failure: %s", strerror(errno)); rv = -5; goto cleanup; } //将数据转为double型,除1000得到正常的十进制温度 *temp = atof(ptr)/1000; cleanup: if (fd > 0) close(fd); return rv; }
【C语言】树莓派(Raspberry Pi)+DS18B20 获取当前温度



