Lesson 1.6: Temperature and humidity
The DHT11 is the simplest sensor to start measuring your surroundings: a single data wire and a library that does all the work.
Parts
Libraries
- DHT sensor library
- Adafruit Unified Sensor
How it works
Inside there's a capacitive humidity sensor, a thermistor and a small microcontroller that calibrates the readings and sends them as digital data.
It uses its own single-wire protocol: the Arduino requests a reading by pulling the line LOW for a few milliseconds, and the sensor replies with 40 bits —humidity, temperature and a checksum— encoded in the length of each pulse.
It's a slow sensor: it allows no more than one reading per second, and each one reflects the air of a couple of seconds ago. If you need more accuracy or range there's the DHT22, which is programmed the same way.
Specifications
- Temperature
- 0–50 °C, ±2 °C
- Humidity
- 20–90 %, ±5 %
- Readings
- one per second at most
- Supply
- 3.3–5 V
Wiring
| Component | Connects to | Note |
|---|---|---|
| DHT11, VCC (+) | 5V | |
| DHT11, DATA (S) | Pin 2 | |
| DHT11, GND (−) | GND |
Code
// Reads temperature and humidity every two seconds.
#include <DHT.h>
const int DHT_PIN = 2;
DHT dht(DHT_PIN, DHT11);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(2000); // the DHT11 needs time between readings
float humidity = dht.readHumidity();
float celsius = dht.readTemperature();
if (isnan(humidity) || isnan(celsius)) {
Serial.println("Read error");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" % Temperature: ");
Serial.print(celsius);
Serial.println(" °C");
}What the code does
- DHT dht(DHT_PIN, DHT11); creates the sensor with its pin and model. For a DHT22, just change DHT11 to DHT22.
- readTemperature() returns degrees Celsius; readTemperature(true), degrees Fahrenheit.
- isnan() catches a failed reading: the library returns NaN —«not a number»— when the sensor doesn't answer or the data doesn't add up.
- The delay(2000) sits at the start of loop() so the sensor also gets time right after power-up.
Step by step
- Install «DHT sensor library», by Adafruit, from the library manager. If it asks about dependencies, install «Adafruit Unified Sensor» as well.
- Wire the module following the table.
- Upload the code and open the serial monitor at 9600 baud.
- Breathe on the sensor and watch the humidity rise.
Result
Humidity and temperature appear every two seconds. When you breathe on it, the humidity rises within a few seconds.
If it doesn't work
- If you only get «Read error», check the data wire and that the model in the code —DHT11 or DHT22— matches yours.
- If you're using the bare four-legged sensor, it's missing the 10 kΩ resistor between DATA and VCC; the third leg isn't connected.
- Reading more than once per second returns errors or the same value over and over.