DHT22: Humidity and Temperature Sensor

Posted on 2019-11-10 by me

The DHT22 is a popular digital humidity and temperature sensor. A nice little tutorial is available from Adafruits, complete with code and some specs.

  • 3 to 5V power and I/O
  • 2.5mA max current use during conversion (while requesting data)
  • Good for 0-100% humidity readings with 2-5% accuracy
  • Good for -40 to 80°C temperature readings ±0.5°C accuracy
  • No more than 0.5 Hz sampling rate (once every 2 seconds)
  • Body size 15.1mm x 25mm x 7.7mm
  • 4 pins with 0.1” spacing

A full pdf manual is here if needed. And adafruit also provide drivers.

Of the four pins, reading left to right (with the grill facing up)

  1. VCC (power)
  2. Data out
  3. Not connected
  4. Ground

It should work on 3.3V but if this isn’t enough, then switch to 5V.

Wiring up

  1. Insert the DHT22 into 4 adjacent columns of the breadboard.
  2. Reading left to right, in the first connect the 3.3V on the RPi (failing this change to 5V) to pin 1.
  3. Between the first and second, add a 10kOhm resistor ie the pull-up.
  4. Attach a GPIO pin to the second column. (We use pin 4 which is referenced in the code.)
  5. Ground the forth.

Note : using jump cables on the DHT22 pins led to temperamental connection.

Software

A little python script queries the sensor, prints a reading if it exists, else prints an error. It runs indefinitely, and sleeps between query attempts. This is a minor adaptation of code found here.

Requirements: Adafruit_DHT

import time
import Adafruit_DHT

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 11 # GPIO pin number used.

print("Begin. Using pin", DHT_PIN) 
while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    t = time.strftime('%Y-%m-%d %H:%M:%S %Z', time.gmtime())
    if humidity is not None and temperature is not None:
        print("{0} Temp={1:0.1f}*C  Humidity={2:0.1f}%".format(t, temperature, humidity))
    else:
        print("{} Failed to retrieve data from humidity sensor".format(t))
    time.sleep(3) 

Example output:

2019-11-10 11:59:16 GMT Temp=20.3*C  Humidity=52.4%
2019-11-10 11:59:19 GMT Temp=20.3*C  Humidity=52.4%
2019-11-10 11:59:25 GMT Temp=20.3*C  Humidity=52.4%