Raspberry Pi Pico: DHT11/DHT22 Temperature and Humidity Sensor (MicroPython)

This guide shows how to read temperature and humidity from the DHT11 or DHT22 sensors using the Raspberry Pi Pico board with MicroPython firmware.

Raspberry Pi Pico with DHT11 DHT22 Temperature and Humidity Sensor MicroPython

Do you prefer using Arduino IDE? Check the following tutorial: Raspberry Pi Pico: DHT11/DHT22 Temperature and Humidity Sensor (Arduino IDE).

Table of Contents

DHT Module Usage

There is a dht module that comes with the MicroPython firmware by default, which makes it pretty straightforward to get temperature and humidity from the DHT11 or DHT22 temperature sensors.

1. Start by importing the dht and machine modules:

import dht
from machine import Pin

2. Create a dht object that refers to the sensor’s data pin, in this case, it’s GPIO 22:

#sensor = dht.DHT11(Pin(22))
sensor = dht.DHT22(Pin(22))

3. To measure and read the sensor values, use:

sensor.measure() 
sensor.temperature()
sensor.humidity()

Continue reading for more information and the detailed tutorial.

Prerequisites – MicroPython Firmware

To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board.

The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.

Introducing the DHT11 and DHT22 Sensors

The DHT11 and DHT22 sensors are used to measure temperature and relative humidity. These are very popular among makers and electronics hobbyists.

DHT11/DHT22 Temperature and Humidity Sensors

These sensors contain a chip that does analog to digital conversion and spit out a digital signal with the temperature and humidity. This makes them very easy to use with any microcontroller.

DHT11 vs DHT22

The DHT11 and DHT22 are very similar, but differ in their specifications. The following table compares some of the most important specifications of the DHT11 and DHT22 temperature and humidity sensors. For a more in-depth analysis of these sensors, please check the sensors’ datasheet.

DHT11
DHT22
Temperature range0 to 50 ºC +/-2 ºC-40 to 80 ºC +/-0.5ºC
Humidity range20 to 90% +/-5%0 to 100% +/-2%
ResolutionHumidity: 1%
Temperature: 1ºC
Humidity: 0.1%
Temperature: 0.1ºC
Operating voltage3 – 5.5 V DC3 – 6 V DC
Current supply0.5 – 2.5 mA1 – 1.5 mA
Sampling period1 second2 seconds
Price$1 to $5$4 to $10
Where to buyCheck pricesCheck prices

The DHT22 sensor has a better resolution and a wider temperature and humidity measurement range. However, it is a bit more expensive, and you can only request readings with 2 seconds interval.

The DHT11 has a smaller range and it’s less accurate. However, you can request sensor readings every second. It’s also a bit cheaper.

Despite their differences, they work in a similar way, and you can use the same code to read temperature and humidity. You just need to select in the code the sensor type you’re using.

DHT Pinout

DHT sensors have four pins as shown in the following figure. However, if you get your DHT sensor in a breakout board, it comes with only three pins and with an internal pull-up resistor on pin 2.

DHT22 Temperature and Humidity Sensor using Arduino IDE

The following table shows the DHT22 and DHT11 pinout. When the sensor is facing you, pin numbering starts at 1 from left to right

DHT pinConnect to
13.3V
2Any digital GPIO; also connect a 10k Ohm pull-up resistor
3Don’t connect
4GND

DHT Sensor Breakout Board

If you got a DHT11 or DHT22 sensor on a breakout board, they only come with three pins and have an internal pull-up resistor on the data pin.

DHT22 sensor

In this case, wiring is even simpler and you don’t need to wire an external resistor. The DHT breakout boards usually have labels on the pins: GND, VCC, and DATA.

DHT pinConnect to
GNDGND
VCC3V3(OUT)
DATGPIO 22 (or any other digital pin)

Parts Required

Raspberry Pi Pico with DHT Sensor

Here’s a list of parts you need to build the circuit (if you don’t have a DHT breakout board, you need a 4.7kOhm resistor):

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Wiring the DHT11/DHT22 to the Raspberry Pi Pico

Wire the DHT22 or DHT11 sensor to the Raspberry Pi Pico as shown in the following schematic diagram. If you have a DHT breakout board, ignore the resistor.

raspberry pi pico with DHT sensor fritzing diagram

In this example, we’re connecting the DHT data pin to GPIO 22. However, you can use any other suitable digital pin.

You might also like reading: Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained.

Raspberry Pi Pico with DHT Sensor – Code

Open a new file in Thonny IDE or another MicroPython IDE of your choice and copy the following code.

# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-dht11-dht22-micropython/

from machine import Pin
from time import sleep
import dht 

sensor = dht.DHT22(Pin(22))
#sensor = dht.DHT11(Pin(22))

while True:
  try:
    sleep(2)
    sensor.measure()
    temp = sensor.temperature()
    hum = sensor.humidity()
    temp_f = temp * (9/5) + 32.0
    print('Temperature: %3.1f C' %temp)
    print('Temperature: %3.1f F' %temp_f)
    print('Humidity: %3.1f %%' %hum)
  except OSError as e:
    print('Failed to read sensor.')

View raw code

How the Code Works

Import the Pin class from the machine module to define pins, import the sleep method from the time module to add delays to your code, and finally import the dht module to import the functions to read from the DHT sensors.

from machine import Pin
from time import sleep
import dht 

Define a dht object called sensor on the specified data pin. In this case, we’re connecting the data pin to GPIO 22. Use the following command if you’re using a DHT22 sensor:

sensor = dht.DHT22(Pin(22))

Comment the previous line and uncomment the next one if you’re using a DHT11 sensor.

#sensor = dht.DHT11(Pin(22))

In the while loop, we use try and except statements. In the try statement, we try to get temperature and humidity values.

Note: try and except allow us to continue the execution of the program when an exception happens. For example, when an error occurs, the try block code execution is stopped and transferred to the except block. In our example, the exception is especially useful to prevent the board from crashing when we are not able to read from the sensor.

In the try statement, first, add a delay of two seconds because the DHT22 maximum sampling rate is two seconds. In the case of the DHT11, it is one second.

sleep(2)

Before requesting temperature and humidity, you need to use the measure() method on the sensor object.

sensor.measure()

Then, read the temperature with sensor.temperature() and the humidity with sensor.humidity(). Save those readings on the temp and hum variables.

temp = sensor.temperature()
hum = sensor.humidity()

The following command converts the temperature to Fahrenheit degrees.

temp_f = temp * (9/5) + 32.0

Finally, print all the readings on the MicroPython shell using the print() function:

print('Temperature: %3.1f C' %temp)
print('Temperature: %3.1f F' %temp_f)
print('Humidity: %3.1f %%' %hum)

In case there is an error getting the readings, the except statement runs and an error message is printed:

except OSError as e:
  print('Failed to read sensor.')

Demonstration

Save the code to your Raspberry Pi Pico board using Thonny IDE or any other MicroPython IDE of your choice.

Copy the code provided to a new file on Thonny IDE.

DHT sensor MicroPython Thonny IDE

With the code copied to the file, click on the Save icon. Then, select Raspberry Pi Pico.

Saving file to Raspberry Pi Pico MicroPython IDE

Save the file with the following name: main.py.

Micropython saving main.py file Thonny IDE

Note: When you name a file main.py, the Raspberry Pi Pico will run that file automatically on boot. If you call it a different name, it will still be saved on the board filesystem, but it will not run automatically on boot.

Reset your board (unplug and plug it into your computer). Click the little green button “Run Current Script” or press F5.

run script on thonny ide

New temperature and humidity readings will be published on the shell every two seconds.

Raspberry Pi Pico display DHT readings on micropython shell

Troubleshooting

If your DHT sensor fails to get the readings, read our DHT Troubleshooting Guide to help you fix the issue (even though it’s a troubleshooting guide for Arduino IDE, most issues are related to hardware, so most tips are useful regardless of the programming language you’re using).

Wrapping Up

In this tutorial, you learned how to interface the DHT11 and DHT22 temperature sensors with the Raspberry Pi Pico and how to get temperature and humidity readings using MicroPython firmware.

There’s a specific built-in MicroPython module to interface with DHT sensors, the dht module. After defining a dht object, you just need to use the temperature() and humidity() methods.

Learn more about the Raspberry Pi Pico with our eBook:

We have other Raspberry Pi Pico basic tutorials that you might like reading:

>> Check out all our Raspberry Pi Pico Guides.

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

2 thoughts on “Raspberry Pi Pico: DHT11/DHT22 Temperature and Humidity Sensor (MicroPython)”

  1. Hi.
    If someone would like to use the bme280 sensor.
    Then this can be used with micropython and Thonny.

    import machine
    import bme280
    from time import sleep

    i2c = machine.I2C(id=0, scl=machine.Pin(1), sda=machine.Pin(0))
    bme = bme280.BME280(i2c=i2c)

    while True:
    try:
    sleep(2)
    print(bme.values)
    temperature = bme.values[0]
    temperature = “{:.1f}”.format( float(temperature[:-1]))
    humidity = bme.values[2]
    humidity = “{:.1f}”.format( float(humidity[:-1]))
    pressure = bme.values[1]
    pressure = “{:.1f}”.format( float(pressure[:-3]))

    #print(temperature + “C” )
    print(temperature)
    print(humidity)
    print(pressure)
    except OSError as e:
    print(‘Failed to read sensor.’)

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.