代码
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <wiringPi.h>
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/";
Get_FilePath(path);
while(1){
if (Get_DS18B20_Temp(&temp, path) < 0)
{
printf("ERROR: DS18B20 Get Temperature Failure\n");
}
printf("Temperature is: %.3f C\n", 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;
memset(dir_name, 0, sizeof(dir_name));
if ((dirp = opendir(path)) == NULL)
{
printf("ERROR: Open Directory '%s' Failure: %s\n", path, strerror(errno));
return -1;
}
printf("Open Directory '%s' Successfully\n", path);
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: %s\n", dir_name);
found = 1;
break;
}
closedir(dirp);
if (found == -1)
{
printf("ERROR: Can not find DS18B20 in %s\n", path);
return -2;
}
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];
memset(buf, 0, sizeof(buf));
if ((fd = open(path, O_RDONLY)) < 0)
{
printf("ERROR: Open file '%s' Failure: %s\n", path, strerror(errno));
return -3;
}
printf("Open file '%s' fd[%d] Successfully\n", path, fd);
if ((rv = read(fd, buf, sizeof(buf))) < 0)
{
printf("ERROR: Read data from file '%s' Failure: %s\n", path, strerror(errno));
rv = -4;
goto cleanup;
}
printf("Read %dB data from file '%s'\n", rv, path);
if ((ptr = strstr(buf, "t=") + 2) == NULL)
{
printf("ERROR: Find data Failure: %s", strerror(errno));
rv = -5;
goto cleanup;
}
*temp = atof(ptr)/1000;
cleanup:
if (fd > 0)
close(fd);
return rv;
}
使能树莓派内核的单总线协议驱动模块(1-Wire)
【C语言】树莓派(Raspberry Pi)+DS18B20 获取当前温度