Raspberry Pi: DHT11/DHT22 Temperature and Humidity (Python)

Learn how to interface the DHT11 and DHT22 digital temperature sensors with the Raspberry Pi to get temperature and humidity readings. You’ll learn how to connect the sensors to the Raspberry Pi, include the required libraries, and write a Python script that displays the current temperature and humidity on the shell/terminal.

Raspberry Pi with DHT11 DHT22 Getting Temperature and Humidity Python

Table of Contents

Throughout this tutorial, we’ll cover the following main topics:

Prerequisites

Before continuing with this tutorial, check the following prerequisites.

  1. Get familiar with the Raspberry Pi board—if you’re not familiar with the Raspberry Pi, you can read our Raspberry Pi Getting Started Guide here.
  2. You must know how to run and create Python files on your Raspberry Pi. We like to program our Raspberry Pi via SSH using an extension on VS Code. We have a detailed tutorial about that subject: Programming Raspberry Pi Remotely using VS Code (Remote-SSH).
  3. Know how to use the Raspberry Pi GPIOs so that you know how to wire the circuit properly. Read the following tutorial: Raspberry Pi Pinout Guide: How to use the Raspberry Pi GPIOs?

Introducing DHT11/DHT22 Sensors

The DHT11 and DHT22 sensors are used to measure temperature and relative humidity. These are very popular among makers and electronics hobbyists.

DHT11/DHT22 Temperature and Humidity Sensors

These sensors contain a chip that does analog to digital conversion and spit out a digital signal with the temperature and humidity. This makes them very easy to use with any microcontroller.

DHT11 vs DHT22

The DHT11 and DHT22 are very similar but differ in their specifications. The following table compares some of the most important specifications of the DHT11 and DHT22 temperature and humidity sensors. For a more in-depth analysis of these sensors, please check the sensors’ datasheet.

DHT11
DHT22
Temperature range0 to 50 ºC +/-2 ºC-40 to 80 ºC +/-0.5ºC
Humidity range20 to 90% +/-5%0 to 100% +/-2%
ResolutionHumidity: 1%
Temperature: 1ºC
Humidity: 0.1%
Temperature: 0.1ºC
Operating voltage3 – 5.5 V DC3 – 6 V DC
Current supply0.5 – 2.5 mA1 – 1.5 mA
Sampling period1 second2 seconds
Price$1 to $5$4 to $10
Where to buyCheck pricesCheck prices

The DHT22 sensor has a better resolution and a wider temperature and humidity measurement range. However, it is a bit more expensive, and you can only request readings with 2 seconds interval.

The DHT11 has a smaller range and it’s less accurate. However, you can request sensor readings every second. It’s also a bit cheaper.

Despite their differences, they work in a similar way, and you can use the same code to read temperature and humidity. You just need to select in the code the sensor type you’re using.

DHT Pinout

DHT sensors have four pins as shown in the following figure. However, if you get your DHT sensor in a breakout board, it comes with only three pins and with an internal pull-up resistor on pin 2.

DHT22 Temperature and Humidity Sensor using Arduino IDE

The following table shows the DHT22 and DHT11 pinout. When the sensor is facing you, pin numbering starts at 1 from left to right

DHT pinConnect to
13.3V
2Any digital GPIO; also connect a 4.7k Ohm pull-up resistor
3Don’t connect
4GND

DHT Sensor Breakout Board

If you got a DHT11 or DHT22 sensor on a breakout board, they only come with three pins and have an internal pull-up resistor on the data pin.

DHT22 sensor

In this case, wiring is even simpler and you don’t need to wire an external resistor. The DHT breakout boards usually have labels on the pins: GND, VCC, and DATA.

DHT pinConnect to
GNDGND
VCC3V3 (OUT)
DATGPIO 4 (or any other digital pin)

Parts Required

Raspberry Pi with DHT22 Circuit

Here’s a list of parts you need to build the circuit (if you don’t have a DHT breakout board, you need a 4.7kOhm resistor):

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Wiring the DHT11/DHT22 Sensor to the Raspberry Pi

Wire the DHT22 or DHT11 sensor to the Raspberry Pi as shown in the following schematic diagram. If you have a DHT breakout board, ignore the resistor.

Raspberry Pi DHT Sensor Wiring

In this example, we’re connecting the DHT data pin to GPIO 4. However, you can use any other suitable digital GPIO. Learn more about the Raspberry Pi GPIOs here.

Getting DHT11/22 Temperature and Humidity

There are different ways to get temperature and humidity readings from the DHT11 or DHT22 sensors using the Raspberry Pi with Python. We’ll use the Adafruit_DHT Python library.

Installing the Adafruit_DHT Library

Open a Terminal window on your Raspberry Pi and run the following command to install the library:

sudo pip3 install Adafruit_DHT
Install DHT Library on the Raspberry Pi

If you get an error regarding not having PIP installed, you need to run the following two commands and then try to install the library again.

sudo apt-get install python3-dev python3-pip
sudo python3 -m pip install --upgrade pip setuptools wheel

Python Code for Raspberry Pi DHT11/DHT22

The following script gets temperature and humidity from the DHT sensors and prints the readings on the Python shell. Create a new Python file with a name of your choice, for example, dht_basic.py, and copy the following code.

# Complete Project Details: https://RandomNerdTutorials.com/raspberry-pi-dht11-dht22-python/

