树莓派驱动DS18b20温度检测模块

第一步:允许单总线接口

sudo raspi-config

第二步:进入interfacing options
在这里插入图片描述
第三步:
在这里插入图片描述
第四步:接线
正极接3-5.5V,负极接地,OUT引脚接GPIO4(BCM编码)

代码

#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;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值