Sensing the world · Lesson
10 min read
Temperature and humidity (DHT11/22)
Read a digital sensor with a library and handle failed readings.
What You Will Learn
- Use the DHT library
- Check for NaN
- Respect the sensor's sampling rate
The DHT11 and DHT22 send temperature and humidity over one data wire using their own timing protocol. The DHT library handles the details.
Arduino C++
#include <DHT.h>
DHT dht(4, DHT11);
void setup() { Serial.begin(9600); dht.begin(); }
void loop() {
float t = dht.readTemperature();
if (isnan(t)) { Serial.println("read failed"); }
else { Serial.println(t); }
delay(2000);
}| DHT11 | DHT22 | |
|---|---|---|
| Temperature | 0–50 °C, ±2 °C | −40–80 °C, ±0.5 °C |
| Humidity | 20–90 %, ±5 % | 0–100 %, ±2 % |
| Max rate | 1 reading/s | 1 reading / 2 s |
LCD thermometerarduino-uno
Note: Change temperature and humidity on the sensor. Disconnect its VCC wire to see how failures show up (NaN).
Check Your Understanding
Test what you learned in this lesson