• First Steps
  • General
  • Projects
Facebook Twitter YouTube
Tutorials for Raspberry Pi Tutorials for Raspberry Pi
  • Hardware & GPIO
  • Sensors & Components
  • Scale
  • Cases
  • Fingerprint
  • Gas Sensor
  • Heartbeat
  • German
  • French
Tutorials for Raspberry Pi Tutorials for Raspberry Pi
Home»Hardware & GPIO»Raspberry Pi: Measure Humidity and Temperature with DHT11/DHT22

Raspberry Pi: Measure Humidity and Temperature with DHT11/DHT22

Facebook Twitter LinkedIn Tumblr Email Reddit
Raspberry Pi: Measure Humidity and Temperature with DHT11/DHT22
Share
Facebook Twitter LinkedIn Email Tumblr Reddit Telegram WhatsApp

With the Raspberry Pi and some sensors, it is easy to measure the temperature without much effort. In addition, however, the humidity in certain situations or projects (such as a weather station) can be enlightening. Sensors such as the DHT11 and DHT22 are not only available for a few euros, but they can also measure the temperature as well as the humidity.

Accessories

As the sensors already carry (almost) everything, apart from a resistor, not many additional accessories are required. I have used this:

  • DHT11 or DHT22 humidity sensor
  • 10kΩ resistor
  • Breadboard and jumper wires

You can see the difference between DHT11 and DHT22 here. As a result, the DHT11 (blue) is cheaper, but the DHT22 (white) is more precise and lasts longer. For applications in “extreme” areas (0-20% or 80-100% humidity), the DHT22 should be used, as it also supports these areas in contrast to the DHT11. For example, I have a DHT22 sensor in my fridge to measure and log temperature and humidity. In general, the 11er model should also be enough.

 

Setup of Raspberry Pi Humidity Sensor

Raspberry Pi Humidity/Temperature Sensor ConstructionThe left pin of the sensor is connected to 3V3 of Pi (pin1), the second sensor pin via a pull-up resistor (4.7k – 10kΩ) with a free GPIO of the raspberry (GPIO4, pin7) and the right senior pin comes at GND (Pin6) from the Pi. The second pin from the right of the sensor remains free.

The structure is identical for DHT11 or DHT22 since the pins are assigned the same way.

 

Raspberry Pi Humidity Software Installation and Testing

First of all, some packages have to be installed:

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

The library for the sensors can now be loaded. I use a ready-made library from Adafruit that supports various sensors

sudo pip3 install adafruit-circuitpython-dht
sudo apt-get install libgpiod2

Then we create a new file with our code:

sudo nano dht_example.py

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import time
import board
import adafruit_dht
 
# Initial the dht device, with data pin connected to:
# dhtDevice = adafruit_dht.DHT22(board.D4)
 
# you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio.
# This may be necessary on a Linux single board computer like the Raspberry Pi,
# but it will not work in CircuitPython.
dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False)
 
while True:
    try:
        # Print the values to the serial port
        temperature_c = dhtDevice.temperature
        temperature_f = temperature_c * (9 / 5) + 32
        humidity = dhtDevice.humidity
        print(
            "Temp: {:.1f} F / {:.1f} C    Humidity: {}% ".format(
                temperature_f, temperature_c, humidity
            )
        )
 
    except RuntimeError as error:
        # Errors happen fairly often, DHT's are hard to read, just keep going
        print(error.args[0])
        time.sleep(2.0)
        continue
    except Exception as error:
        dhtDevice.exit()
        raise error
 
    time.sleep(2.0)
 

Note that you replace adafruit_dht.DHT22 with adafruit_dht.DHT11 if you are using a DHT11 temperature sensor.

We save the file with CTRL + O and exit the editor with CTRL + X. Then we execute our code:

sudo python dht_example.py

 

 

Earlier version

There is also another repository from Adafruit, which should no longer be used. For the sake of completeness, I’ll show it here anyway (you can skip this part if everything worked before):

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

