skip to Main Content

RPI Python: DHT-11 Temp / Humidity


Readers should be familiar with navigating using the terminal and editing / running python scripts.
Tutorials are available here:
Terminal Intro
Editing Files Tutorial

Hardware setup:

Carefully observe the ports and connect the positive line to the 5v, negative to ground, and the data out line to pin-14 also known as TXD on the raspberry pi GPIO.

Software Setup:

Step one is to download the DHT-11 Python library, which is very small and simple to use

Navigate to whatever directory you want in the terminal and use

git clone

To download the library.

Then navigate into the directory with cd, and look around with ls

We can already run the example with

sudo python

You should see the temperature and humidity displayed on the screen every few seconds.

Use Ctrl+c to kill the process and get back to the terminal.

Next we can move on to writing our own program that uses the sensor.
If you need to see an example, here is the full project we will be writing in this article finished.

First we need some boilerplate

import RPI.GPIO as GPIO
import dht11
import time

#warmup our GPIO pins 

#get ready to read data with pin 14 
instance = dht11.DHT11(pin=14)

Next we can start writing our own code. Similar to the clock tutorial we will use a infinite loop to keep our code going

while True:
result =
if result.is_valid():
 print("Temperature: %d C" % result.temperature)

Our code actually does less than the dht_11 example, but it’s a bit simpler.

result =

First we store our input from the sensor in the ‘result’ variable

if result.is_valid():

Next we use an if statement to only proceed if the result is valid

print("Temperature: %d C" % result.temperature)

In our if block we print the temperature using the print function, the ‘%d’ acts as a placeholder for a number (digits), followed by a list of variables to fill the placeholders

print("number %d %d" % (1, 2))

For example would print “number 1 2” to the terminal

Our output should look something like

"Temperature: 20 C"

After exiting the if block we wait for a full second before running the loop again


Remember to exit the program while its running use Control-C to escape
Here is the full example code from this tutorial

Back To Top