In this Raspberry Pi humidity sensor tutorial, we will show you how to connect the DHT22 sensor to the Raspberry Pi and how you can use Python to read data from the sensor.

Raspberry Pi Humidity Sensor

The DHT22 is a versatile and low-cost humidity sensor that can also calculate the temperature of an area.

This sensor has a relatively long transmission distance, allowing the sensor to transmit data through wires up to 20m away from the Raspberry Pi.

As a bonus, the DHT22 is a digital sensor with an inbuilt analog to digital converter. The converter makes it a lot easier to connect the sensor to the Raspberry Pi as you do not need to deal with any additional chips.

The biggest downside to the DHT11 and DHT22 sensors is that they are quite slow sensors. They have a sampling rate of once every second for the DHT11 and once every 2 seconds for the DHT22.

You can also use the DHT22 with the Arduino, so be sure to check that tutorial if you would rather use an Arduino board.

While this tutorial covers connecting the DHT22 to the Raspberry Pi, it will also work with the DHT11 and AM2302 humidity sensors as they all use the same pinouts.

Equipment

Below is all the equipment that you will need for connect the DHT22 Humidity Sensor to your Raspberry Pi.

Recommended

Raspberry Pi

8GB SD Card or Micro SD Card if you’re using a Raspberry Pi 2, 3 or B+

Breadboard wire

DHT22 Humidity Sensor

10k ohm resistor (Brown, Black, Orange, Gold)

Optional

Raspberry Pi Case

Video

The video below will take you through the steps to assembling the humidity circuit and how to connect it to your Raspberry Pi. It also covers the steps on how to write a simple Python script to talk with the DHT22 sensor.

If you prefer a written tutorial. then you can find that right underneath the video.

Can’t see the video? Support us by disabling your adblocker.

Raspberry Pi Humidity Sensor Hardware Setup

In this section of the tutorial, we will show you the process on how to connect your DHT22 humidity sensor to the Raspberry Pi.

Thanks to the DHT22 being a digital sensor, it is incredibly straightforward to connect to the Raspberry Pi. The single data pin is able to connect directly to the Raspberry Pi’s GPIO pins.

You can follow our guide below to see how to connect the DHT22 to your Raspberry Pi.

DHT22 Pinout

To make things easier when assembling the humidity sensor circuit we have included the pinout of the DHT22 sensor.

This diagram should help you work out where each pin needs to go on the Raspberry Pi.

  • Pin 1 is VCC (Power Supply)
  • Pin 2 is DATA (The data signal)
  • Pin 3 is NULL (Do not connect)
  • Pin 4 is GND (Ground)

DHT22 Temperature Sensor with numbering

Raspberry Pi DHT22 Circuit

Here we have included a couple of ways you can put the Raspberry Pi Humidity sensor circuit together.

You can either rely on our two diagrams below to see what pins need to go to what or use our written steps below.

  • Place a 10k resistor between Pin 1 and Pin 2 of the DHT22
  • Wire Pin 1 of the DHT22 to Physical Pin 1 (3v3) on the Pi
  • Wire Pin 2 of the DHT22 to Physical Pin 7 (GPIO4) on the Pi
  • Wire Pin 4 of the DHT22 to Physical Pin 6 (GND) on the Pi

Raspberry Pi Humidity Sensor DHT22 Wiring Schematic

Raspberry Pi Humidity Sensor DHT22 GPIO Pins

Preparing the Raspberry Pi to talk with the Humidity Sensor

1. Before we get started with programming a script for the Raspberry Pi humidity sensor, we must first ensure that we have the latest updates on our Raspberry Pi.

We can do this by running the following two commands to update both the package list and installed packages.

sudo apt-get update
sudo apt-get upgrade

2. With our package list now up to date, we need to go ahead and install both python 3 and pip. We will be using both of these packages to interact with our humidity sensor.

Install both python3-dev and python3-pip by running the command below.

sudo apt-get install python3-dev python3-pip

3. Before we go ahead and install the DHT library, we should first run the following command to ensure we have the latest versions of the setuptools, wheel and pip python packages.

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

