‘0’:0x00
‘r’:return
‘\n’:newline
通讯协议:
W1:DQ
I2C:SDA、SCK
UART:GND、TXD、RXD
SPI:CLK、CS、MISO、MOSI
常用I2C、SPI
流程
打开目标文件夹opendir()
找到并打开目标文件strstr()、open()
读文件并找到目标信息read()、strstr()
关闭文件close()
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
int get_temperature(float *temp);
int main(int argc,char *argv[])
{
float temp;
int rv;
rv = get_temperature(&temp);
if(rv<0)
{
printf("get temperature fialure,return vilue:%d",rv);
return -1;
}
printf("temp: %.4f\n",temp);
return 0;
}
int get_temperature(float *temp)
{
int fd=-1;
char buf[128];
char *ptr=NULL;
DIR *dirp=NULL;
struct dirent *direntp = NULL;
char w1_path[64]="/sys/bus/w1/devices/";
char chip_sn[32];
char ds18b20_path[64];
dirp=opendir(w1_path);
if(!dirp)
{
printf("Opendir :%s failure:%s\n",w1_path,strerror(errno));
return -1;
}
while(NULL!=(direntp=readdir(dirp)))
{
if(strstr(direntp->d_name,"28-"))
{
strncpy(chip_sn,direntp->d_name,sizeof(chip_sn));
}
}
snprintf(ds18b20_path,sizeof(ds18b20_path),"%s%s/w1_slave",w1_path,chip_sn);
printf("ds18b20_path:%s\n",ds18b20_path);
fd=open(ds18b20_path,O_RDONLY);
if(fd<0)
{
printf("open file failure: %s\n",strerror(errno));
return -2;
}
memset(buf,0,sizeof(buf));
read(fd,buf,sizeof(buf));
if(read(fd,buf,sizeof(buf))<0)
{
printf("read file failure: %s/n",strerror(errno));
return -3;
}
//printf("buf:%s\n",buf);
ptr=strstr(buf,"t=");
if(!ptr)
{
printf("NO Find f=");
return -4;
}
ptr+=2;
//printf("str:%s\n",ptr);
*temp = atof(ptr)/1000;
printf("temp: %.4f\n",*temp);
close(fd);
return 0;
}
输出结果:
iot23@pubraspberry:~/oujunhong/gettemp $ ls
ds18b20.c gettemperature
iot23@pubraspberry:~/oujunhong/gettemp $ ./gettemperature
ds18b20_path:/sys/bus/w1/devices/28-041701d839ff/w1_slave
temp: 25.0000
temp: 25.0000