DHT11 Sensor With Raspberry PI and Python

4.7
(19)

Last Updated on 9th November 2024 by peppe8o

I will show you how to interface a Raspberry PI with a DHT11 Sensor using Python in this article.

Getting environmental conditions is the first and simplest task required to create more complex electronic automations. Raspberry PI with DHT11 sensor can get temperature and humidity values with cheap pieces.

What is a DHT11

The DHT11 Sensor, which acronym stands for “Digital Humidity and Temperature”, is a cheap solution to measure indoor Temperature and Humidity (it is not indicated for outdoor uses). It’s really common in environment check projects as it can be used both with Raspberry PI (computer boards, as well as Pico microcontroller) and Arduino, usually in Weather Station projects or similar.

It can be found in the market with 2 different configurations. One comes with the DHT11 sensor alone and the other brings a small base:

dht11-models

The one with only the azure block, the “sensor” (on the right side of the previous image), requires you to buy a 10k Ohm resistor, while the one with the base, the “module” (on the left side of the previous image) has the 10k Ohm resistor already integrated. We’ll see later in this post how to use the resistor.

Another difference is the number of PINs, as the sensor has 4 PINs and the module has only 3 PINs.

Another common sensor, with a similar name, is the DHT22. The difference between DHT11 and DHT22 is that the DHT22 is the more expensive version, but allows a better humidity measuring range (from 0 to 100% with 2-5% accuracy), while the DHT11 real humidity range is from 20 to 80% with 5% accuracy.

DHT11 Pinout

The DHT11 sensor has 4 PINS, from left to right:

PINDescription
VCCPower supply (3.3V or 5V)
DataDigital input/output
NCNot Connected
GNDGround

As you can see, there’s a PIN not connected. Usually, in the DHT11 module you will find only the 3 effective PINs without the NC. The Data PIN from the DHT11 sensor requires a pull-UP resistor (connected to the VCC), which is the integrated resistor in the module version.

dht11-pinout

I’ll use a Raspberry PI 5 computer board for this article, but this tutorial also applies to other Raspberry PI computer board models.

What We Need

As usual, I suggest adding from now to your favourite e-commerce shopping cart all the needed hardware, so that at the end you will be able to evaluate overall costs and decide if to continue with the project or remove them from the shopping cart. So, hardware will be only:

raspberry-pi-5-model-b-board

You may also find it useful to evaluate a sensor kit which is a cost-saving solution if you want to test many sensors for different purposes.

Step-by-Step Procedure

Raspberry PI and DHT11 Wiring Diagram

To configure the DHT11 humidity module sensor with a Raspberry PI computer board, you need to connect the VCC and GND pins to +5V (or 3.3V) and GND from Raspberry Pi and the Data Pin of DHT11 to the GPIO PIN 17 of the Raspberry PI, according to the following wiring diagram.

Note that the following procedure will work only with GPIO 17.

Please refer to the following picture for wiring, according to the Raspberry PI pinout:

raspberry-pi-dht11-module-wiring-diagram-1

In case you have a DHT11 sensor, you must add the 10k Ohm pull-up resistor between the data cable and the VCC cable, as shown in the following picture:

raspberry-pi-dht11-sensor-wiring-diagram-2

Please find below some pictures from my home lab:

raspberr-pi-dht11-wiring-images-01
raspberr-pi-dht11-wiring-images-02
raspberr-pi-dht11-wiring-images-03
raspberr-pi-dht11-wiring-images-05
raspberr-pi-dht11-wiring-images-04

Install OS (Raspberry PI OS Lite)

Start preparing your Operating System. You can install the fast Raspberry PI OS Lite (without a Desktop environment) or opt for Raspberry PI OS Desktop, using its internal terminal.

Make sure your OS is up to date with the following commands:

sudo apt update -y && sudo apt upgrade -y

Configure DHT11 Overlay

With the newer Raspberry PI OS kernels we don’t need anymore to use python libraries to use the DHT11 sensor, as it is already supported by the kernel. We just need to edit the config.txt file:

sudo nano /boot/firmware/config.txt

and append the following line at the end of the file:

dtoverlay=dht11,gpiopin=17

Save and close.

We finally need to reboot the Raspberry PI so that we can have the the changes working:

sudo reboot now

After our Raspberry PI reboots, we can check if the DHT11 is correctly working. It should be mapped by the kernel at the “device0” of the “iio” folder, so you should be able to read the temperature with the following cat command:

cat /sys/bus/iio/devices/iio:device0/in_temp_input

This will give you the temperature in Celsius degrees multiplied by 1000, as in the following output of my board:

pi@raspberrypi:~ $ cat /sys/bus/iio/devices/iio:device0/in_temp_input
20100

From this example you can have the correct temperature value by dividing the result by 1000, so in my case, it’s 20.1°C.

