Some links in this post may be affiliate links. We may get paid if you buy something or take an action after clicking one of these, but without addictional costs for you compared to direct buying.

Use Raspberry PI with DHT11 Temperature and Humidity Sensor

Raspberry pi DHT11 featured image
Follow my latest articles on Twitter: . Or subscribe my newsletter (top right in this page) to be notified when new projects are available!
4.3
(9)

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

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

DHT11 sensor

DHT11 Sensor is a cheap solution to measure indoor Temperature and Humidity (it is not indicated for outdoor uses). It can be used with Arduino (usually in Weather Station projects or similar) or alone, directly connected to a Raspberry PI.

For this article, I’m going to use a Raspberry PI Zero W with soldered header. But this article apply also to other Raspberry PI boards.

What We Need

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

Raspberry PI Zero WH board
Raspberry PI Zero WH board

You may also find useful evaluating a sensors kit (like Elegoo Starter Kit) which is a cost saving solution if you want to test many sensors for different purposes.

Check hardware prices with following links:

Amazon raspberry pi boards box
Amazon raspberry pi Zero W box
Amazon Micro SD box
Amazon Raspberry PI Power Supply box
Amazon DHT11 umidity temperature box

Step-by-Step Procedure

Wiring Diagram

Please refer to following picture to connect Raspberry PI with DHT11 sensor:

RPI DHT11 wiring

Note that DHT11 signal (Data) pin is connected to RPI pin 11, which corresponds to GPIO 17 (refer to Raspberry PI GPIO schemas for complete schema).

Install OS (Raspberry PI OS Lite)

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

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

sudo apt update
sudo apt upgrade

Istall CircuitPython Libraries

CircuitPython libraries are a set of Python libraries from Adafruit which simplify external sensors management. These libraries require Python3. Check if it is installed with command:

python3 --version

Otherwise, install python3:

sudo apt install python3

Install pip for python3:

sudo apt install python3-pip

Enable I2C and SPI

Enable and configure I2C (standard designed to allow one chip to talk another)

sudo apt install -y python-smbus
sudo apt install -y i2c-tools

And enable Raspberry PI I2C kernel support with:

sudo raspi-config

In following config screen, go to Interfacing Options > I2C. Enable it by pressing yes in next screen and following confirmation. Once enabled, you should be forwarded again to raspi-config home page.

To enable SPI, go again in Interfacing Options >SPI. Enable it by pressing yes in next screen and following confirmation.

Click Finish in raspi-config home page to go back ssh terminal.

Install Python Libraries

Start from GPIO library:

pip3 install RPI.GPIO

Finally, install adafruit-blinka library. This includes also a few different libraries such as adafruit-pureio (our ioctl-only i2c library), spidev (for SPI interfacing), Adafruit-GPIO (for detecting your board) and of course adafruit-blinka):

pip3 install adafruit-blinka

Setup CircuitPython-DHT

Following adafruit dht library will be required to enable communication of Raspberry PI with DHT11 sensor:

pip3 install adafruit-circuitpython-dht
sudo apt install libgpiod2

Create a new reading script named DHT11Test.py:

nano DHT11Test.py

Insert the following code:

import time
import board
import adafruit_dht
#Initial the dht device, with data pin connected to:
dhtDevice = adafruit_dht.DHT11(board.D17)
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)

And finally execute by typing:

 python3 DHT11Test.py

This code will show measured data and also makes you aware that DHT11 sensor naturally receives a number of reading errors (as also referenced in adafruit comment inside the script):

pi@raspberrypi:~ $ python3 DHT11Test.py
Temp: 66.2 F / 19.0 C    Humidity: 56%
Temp: 66.2 F / 19.0 C    Humidity: 56%
Temp: 66.2 F / 19.0 C    Humidity: 56%
Temp: 66.2 F / 19.0 C    Humidity: 56%
Checksum did not validate. Try again.
Temp: 66.2 F / 19.0 C    Humidity: 56%
A full buffer was not returned.  Try again.
Temp: 66.2 F / 19.0 C    Humidity: 56%
Checksum did not validate. Try again.
Temp: 66.2 F / 19.0 C    Humidity: 56%
Temp: 66.2 F / 19.0 C    Humidity: 56%
Temp: 66.2 F / 19.0 C    Humidity: 56%
Temp: 66.2 F / 19.0 C    Humidity: 56%
Temp: 66.2 F / 19.0 C    Humidity: 56%

To have a clean list of correct measurements from Raspberry PI with DHT11, change inside code the line “print(error.args[0])” with “pass”. This avoids printing errors on terminal and outputs readings when it is corretly received:

pi@raspberrypi:~ $ python3 DHT11Test.py
Temp: 66.2 F / 19.0 C    Humidity: 55%
Temp: 66.2 F / 19.0 C    Humidity: 55%
Temp: 66.2 F / 19.0 C    Humidity: 55%
Temp: 66.2 F / 19.0 C    Humidity: 55%
Temp: 66.2 F / 19.0 C    Humidity: 55%
Temp: 66.2 F / 19.0 C    Humidity: 55%
Temp: 66.2 F / 19.0 C    Humidity: 55%
Temp: 66.2 F / 19.0 C    Humidity: 55%

Enjoy!

How useful was this post?

Click on a star to rate it anonymously!

Average rating 4.3 / 5. Vote count: 9

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?

17 comments

  1. Hi
    Simple starter project, works great, except.!
    Program copied using Thony, Ok
    Run 1st time no problem,
    Stop program using Crtl C, to make change to program.
    Program will not rerun without rebooting pi
    Gives error “unable to set line 17 to input”
    Any ideas.

    Thanks for taking time to put up your projects, appreciated

    1. Hi Stephen,
      thank you for your feedback. differently from some other python script, as before referenced this is an adafruit code. Before reporting what is my supposed solution, please find below some considerations.
      When you use GPIO library, at code starting you usually set PIN working state with GPIO.setup(). This function tells Raspberry PI if each PIN will be used as input or output. This function also marks the PIN as “in use” and every successive attempt to reuse the same PIN will warn user that the PIN is already “marked” untill you reboot or clean GPIOs status. Surely adafruit set PIN in their imported libraries but final cleaning is missing.
      A solution to this problem should be adding an exception which catches keyboard interrupt (CTRL+C) and cleans GPIO PIN when before script exit. New code should include the following (change only from while statement and keep previous lines):

      except KeyboardInterrupt:
      print(‘interrupted!’)
      GPIO.cleanup()

      Please get new code from your Raspberry PI with following command:

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

      I added this to a download file because wordpress comments cut spaces, which are really important in python code…
      Please, also let me know it this works, so that I can update my post code accordingly.
      Thank you very much.

  2. Hi m8
    I got the error as sho´n below here?

    Python 3.7.3 (/usr/bin/python3)
    >>> %Run dht_test.py
    Traceback (most recent call last):
    File “/usr/lib/python3.7/ast.py”, line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
    File “/home/pi/Desktop/dht_test.py”, line 14
    except RuntimeError as error: # Errors happen fairly often, DHT’s are hard to read, just keep going
    ^
    IndentationError: unindent does not match any outer indentation level

    Kind regard

    -Jens

    1. Hi Jens,
      try removing 1 space char before “try:”. It appears a banal indenting error and Python is rigid on indentation…
      Please let me know if it works.

  3. Hi again…

    Now I got this error:

    >>> %Run dht_test.py
    Unable to set line 17 to input

    after restart of the program.

    -Jens

  4. import time
    import board
    import adafruit_dht
    from datetime import datetime
    #Initial the dht device, with data pin connected to:

    dhtDevice = adafruit_dht.DHT11(board.D17)

    while True:
    try:
    # Print the values to the serial port
    temperature_c = dhtDevice.temperature
    temperature_f = temperature_c * (9 / 5) + 32
    humidity = dhtDevice.humidity
    now = datetime.now()
    current_time = now.strftime(“%H:%M:%S”)
    print (“Ny læsning: “)
    print(“Current Time =”, current_time)
    print(“Temp: {:.1f} F / {:.1f} C Humidity: {}% “.format(temperature_f, temperature_c, humidity))
    print (“———-“)
    time.sleep(2.5)
    except RuntimeError as error: # Errors happen fairly often, DHT’s are hard to read, just keep going
    print(error.args[0])
    print (“Fejl i læsning af pin”)
    except KeyboardInterrupt:
    print(‘interrupted!’)
    GPIO.cleanup()

    As u Can see I already did that

  5. Yep, coming here:

    With “False” i got this error: “NameError: name “false” is not defined.

    Without, i get this one 2nd run of the program: Unable to set line 17 to input

    Kind regards Jens

        1. Hi Jens, just a question: when you get “Unable to set line 17 to input”, what do you get from this command:
          ps -ef | grep dht
          Ps command lists all running processes in your RPI, while grep filters to output only those having *dht* in process name (supposing that you have left script name including dht string).
          I wasn’t able to reproduce your error terminating script execution with CTRL+C, while I had your same error “pausing” script output with “CTRL+Z”.

  6. hi guys i have tried everything on this page lol and im still getting “Unable to set line 17 to input” do we have any other ideas

  7. I cant send to u here, due to this fail on your homepage:
    Not Acceptable!
    An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.

    Below here, is the last part of a hole lot of words.

    DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus TEXTDOMAIN=Linux-PAM _=/usr/bin/grep

    -Jens

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept the Privacy Policy