4. Now using pip, we will go ahead and install Adafruit’s DHT library to the Raspberry Pi.

We will be using this Python library to interact with our DHT22 Humidity/Temperature sensor.

As a bonus, the library also supports the DHT11 and AM2302 humidity/temperature sensors making it a great library to learn how to utilize.

Run the following command to install the DHT library to your Raspberry Pi.

sudo pip3 install Adafruit_DHT

5. In the next section of our Raspberry Pi humidity sensor tutorial, we will show you how you can put this library to use and utilize it within a python script to talk with the DHT22 sensor.

Programming for the Raspberry Pi humidity sensor

1. Now that we have installed the Adafruit DHT library to our Raspberry Pi we can now proceed to program with it.

First, we must make a Python script in which we will store all our code. To begin writing this file, you can enter the following command into your Raspberry Pi.

nano ~/humidity.py

2. Within this file, we need to enter the following lines of code. We will explain each section of the code as we go along.

import Adafruit_DHT

This line imports the “Adafruit_DHT” library that we obtained using pip in the previous section.

We will be using this library to talk and interact with the DHT22 sensor. The library allows us to very easily retrieve the temperature and humidity from the sensor with a few lines of python code.

DHT_SENSOR = Adafruit_DHT.DHT22

On this line, we define a constant for the sensor that we want to utilize for the DHT Library. The Adafruit DHT library has three choices that you can choose from depending on the sensor used.

For this tutorial, we are making use of the DHT22, so we defined our “DHT_SENSOR” constant as “Adafruit_DHT.DHT22“.

If you are following this guide but are using either the DHT11 or the AM2302 you can use either “Adafruit_DHT.DH11” or “Adafruit_DHT_AM2302” respectively.

DHT_PIN = 4

Next, we define a constant called “DHT_PIN” this is to store the number of the GPIO pin that the DHT22 is plugged into on the Raspberry Pi.

The number we use refers to the BCM numbering of the GPIO pins. In our tutorials case, this means we need to use the number “4” as we utilized the GPIO4 pin for our data connection.

If you utilized a different GPIO pin, then make sure you update this number accordingly.

while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

Next, we start up an infinite loop by using the “while TRUE:” code. This loop will continually run until a user kills the Python script.

At the start of every loop, we utilize the Adafruit DHT library to retrieve both the humidity and temperature from the DHT22 sensor, specifying both our DHT_SENSOR and DHT_PIN constant.

The “read_retry” function will continually try to retrieve the data from the humidity sensor.

if humidity is not None and temperature is not None:
        print("Temp={0:0.1f}*C  Humidity={1:0.1f}%".format(temperature, humidity))
    else:
        print("Failed to retrieve data from humidity sensor")

Finally, we check to ensure that the DHT library returned data that is useful to us.

If either the “humidity” or “temperature” variables are “None” then we return a message telling the end user that we failed to retrieve data from our humidity sensor.

If we did have values in both of those variables, then we print out a message showing the end user both the temperature and the humidity that we just retrieved from our humidity sensor.

3. Once you have finished entering the code, it should look like what we have displayed below.

import Adafruit_DHT

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

    if humidity is not None and temperature is not None:
        print("Temp={0:0.1f}*C  Humidity={1:0.1f}%".format(temperature, humidity))
    else:
        print("Failed to retrieve data from humidity sensor")

4. When you are happy that all the code you entered is correct you can then save the file by pressing CTRL + X, then Y followed by ENTER.

5. With the script now saved, let’s go ahead and run it so that we can start to see the data from the humidity sensor.

You can run this script by running the following command.

python3 ~/humidity.py

6. From this command, you should start seeing results like what we have below. The temperature and the humidity should be displayed through the command line.

Temp=25.6*C  Humidity=51.8%
Temp=25.2*C  Humidity=45.4%
Temp=25.1*C  Humidity=45.4%
Temp=25.0*C  Humidity=45.3%

7. In the next section of the tutorial, we will show you how you can modify this script so that it logs the data to a file. The file will be able to be read by a program such as Microsoft Excel or Google Spreadsheets.

Logging the Data from the Raspberry Pi Humidity Sensor