IMPORTANT NOTE:

If you get an error similar to the following:

pi@raspberrypi:~ $ cat /sys/bus/iio/devices/iio\:device0/in_temp_input
cat: '/sys/bus/iio/devices/iio:device0/in_temp_input': Input/output error

Then you can fix it by updating your Raspberry PI firmware to a specific firmware pull which makes the DHT11 sensor to work. It worked with my Raspberry PI 5 model B and Raspberry PI 3 model A+, so this should work with any newer computer board. For older ones, please check that the new firmware will not negatively affect your computer board by asking the Raspberry PI forum or support.

You can do this operation with the following command, then rebooting:

sudo rpi-update pulls/6454
sudo reboot

Similarly, you can get the relative humidity value, again multiplied by 1000, with the following command:

cat /sys/bus/iio/devices/iio:device0/in_humidityrelative_input

In my case, I get the following output:

pi@raspberrypi:~ $ cat /sys/bus/iio/devices/iio:device0/in_humidityrelative_input
71800

The correct way to read this value is by dividing it by 1000 and considering the result as a humidity percentage, so my value is 71.8%.

Use Raspberry PI and DHT11 Temperature and Humidity in Python Projects

To use the sensor in your Raspberry PI and DHT11 projects with Python, you just need to read from the Python program the file values, also correctly handling the errors which could arise.

You can get directly in your Raspberry PI from my download area the small script I’ve prepared:

wget https://peppe8o.com/download/python/dht11/dht11.py

The following will explain the script line by line.

We don’t need any specific library to read the values. We’ll import only the sleep function from the Python time library in order to give a few time between each reading. Without this time, the DHT11 readings could be too much fast and the sensor could not answer properly:

from time import sleep

To make our script as simple and easy to read as possible, we’ll define 2 custom functions. The read_bus() function will open any file for reading and read a single line of it. Used with the DHT11 overlay, it will return the values as previously seen with the Linux cat function. So, basically it opens a file (which path is expected as input, reads the value, closes the file and returns the read value:

def read_bus(file):
    f = open(file,"rt")
    value = int(f.readline())
    f.close
    return value

The following dht11_val() custom function will try to read the temperature and humidity values, returning them already divided by 1000.

It initializes the “t” and “v” variables to zero.

Then, the try: .... except statements will try to execute the code lines within the try part. This section just uses the read_bus() functions to read the in_temp_input and in_humidityrelative_input files, assigning them to the related variables. If the values are read correctly, it mover to the final return statement. If any error occurs in one of these readings, the except statement will manage the error by printing the error message and setting to “N/A” both the temperature and humidity values.

At the end of this custom function, the return statement will give us back the temperature and humidity measurements:

def dht11_val():
    t = h = 0
    try:
        t = read_bus("/sys/bus/iio/devices/iio:device0/in_temp_input")/1000
        h = read_bus("/sys/bus/iio/devices/iio:device0/in_humidityrelative_input")/1000
    except Exception as e:
        print(e)
        t = h = "N/A"
    return t, h

So, at the end of the dht11_val() execution we’ll have as result “N/A” if an error occurred or the required values.

With these custom functions, our program becomes really easy. For this test, we’ll execute an infinite loop with the while True: line. At each loop, the first action is reading the temperature and humidity values:

while True:
    (temp, hum) = dht11_val()

After reading the values, if there were no reading errors (which means that both temperature and humidity are different from “N/A”), then we’ll print them in our Raspberry PI terminal console:

    if temp != "N/A" and hum != "N/A":
        print("Temperature %(t)0.2f°C, Humidity: %(h)0.2f%%" % {"t": temp, "h": hum})

The final sleep(1) assures that every check of the DHT11 sensor values will have at least 1 second of interval:

    sleep(1)

Test the dht11.py script

You can test the script by issuing the following command from your terminal:

python3 dht11.py

Then you should get the Raspberry PI readings of DHT11 temperature and humidity like in the following output:

pi@raspberrypi:~ $ python3 dht11.py
Temperature 20.30°C, Humidity: 71.30%
Temperature 20.30°C, Humidity: 71.30%
Temperature 20.30°C, Humidity: 71.30%
Temperature 20.30°C, Humidity: 71.30%
Temperature 20.30°C, Humidity: 71.30%
Temperature 20.30°C, Humidity: 71.30%
Temperature 20.30°C, Humidity: 71.30%

At any time you can stop the script from running by using the CTRL+C keys of your keyboard.

What’s Next

Interested in more cool ways to use your Raspberry PI computer board? Take a look at peppe8o Raspberry PI computer tutorials!

Enjoy!

How useful was this post?

Click on a star to rate it anonymously!

Average rating 4.7 / 5. Vote count: 19

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?