Now the library for the sensors can be loaded. I use a pre-built Adafruit library that supports a variety of sensors:

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

This creates a Python library that we can easily integrate into our projects.

If everything went well, we can already read the temperature and humidity. The easiest way is to first use the demo files:

cd examples
sudo ./AdafruitDHT.py 11 4

The first parameter (11) indicates which sensor was used (22 for the DHT22) and the second, to which GPIO it is connected (not the pin number, but the GPIO number). This produces an output like the following:

$ sudo ./AdafruitDHT.py 11 4
Temp=24.0*  Humidity=41.0%

Attention: The sensors are only ready every two seconds. Be careful not to start a query every second.

 

To integrate the Raspberry Pi humidity library into other (Python) projects, you only need the following:

Python
1
2
3
4
5
6
import Adafruit_DHT
...
sensor = Adafruit_DHT.DHT11
pin = 4
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
...

 

Log data permanently

For weather stations and similar projects for monitoring the temperature and humidity, it is useful to store these values at regular time intervals so that they can be analyzed later. One possibility would be to save in local database, but this has the disadvantage that under certain circumstances, the SD card could be charged too much.

Therefore, I have chosen a different method that stores the data on an external server. This service is free for normal use and it is very easy to save data, as shown here:

air moisture Humidity Luftfeuchte temperatur Wetterstation
Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
Previous ArticleRaspberry Pi: YouTube Live Streaming Setup
Next Article Mit dem Raspberry Pi und OpenHAB Funksteckdosen (433 MHz) schalten

Related Posts

How to build a ESP8266 Scale (with Weight Sensor HX711)

How-To: Bluetooth Connection between ESP32’s and Raspberry Pi’s

How to create a Solar Powered Raspberry Pi Bitcoin Miner

How to build a Smart Agriculture System using IoT

