DHT11 Sensor With Raspberry PI and Python
Last Updated on 2nd September 2023 by peppe8o
In this article, I will show you how to interface a Raspberry PI with DHT11 Sensor using Python.
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
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 can be used with Arduino (usually in Weather Station projects or similar) or alone, directly connected to a Raspberry PI.
To configure the DHT11 humidity sensor on a Raspberry Pi you need to connect the VCC and GND pins to +5V and GND from Raspberry Pi and the Data Pin of DHT11 to a GPIO PIN of the Raspberry Pi, according to the following wiring diagram.
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 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.
For this article, I’m going to use a Raspberry PI Zero W with a soldered header. But this article applies also to other Raspberry PI computer boards.
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 continue with the project or remove them from the shopping cart. So, hardware will be only:
- Raspberry PI Zero W (including proper power supply or using a smartphone micro usb charger with at least 3A) or newer Raspberry PI Board
- high speed micro SD card (at least 16 GB, at least class 10)
- Dupont Wiring
- DHT11 Temperature / Humidity sensor
You may also find it useful to evaluate 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 the following links:
Step-by-Step Procedure
Wiring Diagram
Please refer to the following picture to connect Raspberry PI with the DHT11 sensor:

Note that the 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 the 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 the 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 to 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 the following config screen, go to Interfacing Options > I2C. Enable it by pressing yes on the next screen and following confirmation. Once enabled, you should be forwarded again to the raspi-config home page.
To enable SPI, go again to Interfacing Options >SPI. Enable it by pressing yes on the next screen and following confirmation.
Click Finish on raspi-config home page to go back ssh terminal.
Install Python Libraries
RPI.GPIO should be already installed (otherwise, you can get it installed with the command “sudo apt install python3-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 the 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 correctly 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!
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
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.
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
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.
Dammmm you are good m8.
Thx, its working just fine now.
-Jens, Denmark
Hi again…
Now I got this error:
>>> %Run dht_test.py
Unable to set line 17 to input
after restart of the program.
-Jens
Same error as Stephen (a few comments above).
Try this script:
wget https://peppe8o.com/download/python/dht_test.py
where I addded “except KeyboardInterrupt:” exception management which cleans GPIOs on CTRL+C interruption.
Please let me know if this works, so that I can publish this version instead of old.
Many thanks!
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
Same issue reported at https://github.com/adafruit/Adafruit_CircuitPython_DHT/issues/27.
This is definitely an Adafruit CirtuiPython bug. In that thread, some user refer they solved by:
– changing “dhtDevice = adafruit_dht.DHT11(board.D17)” with “dhtDevice = adafruit_dht.DHT11(board.D17,False)”
– changing “GPIO.cleanup()” with “dhtDevice.exit()”
Please can you test these changes?
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
I need to cable again my RPI with DHT11 and make some more tests. Please give me a few days
Super m8
-Jens
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”.
Hi,
I’m getting this error how to fix it
unsupported operand type(s) for *: ‘NoneType’ and ‘float’
Where are you getting this error? Please can you provide the full error lines?
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
However idk if its worth noting im doing this with a raspberry pi4
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
Thanks for the great directions. I followed them and the code worked first time.
hi,
how to fix this error
temperature_f = temperature_c * (9/5)+32
TypeError: unsupported operand type(s) for *: ‘NoneType’ and ‘float’
OK, this seems an error coming from your DHT sensor not giving back any reading.
Please, firstly check that connections are correctly wired.
If all the wiring is ok, then try changing following code:
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print("Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(temperature_f, temperature_c, humidity))
with this:
humidity = dhtDevice.humidity
if temperature_c is not None and humidity is not None
temperature_f = temperature_c * (9 / 5) + 32
print("Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(temperature_f, temperature_c, humidity))
else
print("Reading Error")
Please note that in this comment area I can’t write tabulations, so you need to add tab (or space) before 2nd, 3rd and 5th row.
In case of any problem, please write to me at giuseppe@peppe8o.com
I avoid the “unable to set line to input”, by getting the GPIO to reset by killing, in my case, the libgpiod_pulsein64 linux process, which was still running after a ctrl-c/break.
Hi John, your suggestion makes me think that starting the python script with a check at the running processes and killing the concurrent could improve the script’s reliability. I’ll try it in the following weeks. In the meanwhile, thank you for your feedback!
Pi 3B OK, thank you