Measure Temperature and Humidity with DHT11/DHT22 Sensor

With very little knowledge and effort, it is easy to measure the temperature and humidity using a sensor. Sensors such as the DHT11 and DHT22 are affordable, accurate and can measure both temperature and humidity.

Equipment List

To make this tutorial easier, we will be using a DHT11/DHT22 with PCB. Therefore there is no need to use a 10kΩ resistor.

  • Raspberry Pi 3B/3B+ recommended
  • DHT11 or DHT22 humidity sensor
  • Jumper Wires

You can see the difference between the DHT11 and DHT22 here. In short, the DHT11 is cheaper, but the DHT22 is more precise and lasts longer. For applications in areas where accuracy and reliability is more important, the DHT22 should be used. Personally, we think the DHT22 should be used wherever possible as its only slightly more expensive.

Setting up the Hardware


The left pin of the sensor is connected to 3V3 of Pi (pin1), the second pin on the sensor is connected to a free GPIO pin on the raspberry (GPIO26, pin37) and the right pin of the sensor goes to GND (Pin9) on the Pi. The setup is identical for both DHT11 and DHT22 since the pins are assigned the same way.

Getting Readings from the Sensor on the Raspberry Pi

Before continuing, the below steps assume your Pi has Raspbian installed and is connected to the internet. If you haven’t done this yet, please follow the steps here.

We need to install some packages:

sudo apt-get update 
sudo apt-get install build-essential python-dev python-openssl git

Now we need the library for the sensors. We use a pre-built Adafruit library that supports the DHT11 and DHT22:

cd /home/pi
git clone https://github.com/adafruit/Adafruit_Python_DHT.git && cd Adafruit_Python_DHT 
sudo python setup.py install

This creates the Adafruit Python library that we can easily integrate into our projects. If everything went well, we should be able to read the temperature and humidity. Let’s test our setup with the example script provided by Adafruit. The first parameter (22) indicates which sensor we are using (11 if you are using the DHT11) and the second is which GPIO it is connected to (not the pin number, but the GPIO number). Run these commands:

cd examples
sudo ./AdafruitDHT.py 22 26

This produces an output like the following:

pi@how2pi:~ $ sudo ./AdafruitDHT.py 22 26
Temp=23.2*  Humidity=45.1%

Be aware: Both DHT11 and DHT22 can only read at a rate of every 2 seconds. We recommend a minimum interval of 3-5 seconds.

In order to utilise the temperature and humidity library into other Python scripts, you only need the following code:

import Adafruit_DHT
...
sensor = Adafruit_DHT.DHT11
pin = 4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
...

Leave a Comment