This short article describes how to connect and use a DHT22 temperature and humidity sensor on a Raspberry Pi.
I bought a sensor kit from AZ-Delivery. It is easy connect as no soldering work is required. In case you need more details they offer a free DHT22 ebook download.
Note that in their ebook they recommend to use the Adafruit_DHT library. Since that one is deprecated you need to use the CircuitPython-DHT library instead. Details below.
The sensor has three pins: +5V, GND and OUT. They say that +3.3V is also supported but might result in less accurate results.
For the following description I assume that the sensors OUT pin is connected to GPIO4 on your RPi.
Since I want to use python some libraries are required. Ppython pip and libgpiod2 are required:
sudo apt install python3-pip libgpiod2Additionally some python dependencies are required by the DHT library so you need to install them first:
sudo python3 -m pip install --upgrade pip setuptools wheelFinally install the CircuitPython-DHT library will be installed:
sudo pip3 install adafruit-circuitpython-dhtAnd here is a small example script called dht22.py that reads data from the sensor:
import time
import adafruit_dht
# Using GPIO4
dhtDevice = adafruit_dht.DHT22(4)
while True:
try:
t = dhtDevice.temperature
h = dhtDevice.humidity
print("{:.1f}°C / {}%".format(t, h))
except RuntimeError as error:
print(error.args[0])
time.sleep(2.0)The sensor sends data every two seconds. So that script reads the data every two seconds and prints the results to the terminal:
$ python3 dht22.py
25.8°C / 44.4%
25.9°C / 44.4%
25.9°C / 44.4%
25.9°C / 44.4%
Checksum did not validate. Try again.
25.9°C / 44.4%It is a good idea to read the data within a try-except block since every now and then it fails with the checksum error message above. Just re-read and everything is fine.

