树莓派+温度模块
溫度模塊(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。
總結
- 上一篇: SpringBoot异步调用方法
- 下一篇: 南航计算机考研录取分数线是国家划线,【考