要使用DH11需要先下载DH11的函数库,打开Arduino后,管理库,在搜索 DH11 即可搜索到 DHT_sensor_library。
打开示例 DHTtester ,编译上传,会发现一个错误,大致意思是缺少 Adafruit_Sensor.h 这个头文件,可在 https://github.com/adafruit/Adafruit_Sensor 此处下载。
将下载后的压缩包解压后,找到 Adafruit_Sensor.h 文件,复制到 库文件夹 DHT_sensor_library 下即可,重新打开 Arduino后,编译就没有错误了。
上传之后可以看到 湿度,C温度,F温度,体感C温度,体感F温度。
示例代码如下:
// Written by ladyada, public domain
// 导入头文件
#include "DHT.h"
// 定义OUT接口的数字引脚
#define DHTPIN 2 // what digital pin we're connected to
// Uncomment whatever type you're using!
// 选择DHT类型为 DHT 11
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
// 生成 DHT 对象,参数是PIN和DHT类型
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
// 必须使用的begin()函数
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
// 每次等待2秒后再输出(这里必须等大于1秒,不然不准确)
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
// readHumidity() 这里是读取当前的湿度
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
// readTemperature() 读取当前的温度,单位C
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
//readTemperature(true) 读取当前的温度,单位F
float f = dht.readTemperature(true);
// 如果读取失败则退出,再读取一次
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index in Fahrenheit (the default)
// 读取体感温度,单位F
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
// 读取体感温度,单位C
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
}
网友评论