MicroPython: ESP32/ESP8266 with DHT11/DHT22 Temperature and Humidity Sensor

This tutorial shows how to use the DHT11 or DHT22 temperature and humidity sensors with the ESP32 and ESP8266 development boards using MicroPython firmware.

DHT Module Usage

There is a dht module that comes with the MicroPython firmware by default. So, it is easy to get temperature and humidity.

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 14:

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

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

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

Continue reading for the complete and detailed tutorial.

Prerequisites – Flashing MicroPython

To follow this tutorial you need MicroPython firmware installed in your ESP32 or ESP8266 boards. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:

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 Sensor using Arduino IDE

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

Parts Required

To follow this tutorial you need to wire the DHT11 or DHT22 temperature sensor to the ESP32 or ESP8266. You need to use a 10k Ohm pull-up resistor.

Here’s a list of parts you need to build the circuit:

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!

Schematic: ESP32 with DHT11/DHT22

Wire the DHT22 or DHT11 sensor to the ESP32 development board as shown in the following schematic diagram.

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

Learn how to use the ESP32 GPIOs with our guide: ESP32 Pinout Reference: Which GPIO pins should you use?

Schematic: ESP8266 with DHT11/DHT22

Follow the next tutorial if you’re using an ESP8266 board.

Code

Open a new file in your MicroPython IDE (like uPyCraft IDE or Thonny IDE) and copy the following code.

# Complete project details at https://RandomNerdTutorials.com

from machine import Pin
from time import sleep
import dht 

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

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 14. Use the following command if you’re using a DHT22 sensor:

sensor = dht.DHT22(Pin(14))

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

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

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 allows 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 ESP32 or ESP8266 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 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

After copying the code and making any necessary changes, you can upload the code to your ESP32 or ESP8266.

If you’re using Thonny IDE, you just need to go to Device > Upload current script as main script. After uploading the code, press the ESP on-board RESET button.

New temperature and humidity readings should be displayed on the MicroPython Shell, every two seconds.

If you’re using uPyCraft IDE and you’re having trouble uploading the code, go to the following tutorial and scroll down to the “Running Your First Script” section: Getting Started with MicroPython on ESP32 and ESP8266.

Troubleshooting

If your DHT sensor fails to get the readings, read our DHT Troubleshooting Guide to help you fix the issue.

Wrapping Up

Getting temperature and humidity readings with MicroPython is easy thanks to the dht module. After defining a dht object, you just need to use the temperature() and humidity() methods.

We hope you’ve found this guide useful. Now, you can display your sensor readings in a web server that you can access from your smartphone. Just follow this tutorial: Web Server MicroPython….

If you like MicroPython and you want to learn more, we recommend taking a look at our eBook: MicroPython Programming with ESP32 and ESP8266.

Thanks for reading.


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

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.