import Adafruit_DHT
import time

# comment and uncomment the lines below depending on your sensor
sensor = Adafruit_DHT.DHT22
# sensor = Adafruit_DHT.DHT11

# DHT pin connects to GPIO 4
sensor_pin = 4

while True:
    humidity, temperature = Adafruit_DHT.read_retry(sensor, sensor_pin)  # Use read_retry to retry in case of failure
    if humidity is not None and temperature is not None:
        # Uncomment the line below to convert to Fahrenheit
        temperatureF = temperature * 9/5.0 + 32
        print("Temp={0:0.1f}ºC, Temp={1:0.1f}ºF, Humidity={2:0.1f}%".format(temperature, temperatureF, humidity))
    else:
        print("Sensor failure. Check wiring.")
    time.sleep(3)

View raw code

How the Code Works

Continue reading to learn how the code works, or skip to the Demonstration section.

Importing libraries

Start by importing the required libraries: the Adafruit_DHT, that you installed previously, to get readings from the sensors, and the time module to add delays to our code.

import Adafruit_DHT
import time

DHT Sensor Type

On the following lines, you should select the DHT sensor you’re using, either DHT11 or DHT22. You should comment/uncomment the appropriate lines. I’m using a DHT22, so it looks as follows:

sensor = Adafruit_DHT.DHT22
# sensor = Adafruit_DHT.DHT11

If you’re using a DHT11, it should be like this:

# sensor = Adafruit_DHT.DHT22
sensor = Adafruit_DHT.DHT11

Sensor Pin

The following line defines the sensor pin that the DHT data pin is connected to. In our case, we’re connecting to GPIO 4. Adjust that line if you’re using a different GPIO number.

# DHT pin connects to GPIO 4
sensor_pin = 4

While loop

Then, we have a loop that keeps the program running indefinitely, until you stop the program. Inside the loop we’ll read the sensor and display the readings.

while True:

Reading Temperature and Humidity

Getting temperature and humidity is as easy as using the read_retry() function from the library. This function accepts as arguments, the DHT sensor type and the pin. It returns the humidity and temperature readings that we save in the humidity and temperature variables.

humidity, temperature = Adafruit_DHT.read_retry(sensor, sensor_pin)  # Use read_retry to retry in case of failure

Note: there is also another function called read(), but we prefer to use the read_retry() because this one automatically retries getting new readings if the initial attempt fails.

Then, we check if we have valid temperature humidity and temperature readings with the following line:

if humidity is not None and temperature is not None:

By default, it will get the temperature in Celsius degrees. We add a line to convert it to Fahrenheit degrees.

temperatureF = temperature * 9/5.0 + 32

If we have valid readings, we’ll display them on the shell using the print() function.

print("Temp={0:0.1f}ºC, Temp={1:0.1f}ºF, Humidity={2:0.1f}%".format(temperature, temperatureF, humidity))

Formatting the printing output

Temp={0:0.1f}ºC, Temp={1:0.1f}ºF, Humidity={2:0.1f}%: This is the format string that defines how the output will be displayed. The format string contains placeholders indicated by curly braces {} that will be filled in with actual values using the .format() method.

Temp={0:0.1f}ºC indicates the placeholder for the first value (temperature). It specifies how the value will be formatted:

  • {0}: This specifies the index of the value to be inserted (0 refers to the first value provided to the .format() method).
  • :0.1f: This is a formatting specification that specifies how the value should be displayed. The 0 represents the minimum number of digits, and the .1f means that it will display the value as a floating-point number with one digit after the decimal point.

Temp={1:0.1f}ºF: This part of the format string follows the same structure as above but refers to the second value (temperatureF).

Humidity={2:0.1f}%: This part of the format string refers to the third value (humidity).

Finally, .format(temperature, temperatureF, humidity) inserts the actual values into the placeholders within the format string. The values provided in the parentheses are inserted into the placeholders according to their respective indexes (0, 1, 2).

If we can’t get valid temperature and humidity readings, we print a message on the shell.

else:
    print("Sensor failure. Check wiring.")

We get new temperature readings every three seconds. You can adjust the delay time by changing the argument of the sleep() method.

time.sleep(3)

Demonstration

Save your Python file. Then run it on your Raspberry Pi. Run the following command:

python dht-basic.py

You should get new temperature and humidity readings on the Python Shell or on the Raspberry Pi Terminal every three seconds.

Raspberry Pi Print Temperature and Humidity DHT22 DHT11 Sensor

You can stop the execution of the program by pressing CTRL+C.

Wrapping Up

In this tutorial, you learned how to interface the DHT11 and DHT22 digital temperature and humidity sensors with the Raspberry Pi and how to write a Python program to get and display readings. This is one of the most basic projects to get you started with the DHT11 or DHT22 sensor.

We hope you found this tutorial useful. If you’re a beginner to the Raspberry Pi, you can get started with the following tutorials:

You can check all our Raspberry Pi projects on the following link:

Finally, if you would like to interface the DHT11/22 sensor with other microcontrollers, we have tutorials for ESP32, ESP8266, and Arduino:

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

4 thoughts on “Raspberry Pi: DHT11/DHT22 Temperature and Humidity (Python)”

  1. Hi Sara, can you develop tutorials on how to interface a force Sensor FSR402 or better sensor on esp32 or esp8266. For the measurement of power on a bike crank. Mahen.

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.