APUE-学习

‘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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值