树莓派+温度模块

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_45380951/article/details/100526680

温度模块(18B20)

DS18B20是常用的数字温度传感器,输出的是数字信号;
特点:体积小,硬件开销低,抗干扰能力强,精度高,接线方便;
封装成后可应用于多种场合,如管道式,螺纹式,磁铁吸附式,不锈钢封装式,型号多种多样(LTM8877,LTM8874等)。
根据不同的应用场合就有不同的外观,封装后可用于电缆沟测温,高炉水循环测温,锅炉测温,机房测温,农业大棚测温,洁净室测温,弹药库测温等各种非极限温度场合。耐磨耐碰,体积小,使用方便,封装形式多样,适用于各种狭小空间设备数字测温和控制领域。

模块图(out默认接树莓派引脚7,一般选用3.3v的电源)

#####

升级内核

sudo apt-get update
sudo apt-get upgrade

修改配置

sudo nano /boot/config.txt

在末尾手动添加命令

dtoverlay=w1 -gpio -pullup,gpiopin=4
保存并重启树莓派,按ctr+X可实现退出.

确认设备是否生效

sudo modprobe w1-gpio
sudo modprobe w1-therm
cd /sys/bus/w1/devices/
ls

显示结果

在这里插入图片描述
28-0316977999cf是我的外接温度传感器设备,每个客户端显示的都不同,这个为传感器的序列号。

查看当前温度

cd 28-0316977999cf
cat w1_slave

显示结果

在这里插入图片描述
第二排最后一个即为温度值,所以当前温度为28度。

编写代码

#include <fcntl.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <wiringPi>
int ds18b20_get_temperature(float * temp)
{
    char w1_path[50] = "/sys/bus/w1/devices/";
    char buf[128];
    int fd = -1; 
    char ID[20];
    DIR *dirp;
    struct dirent *direntp;
    int found = 0;
    char *ptr;
    if (temp == NULL)
    {   
        printf("argument error");
        return -1; 
    }   

    if ( (dirp = opendir(w1_path)) == NULL)
    {   
        printf("open %s failure.\n", w1_path);  
        return -2; 
    }   

    while ( (direntp = readdir(dirp)) != NULL)
    {   
        if (strstr(direntp->d_name, "28-") != NULL)
        {   
            strncpy(ID, direntp->d_name, 20 - strlen(ID));
            found = 1;
        }  
    }
    closedir(dirp);
    
    if (found != 1)
    {
        printf("can't find ds18b20.\n");
        return -3;
    }

    strncat(w1_path, ID, sizeof(w1_path)-strlen(w1_path));
    strncat(w1_path, "/w1_slave", 50-strlen(w1_path));

    if ( (fd = open(w1_path, O_RDONLY)) < 0)
    {
        printf("open %s failure.\n", w1_path);
        return -4;
    }

    if ( read(fd, buf, sizeof(buf)) < 0)
    {
        printf("read %s failure.", w1_path);
        return -5;
    }
    close(fd);

    ptr = strstr(buf, "t=");

    if ( ptr == NULL)
    {
        printf("get temperature failure.\n");
        return -6;
    }

    *temp = atof(ptr + 2)/1000;
    return 0;
}
int main(int argc, char *argv[])
{
    float temp = 0;
    if ( ds18b20_get_temperature(&temp) < 0)
    {   
        printf("get temperature error.\n");
        return 1;
    }   
    printf("Temperature is %f C\n", temp);
    return 0;
}

summary:
温湿度模块认准18D20,由于刚开始没有看清模块的型号做了很多的无用功,切忌out口接树莓派管脚7。

猜你喜欢

转载自blog.csdn.net/weixin_45380951/article/details/100526680