DHT22 / AM2302: temperature and relative humidity on one wire

The DHT22 (also sold as the AM2302) measures air temperature and relative humidity (RH). A capacitive humidity sensor and a thermistor are inside the white plastic case. A small chip in the case converts the values to numbers. The chip sends the numbers to the ESP32 on one data wire with a special protocol. Each reading is a 40-bit frame: 16 bits of humidity, 16 bits of temperature and an 8-bit checksum. The sensor is slow. Read it not more than one time every 2 seconds.

The blue DHT11 uses the same protocol. It is less expensive, but it has less range and less accuracy. For more accurate data or for I²C, refer to BMP280 / BME280 and SCD41.

White AOSONG AM2302 (DHT22) sensor with a ventilation grid, on a small black module with three pins labeled plus, out and minus
AM2302 (DHT22) on a 3-pin module: + , out, −.
Photo: Suyash Dwivedi, CC BY-SA 4.0

Data line: one complete reading

Move the pointer over the trace to see the timing of each bit.

The host (ESP32) pulls the line LOW to start (shown shorter than scale). The sensor answers with 80 µs LOW + 80 µs HIGH. Then each bit starts with a 50 µs LOW. A short HIGH (about 26–28 µs) is a 0. A long HIGH (about 70 µs) is a 1. The most significant bit comes first.

ByteMeaningBits (MSB first)HexDec

How it works

One wire, two directions

The data line is open-drain: the ESP32 and the sensor can only pull it LOW. A pull-up resistor (about 10 kΩ) pulls it HIGH. The ESP32 starts a reading. Then it changes the pin to an input and measures the HIGH times of the sensor. This protocol is not the Dallas 1-Wire bus of the DS18B20.

Start and response

The host pulls the line LOW for at least 1 ms (DHT22) or at least 18 ms (DHT11). Then it releases the line for 20–40 µs. The sensor answers with 80 µs LOW and 80 µs HIGH. Then the 40 data bits come immediately. A full reading takes about 5 ms.

Bits: the HIGH time is the value

Each bit starts with a 50 µs LOW. Then the line is HIGH for 26–28 µs (0) or 70 µs (1). The library measures each HIGH time. A HIGH time that is longer than the LOW before it is a 1. This is a form of pulse-width coding, the same idea as in PWM.

Frame: 5 bytes

DHT22: bytes 1–2 are RH × 10. Bytes 3–4 are temperature × 10. The top bit of byte 3 is the sign (1 = below 0 °C). Byte 5 is the checksum: the low 8 bits of the sum of bytes 1–4. DHT11: bytes 1 and 3 are the integer parts. Bytes 2 and 4 are the decimal parts (frequently 0).

Rate limit: 2 seconds

The sensor measures again only after it sends a reading. Each frame contains the values of the previous measurement. Read the DHT22 not more than one time every 2 s (DHT11: 1 s). The Adafruit library keeps the last result and returns it when you read too fast.

Heat index and dew point

The heat index tells how hot the air feels to a person. It uses the NOAA (Rothfusz) equation and is only useful above about 27 °C. The dew point is the temperature at which water condenses from the air. Both libraries below can calculate the two values.

DHT22 and DHT11

DHT22 / AM2302DHT11
Temperature range−40 to 80 °C0 to 50 °C
Temperature accuracy±0.5 °C, resolution 0.1 °C±2 °C, resolution 1 °C
Humidity range0–100 %RH20–90 %RH
Humidity accuracy±2 %RH typical (±5 %RH max)±5 %RH
Fastest sample rate1 reading / 2 s1 reading / 1 s
Start pulse from host≥ 1 ms LOW≥ 18 ms LOW
Supply voltage3.3–6 V (datasheet)3.3–5.5 V
Case colorWhiteBlue

The values are from the Aosong datasheets. Other sellers give slightly different numbers. Your library must know the model, because the byte format is different.

Wiring

ESP32 3V3 GPIO 4 GND DHT22 front view, pins down 1 VCC 2 DATA 3 NC 4 GND 10 kΩ pull-up 3.3 V data (open-drain) 3-pin module (+, out, −): the pull-up is usually on the module.
Connect the bare 4-pin sensor as shown. Pin 1 is at the left when you look at the grid with the pins down. Many 3-pin modules already have the 10 kΩ pull-up. Use 3.3 V for VCC, so the data line never goes above 3.3 V. For long wires (more than about 1 m), use a 4.7 kΩ pull-up.

Connections

DHT22 pinModule labelConnect to
1 VCC+3V3
2 DATAoutGPIO 4, with 10 kΩ to 3V3
3 NC—Not connected
4 GND−GND

The module labels and pin order are different from seller to seller. Read the silkscreen on your module. Do not use the strapping pins 0, 2, 5, 12 and 15. Refer to GPIO.

