树莓派读取 DHT11 温湿度传感器温湿度数值。常用的四种方法,1.系统功能直读、2.使用Adafruit库读取、3.用Python 编程来读取、4.C语言编程读取, 本次教程主要使用C语言读取。
工作电压:3.3v-5v
检测温度范围:±5%RH (0~50°C)
检测湿度范围:1%RH(20%RH ~ 90%RH (25°C)
在开始之前务必先给系统安装好wiringPi库,如果你的树莓派系统还没有安装wiringPi库,可参考这个教程➦树莓派安装wiringPi库
DHT11温湿度传感器 | 树莓派开发板 |
VCC | 5V |
GND | GND |
OUT | GPIO7(wiringPi 7) |
DHT11传感器原理图 | DHT11资料 |
输入命令 新建一个dht11.c程序文件。
sudo nano dht11.c将下列C代码程序粘贴到文件内
#derived from raspi.cc #include <wiringPi.h> #include <stdio.h> #include <stdlib.h> typedef unsigned char uint8; typedef unsigned int uint16; typedef unsigned long uint32; #define HIGH_TIME 32 int pinNumber = 7; uint32 databuf; uint8 readSensorData(void) { uint8 crc; uint8 i; pinMode(pinNumber, OUTPUT); // set mode to output digitalWrite(pinNumber, 0); // output a high level delay(25); digitalWrite(pinNumber, 1); // output a low level pinMode(pinNumber, INPUT); // set mode to input pullUpDnControl(pinNumber, PUD_UP); delayMicroseconds(27); if (digitalRead(pinNumber) == 0) //SENSOR ANS { while (!digitalRead(pinNumber)) ; //wait to high for (i = 0; i < 32; i++) { while (digitalRead(pinNumber)) ; //data clock start while (!digitalRead(pinNumber)) ; //data start delayMicroseconds(HIGH_TIME); databuf *= 2; if (digitalRead(pinNumber) == 1) //1 { databuf++; } } for (i = 0; i < 8; i++) { while (digitalRead(pinNumber)) ; //data clock start while (!digitalRead(pinNumber)) ; //data start delayMicroseconds(HIGH_TIME); crc *= 2; if (digitalRead(pinNumber) == 1) //1 { crc++; } } return 1; } else { return 0; } } int main(void) { printf("PIN:%d\n", pinNumber); if (-1 == wiringPiSetup()) { printf("Setup wiringPi failed!"); return 1; } pinMode(pinNumber, OUTPUT); // set mode to output digitalWrite(pinNumber, 1); // output a high level printf("Starting...\n"); while (1) { pinMode(pinNumber, OUTPUT); // set mode to output digitalWrite(pinNumber, 1); // output a high level delay(3000); if (readSensorData()) { printf("Sensor data read ok!\n"); printf("RH:%d.%d\n", (databuf >> 24) & 0xff, (databuf >> 16) & 0xff); printf("TMP:%d.%d\n", (databuf >> 8) & 0xff, databuf & 0xff); databuf = 0; } else { printf("Sensor dosent ans!\n"); databuf = 0; } } return 0; }如下图:粘贴好后按Ctrl+X选择y 保存即可
然后编译程序
gcc -Wall -o dht11 dht11.c -lwiringPi运行程序
sudo ./dht11
查看效果如下:湿度74% 温度34.2摄氏度