1. Let’s start by creating a new script. This script will be somewhat similar to our previous script but with a few changes made so that we can write to a file.

Start by running the following command to begin writing our new script.

nano ~/humidity_logger.py

2. Within this file enter the following lines. We will only be explaining the new additions to the script in this section.

import os
import time
import Adafruit_DHT

Here we add the import for both the “os” and “time” libraries. We utilize the “os” library so we can check if our CSV file exists before we try to write to it.

We use the “time” library so that we can timestamp each new row with the current date and time.

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

There is no difference with these two lines, keep them as you had in the previous script.

try:
    f = open('/home/pi/humidity.csv', 'a+')
    if os.stat('/home/pi/humidity.csv').st_size == 0:
            f.write('Date,Time,Temperature,Humidity\r\n')
except:
    pass

Here we wrap everything within a try statement to handle any potential errors.

We open up a handle to our “/home/pi/humidity.csv” file with the “a+” tag applied. Thea+ tag means that any data written to the file will be appended to the end of it.

Next, we use the “os” library to see if we have ever written to this file before. If the size returns as 0 we then write an initial line to the file. This line will contain our column headers so you can understand the data easier.

while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

Here we have our while loop again. We utilize the DHT Library to read data from our DHT22 humidity sensor again.

This function will store the data it reads from the sensors into our “humidity” and “temperature” variables.

if humidity is not None and temperature is not None:
        f.write('{0},{1},{2:0.1f}*C,{3:0.1f}%\r\n'.format(time.strftime('%m/%d/%y'), time.strftime('%H:%M'), temperature, humidity))  
    else:
        print("Failed to retrieve data from humidity sensor")

    time.sleep(30)

Our big change to this section of code is that instead of printing the temperature and humidity to the console, we write it to our “humidity.csv” file. We do this by using the file handle we opened earlier.

We format the text written to the file to include both the current date, current time, our formatted temperature and humidity.

At the end of the loop, we sleep the script for 30 seconds, if you want to make it sleep longer or poll more often then modify this number.

3. Once you have finished entering the code, it should look like what we have displayed below.

import os
import time
import Adafruit_DHT

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

try:
    f = open('/home/pi/humidity.csv', 'a+')
    if os.stat('/home/pi/humidity.csv').st_size == 0:
            f.write('Date,Time,Temperature,Humidity\r\n')
except:
    pass

while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

    if humidity is not None and temperature is not None:
        f.write('{0},{1},{2:0.1f}*C,{3:0.1f}%\r\n'.format(time.strftime('%m/%d/%y'), time.strftime('%H:%M'), temperature, humidity))
    else:
        print("Failed to retrieve data from humidity sensor")

    time.sleep(30)

4. Once done, save the file by pressing CTRL + X, then Y followed by ENTER.

5. Now like our last script lets go ahead and now run it by entering the following command.

python3 ~/humidity_logger.py

6. Once you exit out of the script, you will now be able to check out the “humidity.csv” file to see all the results that you have logged over time.

If you run the following command, you should see the contents of the file.

nano ~/humidity.csv

7. Below is an example of the contents that you should see within this file.

Date,Time,Temperature,Humidity
05/04/19,05:47,22.3*C,50.6%
05/04/19,05:48,22.2*C,50.4%
05/04/19,05:48,22.2*C,50.6%
05/04/19,05:49,22.2*C,50.4%
05/04/19,05:49,22.2*C,50.4%
05/04/19,05:50,22.2*C,50.3%
05/04/19,05:50,22.2*C,50.3%
05/04/19,05:51,22.2*C,50.2%

Once you have verified that the file is successfully being written, then you are finally done with programming your Raspberry Pi humidity sensor.

If you need a waterproof temperature sensor, then be sure to check out our DS18B20 temperature sensor tutorial. It covers everything you need to know, and it works perfectly alongside this sensor.

I hope that everything has worked correctly for you and you’re not collecting the humidity and temperature without issues. If you want to leave some feedback, then please don’t hesitate to leave a comment below.

Ultimate Books of Pi Bottom
Get projects delivered to your inbox weekly.