38 Comments

  1. cyril on 6. February 2018 3:27

    I get to the line git clone https://github.com/adafruit/Adafruit_Python_DHT.git & sudo python setup.py install and I get the following python: can’t open file ‘setup.py’: [Error 2] No such file or directory
    [1]+ Exit 128
    What should I check next or should I erase and start over and if start over do I have to delete?

    Reply
  2. cyril on 6. February 2018 4:58

    Found the answer. The line in the tutorial “https://github.com/adafruit/Adafruit_Python_DHT.git & sudo python setup.py install” . After it ran and I got the errors. I changed Directory cd Adafruit_Python_DHT the sudo python setup.py install. Then sudo ./Adafruit.py 11 4 and it worked!

    Reply
  3. ololo on 27. September 2018 13:26

    Cyril, ‘git clone https://github.com/adafruit/Adafruit_Python_DHT.git‘ creates Adafruit_Python_DHT dir and clones there. So, you have to change dir to that one with the ‘cd’ command.

    Reply
    • HerroPrease on 26. April 2021 5:46

      Yeah, that guy is fucking stupid.

      Reply
  4. Andrea on 5. November 2018 15:36

    “on an external server.” which server/service ? thank you

    Reply
    • Kobus Theron on 7. November 2018 5:42

      The example shown is using API calls to Thingspeak to publish the values. It could be a whole tutorial on its own.

      Reply
  5. Jakov on 23. January 2019 19:46

    I set DHT11 with my Raspberry.
    Normally seems it shows correct results eg. 22*/46%, but after 10 lines goes mad eg. 7*/105%. Than again turns to normal. Is it about a bad sensor?

    Reply
    • Lionel on 4. February 2019 19:56

      The manufacturers do not recommended that you read data from the sensor more than once per 2 seconds. If you do you may get incorrect readings.

      Reply
  6. Buraq on 9. February 2019 18:33

    python3?

    Reply
  7. Botan on 26. February 2019 10:47

    Thanks
    I have done what you have done, (Raspberry Pi 3 B), but after running
    pi@raspberrypi:~/projects/Adafruit_Python_DHT/examples $ sudo ./AdafruitDHT.py 22 4
    it prompts the following error
    Failed to get reading. Try again!

    please help.

    Reply
    • Rems on 30. April 2019 15:42

      Same problem…

      Reply
  8. hozan on 27. February 2019 15:48

    hi, i would like to work on raspberry pi ans some sensors like temp, humidity, Nitrogin and PM 10 so when ordering the pi what else i should order, do i need A/D converter and which one , also in order to send data do i need other components to carry out with my work, like what are the components required with the pi

    Reply
  9. Kathleen Fox on 15. March 2019 19:40

    pi@raspberrypi:~/foxfiles/Adafruit_Python_DHT $ git clone https://github.com/adafruit/Adafruit_Python_DHT.git && Adafruit_Python_DHT on setup.py install
    Cloning into ‘Adafruit_Python_DHT’…
    remote: Enumerating objects: 308, done.
    remote: Total 308 (delta 0), reused 0 (delta 0), pack-reused 308
    Receiving objects: 100% (308/308), 91.74 KiB | 0 bytes/s, done.
    Resolving deltas: 100% (168/168), done.
    bash: Adafruit_Python_DHT: command not found
    pi@raspberrypi:~/foxfiles/Adafruit_Python_DHT $

    When I run the example, I get the error ImportError: No module named ‘Adafruit_DHT’. That is probably related to the bash error above. Any help would be appreciated. Thanks.

    Reply
    • Mike on 29. July 2019 17:43

      I am certainly no expert but have had similar problems in the past. It looks like it might be a problem with the DHT library, try removing and installing it again. There also might be a problem with where the files were installed. If they are too deep in the structure it won’t work.

      Reply
  10. Giacomo on 12. April 2019 15:13

    Hi All,

    what’s the maximum distance between the sensor and Raspberry?
    How many sensors I can connect to one Raspberry?
    Thank you!

    Reply
  11. Greg Foster on 19. April 2019 13:30

    Also curious how many sensors you can connect in this configuration, and whether they are serialized or must have a unique pin for each assigned?

    Reply
  12. Jean on 27. April 2019 10:51

    Hey guys,
    I got everything right. I did all the commands that was on this page twice, copied the program on this page, and it said both times:
    Traceback (most recent call last):
    File “/home/pi/Desktop/programs/Temp-humidity sensor.py”, line 1, in
    from Adafruit_DHT import example
    ImportError: No module named ‘Adafruit_DHT’

    Reply
    • Rick on 1. May 2019 19:04

      I was getting the No Module error until I typed (retyped?) the command
      sudo python setup.py install

      Reply
  13. Rems on 30. April 2019 15:38

    Hey, I have a big problem.
    When I write sudo ./AdafruitDHT.py 2302 4, I have “failed to get reading. Try again !”
    Why pleaaaase ?

    Reply
    • Rick on 1. May 2019 19:07

      Have you tried multiple sensors? Also, for the 2302, I just use 22. I had one bad sensor. Drove me nuts till I just plugged in the other sensor. Of note, if you buy the sensors already mounted on a small PC board with only 3 lines coming out, skip the breadboard with the resistor. It’s already on the PC board. Just hook up 3.3, Gnd, and GPIO4.

      Reply
    • Nate on 3. May 2019 21:39

      Try a decoupling capacitor

      Reply
  14. Vla on 22. September 2019 18:05

    Hi
    Someone asked already but I hope for a reply too:
    1. how do I connect multiple DHT11 or DHT22 sensors?
    2. What’s the limit how many can I add to the series?
    3. What’s the Max distance between Raspberry and the sensor for a simple wire without any extra electronic components ?
    4. How to deal with distances longer than a max for simple wires, like what kind of circuits would extend the range or digitize it?

    Thank you!

    Reply
  15. Jeevan on 23. November 2019 6:46

    How to controll the over heat protection auto cutoff circuit baker, I used DHT11 Sensor for room temperature auto cutoff chemni for detections Humidity & Temperature with auto ON & OFF but the value of serial print code was not working how to read the Serial data for DHT11 Sensor relay ON & OFF based on temperature & humidity.

    Reply
  16. Raffaele Morelli on 26. November 2019 12:47

    Could you please give some instructions on how to do this on a mini breadboard?

    Reply
  17. SC on 26. December 2019 22:03

    Great tutorial, thank you! I used a DHT11 and some parts from an Arduino UNO kit to get up-and-running with your code. After initial setup I worked with your google_spreadsheet.py file to create a basic remote-monitoring station for my home temperature. A welcome set of data in the winter for monitoring the operation of our heating system. Muchas Gracias!

    Reply
  18. PSI on 21. October 2020 17:05

    Any succesfull experience with RPI4B and Buster 10?
    Whatever I do I get “Failed to get reading. Try again”

    Reply
  19. Sebastiab on 18. November 2020 23:22

    What was the external server you set you data logging up on?

    Can you please elaborate on this? This is the key issue that I have been trying to solve and you stop just at the crucial bit!

    Reply
  20. DI on 27. March 2021 23:53

    I’ve followed the guide connecting DHT22 to GPIO 6 intead of 4 because 4 it’s already taken.
    switching the setup accordingly (sudo ./AdafruitDHT.py 22 6) it doesn’t show any reading but if i connect it via Raspcontrolled app from mobile it works…… i really cannot get how to run it from pi terminal…..

    Reply
  21. CW on 1. September 2021 3:10

    I guess this is not for newbies, I can’t even get the script to run following the steps.

    pi@raspberrypi:~ $ sudo python dht_example.py
    Traceback (most recent call last):
    File “dht_example.py”, line 2, in
    import board
    ImportError: No module named board

    Reply
    • CW on 1. September 2021 3:34

      issue I had was because of python, need to run using > python3 dht_example.py

      Reply
      • Dylan on 21. October 2021 19:26

        CW, how did you resolve this exactly? I am having the same issue with no module “board” error.

      • Ernest on 26. November 2021 21:29

        It works fine, you only have to run it with “$ python3 dht_example.py”.

  22. LM on 9. April 2022 18:30

    I’m having a problem with the newer version where when i run the file it says:
    “ File “dht_example.py”, line 25
    except RuntimeError as error:
    ^
    IndentationError: unindent does not match any outer indentation level”
    How can I fix this? Im new to python so I don’t know anything of what that means.

    Reply
    • LM on 9. April 2022 19:39

      btw I’m using a DHT11.

      Reply
    • LM on 9. April 2022 19:40

      and I’m using a Raspberry Pi 4 B.

      Reply
  23. agentSmith on 20. July 2022 12:14

    Can i use many sensors with one raspberry? I want to take measurements from different points of a big room

    Reply
    • Barry on 15. December 2022 21:49

      Smithy:
      I have the SAME question. I got one DHT22 to work using GPIO pin 7 but now I want to read a second DHT22 at the same time and cannot get the program to read the second sensor.
      Have you come across a solution?
      Barry
      FLYADIVE@GMAIL.COM

      Reply
  24. Rob Ramsey on 18. December 2022 21:59

    Hello, great article! You mentioned a free external server/service that you use to record and plot your data. Could you provide a name and/or link to that site? Thanks in advance!

    Reply

Leave A Reply Cancel Reply

How to create a Solar Powered Raspberry Pi Bitcoin Miner

Official 7″ Raspberry Pi Touch Display Presented

Top 21 OS for the Raspberry Pi for your Project – Overview

Raspberry Pi Robot: Avoiding Obstacles Automatically (Part 4)

Home Assistant on Raspberry Pi – Getting Started

Raspberry Pi Autostart: Start the Program automatically

Subscribe to Blog
Subscribe to Raspberry Pi Tutorials and don't miss any new Tutorial!
Subscribe

Thank you!

We will contact you soon.

Tutorials for Raspberry Pi
Facebook Twitter YouTube
  • Contact & Disclaimer

Type above and press Enter to search. Press Esc to cancel.