树莓派单总线自动读取18b20温度传感器的C语言例程
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <unistd.h>
-
#include <fcntl.h>
-
#include <dirent.h>
-
#include <string.h>
-
#include <time.h>
-
-
int main(int argc, char *argv[])
-
{
-
char path[50] = "/sys/bus/w1/devices/";
-
char rom[20];
-
char buf[100];
-
DIR *dirp;
-
struct dirent *direntp;
-
int fd =-1;
-
char *temp;
-
float value;
-
-
system("sudo modprobe w1-gpio");
-
system("sudo modprobe w1-therm");
-
if((dirp = opendir(path)) == NULL)
-
{
-
printf("opendir error\n");
-
return 1;
-
}
-
-
while((direntp = readdir(dirp)) != NULL)
-
{
-
if(strstr(direntp->d_name,"28-00000"))
-
{
-
strcpy(rom,direntp->d_name);
-
printf(" rom: %s\n",rom);
-
}
-
}
-
closedir(dirp);
-
-
strcat(path,rom);
-
strcat(path,"/w1_slave");
-
while(1)
-
{
-
if((fd = open(path,O_RDONLY)) < 0)
-
{
-
printf("open error\n");
-
return 1;
-
}
-
-
if(read(fd,buf,sizeof(buf)) < 0)
-
{
-
printf("read error\n");
-
return 1;
-
}
-
-
temp = strchr(buf,'t');
-
sscanf(temp,"t=%s",temp);
-
value = atof(temp)/1000;
-
printf(" temp : %3.3f °C\n",value);
-
-
sleep(1);
-
}
-
return 0;
- }
注:(1)system("sudo modprobe w1-gpio");system("sudo modprobe w1-therm");在程序的开头运行了一下modprobe命令
(2) dirp = opendir(path) 打开/sys/bus/w1/devices/文件路径
(3)direntp = readdir(dirp) 读取当前路径下的文件或文件夹
(4)strstr(direntp->d_name,"28-00000")
查找28-00000开头的文件,strstr为字符串操作函数,上面这条语句表示文件名字是否包含字符串“28-00000”,如果匹配则返回第一次匹配的地址,没有搜索到则返回NULL.
(5)strcpy(rom,direntp->d_name); strcpy为字符串复制函数。,将包含28-00000的文件名复制到rom字符串
(6)strcat(path,rom);strcat(path,"/w1_slave"); strcat为字符串连接函数,此时path的值为/sys/bus/w1/devices/28-00000xxxx/w1_slave
(7)fd = open(path,O_RDONLY); read(fd,buf,sizeof(buf)) 打开文件并读取数据
(8)temp = strchr(buf,'t'); 查找字符‘t’第一次出现的位置,
(9)sscanf(temp,"t=%s",temp); sscanf函数是从一个字符串中读进与指定格式相符的数据,此处为从第二行数据中扫描出温度值