#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
int ds18b20_get_temperature(float *temp)
{
int fd=-1;
char buf[256]; //创建一个buf
DIR* dir; //用opendir打开文件夹,返回一个指针
struct dirent *ptr; //定义一个指向文件夹信息结构体的指针fp,
char* l ="28-";
char* m ="t=";
char* q;
char strtemp[20];
int found; //是否找到设备ds18b20,找到found=1,没找到found=0
char path[128]="/sys/bus/w1/devices/";//用来存放目录路径
char* point;
dir =opendir(path); //打开设备所在路径文件夹
/*判断传进来的地址是否存在,不存在返回-1*/
if(temp==NULL)
{
return -1;
}
/*判断设备所在路径是否合法,合法则打印路径,不合法则调用系统出错,并返回-2 */
if (dir==NULL)
{
perror("oepn devicedir failure");
return -2;
}
else
printf("\nopendir succful!\n") ;
/*读取产品序列号,即:读取28-后的字符串*/
ptr=readdir(dir);
if((ptr=readdir(dir)) == NULL)
{
perror("ptr=readdir(dir)");
return -1;
}
while((ptr=readdir(dir)) !=NULL)
{
//printf("d_name : %s\n",strstr(ptr->d_name,l));
q=strstr(ptr->d_name,l); //指针q指向(传感设备文件全名字符串):“28-041731f7c0ff”
if(q!=NULL) //如果指针不指向空
{
strcpy(strtemp,ptr->d_name); //把设备名拷贝到数组strtemp中去
printf("DEVICE:%s\n",strtemp);
printf("DS18b20 SN=%s\n",q+strlen(l)); //打印去头(28-)产品序列号
printf("path=%s\n",path);
strncat(path,strtemp,sizeof(strtemp));
strncat(path,"/w1_slave",sizeof("/w1_slave"));
printf("ALL_path:%s\n",path);
if((fd=open(path,O_RDONLY))<0)
{
perror("open2 error:");
return -4;
}
else
{
printf("fd=%d\n",fd);
}
memset(buf,0,sizeof(buf));
lseek(fd,0,SEEK_SET);
if ( (read(fd,buf,sizeof(buf)) )<0 )
{
perror("read error\n");
return -5;
}
strstr(buf,"t=");
printf("data=%s\n",buf);
point=strstr(buf,m);
printf("t=%s",point+strlen(m));
if(!point)
{
perror("can't not get [T]");
return -6;
}
*temp=atof(point+strlen(m))/1000;
}
}
}
int main(int argc,char**argv)
{
float temp; //温度是浮点数
if(ds18b20_get_temperature(&temp)<0)
{
printf("ds18b20 Initialization failed\n");
return 1;
}
else
{
printf("The real time temperatue is %f°C\n",temp);
}
return 0;
}
运行结果:
opendir succful!
DEVICE:28-041731f7c0ff
DS18b20 SN=041731f7c0ff
path=/sys/bus/w1/devices/
ALL_path:/sys/bus/w1/devices/28-041731f7c0ff/w1_slave
fd=4
data=d6 01 4b 46 7f ff 0c 10 e9 : crc=e9 YES
d6 01 4b 46 7f ff 0c 10 e9 t=29375
t=29375
The real time temperatue is 29.375000°C