Build steps

  1. Install the librariesIn the Library Manager, install “DHT sensor library” by Adafruit. Also install “Adafruit Unified Sensor” when the IDE asks.
  2. Connect the sensorConnect VCC, DATA and GND as shown. Add the 10 kΩ pull-up if your sensor has no module board.
  3. Upload sketch 1Open the Serial Monitor at 115200 baud. Make sure that a new line comes every 2 s.
  4. Test the sensorBreathe on the sensor. The humidity must increase within some seconds.
  5. Install the sensorPut it in moving air, away from the ESP32 and the voltage regulator. These parts are warm.

Code

1 · Adafruit “DHT sensor library”

This library also needs “Adafruit Unified Sensor”. If a reading fails, the functions return NaN. Always test the result with isnan().

dht22_basic.ino


              #include "DHT.h"

              const int DHT_PIN = 4;
              DHT dht(DHT_PIN, DHT22);          // use DHT11 for the blue sensor

              void setup() {
                Serial.begin(115200);
                dht.begin();
              }

              void loop() {
                delay(2000);                    // not more than 1 reading every 2 s

                float h = dht.readHumidity();          // %RH
                float t = dht.readTemperature();       // °C (true = °F)
                if (isnan(h) || isnan(t)) {
                  Serial.println("Read failed: examine wiring and pull-up");
                  return;
                }
                float hi = dht.computeHeatIndex(t, h, false);  // false = °C
                Serial.printf("T = %.1f C  RH = %.1f %%  heat index = %.1f C\n", t, h, hi);
              }
            

2 · “DHT sensor library for ESPx” with dew point

This library by beegee_tokyo was made for the ESP8266 and ESP32. It gives an error status (timeout or checksum) and the dew point.

dht22_dewpoint.ino


              #include "DHTesp.h"

              const int DHT_PIN = 4;
              DHTesp dht;

              void setup() {
                Serial.begin(115200);
                dht.setup(DHT_PIN, DHTesp::DHT22);
              }

              void loop() {
                delay(dht.getMinimumSamplingPeriod());   // 2000 ms for the DHT22

                TempAndHumidity v = dht.getTempAndHumidity();
                if (dht.getStatus() != DHTesp::ERROR_NONE) {
                  Serial.printf("Error: %s\n", dht.getStatusString());  // TIMEOUT or CHECKSUM
                  return;
                }
                float dew = dht.computeDewPoint(v.temperature, v.humidity);
                float hi  = dht.computeHeatIndex(v.temperature, v.humidity);
                Serial.printf("T = %.1f C  RH = %.1f %%  dew point = %.1f C  heat index = %.1f C\n",
                              v.temperature, v.humidity, dew, hi);
              }
            

3 · Decode a frame yourself

The libraries do this work for you. This function shows the calculation from the simulator above. It returns false if the checksum is incorrect.

dht22_decode.ino


            // b[0..4] are the 5 bytes in the order that they arrive.
            bool decodeDHT22(const uint8_t b[5], float &tempC, float &rh) {
              uint8_t sum = b[0] + b[1] + b[2] + b[3];     // 8-bit sum: overflow is OK
              if (sum != b[4]) return false;               // checksum error: discard

              rh = ((b[0] << 8) | b[1]) / 10.0f;          // RH x 10
              int16_t raw = ((b[2] & 0x7F) << 8) | b[3];  // temperature x 10, no sign bit
              tempC = raw / 10.0f;
              if (b[2] & 0x80) tempC = -tempC;             // top bit = negative
              return true;
            }
          

Troubleshooting

Every reading is NaN (timeout)

The sensor does not answer. Make sure that DATA goes to the pin in your sketch. Make sure that the pull-up is present. Make sure that the model in the code (DHT22 or DHT11) is correct. Wait 2 s after power-on before the first reading.

Some readings fail (checksum)

A bit changed on the wire. Make the wire shorter. Use a 4.7 kΩ pull-up for long wires. Keep the wire away from motor and relay wires. Read less frequently. Ignore one failed reading and use the next good reading.

The temperature is too high

The sensor measures its own air. Heat from the ESP32, the Wi-Fi radio and the regulator increases the value. Put the sensor 5 cm or more away from the board. Do not put it in a closed box without vent holes.

The values do not change

You read faster than every 2 s. The library then returns the last result, and the sensor shows old data. Increase the delay to 2000 ms or more.

Humidity stays at 99.9 %

Water condensed on the sensor. Let the sensor dry in warm air for some hours. Do not use the DHT22 in rain or in mist.

Other timing in the sketch is late

The Adafruit library disables interrupts for about 5 ms during a reading. Usually this has no effect. If other code needs precise timing (for example, an IR receiver or an encoder), read the sensor less frequently.

Resources