Tutorial 26: DHT22 Digital Temp / Humidity Sensor

So we've spent some time taking a look at analog sensors and getting those working with our Raspberry Pi. If we don't want to use analog sensors we can use a digital sensor. Digital sensors communicate with the Pi using binary data not analog voltage levels.

There are several ways to communicate with a digital device and your Raspberry Pi. The DHT22 is a popular sensor among hobbyists for it's relative ease of use and due to it being inexpensive. In this tutorial I show you how to get your Raspberry Pi to use the DHT22 to measure temperature and humidity in Python 3. Note: The DHT22 and DHT11 and AM2302 will all work for this tutorial. The AM2302 is the DHT22 with different packaging. The DHT11 is a less expensive (and less accurate) version of the DHT22.

This tutorial is a little older (published in 2015!). The main principles are still relevant, so I haven't needed to update this lesson.

  • How to build a circuit around a DHT22 and connect it to your Raspberry Pi
  • How to pull temperature and humidity values from the DHT22
You can copy / paste the code below if you’re having issues with typos or want a shortcut. However I recommend that you follow along in the tutorial to understand what is going on!

Remember to start the daemon with the command
'sudo pigpiod' before running this script. It
needs to be restarted every time your pi
is restarted.

import pigpio
import DHT22
from time import sleep

# Initiate GPIO for pigpio
pi = pigpio.pi()
# Setup the sensor
dht22 = DHT22.sensor(pi, 27) # use the actual GPIO pin name

# We want our sleep time to be above 2 seconds.
sleepTime = 3

def readDHT22():
    # Get a new reading
    # Save our values
    humidity  = '%.2f' % (dht22.humidity())
    temp = '%.2f' % (dht22.temperature())
    return (humidity, temp)

while True:
    humidity, temperature = readDHT22()
    print("Humidity is: " + humidity + "%")
    print("Temperature is: " + temperature + "C")

The PIGPIO files can be found below: