天天看點

樹莓派+溫度子產品

溫度子產品(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。