Skip to content

Instantly share code, notes, and snippets.

@0x7d7b
Last active May 27, 2024 16:21
Show Gist options
  • Save 0x7d7b/b763250879f16a5de2736fd8fa3f8437 to your computer and use it in GitHub Desktop.
Save 0x7d7b/b763250879f16a5de2736fd8fa3f8437 to your computer and use it in GitHub Desktop.
Raspberry Pi Temperature Sensor

This short article describes how to connect and use a DHT22 temperature and humidity sensor on a Raspberry Pi.

Prerequisites

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.

DHT22

Wiring

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.

Installation

Since I want to use python some libraries are required. Ppython pip and libgpiod2 are required:

sudo apt install python3-pip libgpiod2

Additionally some python dependencies are required by the DHT library so you need to install them first:

sudo python3 -m pip install --upgrade pip setuptools wheel

Finally install the CircuitPython-DHT library will be installed:

sudo pip3 install adafruit-circuitpython-dht

Python Example

And 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment