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 File> Save as…. Then, select MicroPython device.

Thonny IDE Save to MicroPython Device

Click OK to upload the code to your board.

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 or send sensor readings to an IoT platform via MQTT communication protocol. Take a look at the following tutorials:

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

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!

12 thoughts on “MicroPython: ESP32/ESP8266 with DHT11/DHT22 Temperature and Humidity Sensor”

  1. Hi,
    My son is trying to make a humidity and temp with esp32 and DHT 22, i would like to help him to upload cod and run the program i try several time every time i face with error or …, is there anyone could help me up?

    Reply
  2. Hello!

    Please help – I am having trouble making this program work.

    Here’s the situation:
    -My board is an ESP8266 nodeMCU (Geekreit DOIT ESP-F Devkit v4, if it matters), running MicroPython v. 1.13.
    -My DHT11 module is the kind with the little breakout board and three pins – data, power and ground, respectively. I have the data pin attached to GPIO 14 as per your program, and the other pins attached to the adjacent GND and 3V3 pins.

    So I copy-pasted your code and uploaded it to my board using Thonny, but all I get is “Failed to read sensor.”

    I can blink an LED with this board using MicroPython, so that’s not the problem. I can also get the DHT11 to work with an Arduino, so that’s not the problem either. I have checked the wiring over and over and I know it’s correct. What am I doing wrong?

    Reply
  3. Excellent tutorial! I got a “Micropython starter kit” which had the exact same boards: an ESP32, an SDD1306, and a DHT11. I was afraid at least the OLED module didn’t work since it didn’t seem to power up whether I connected it to the ESP32, or direct to the breadboard. I think it was uploading ssd1306.py to the board that brought it to life, and I got “Hello World” displayed on it.

    I also appended your code for the DHT11 to main.py, modifying it to send output to the OLED module instead. After a little futzing with the parameters to oled.text, the temperature and humidity show up below the Hello World strings.

    Next up: a nicer format instead of the bare numbers, and installing larger fonts so the numbers take up more of the screen. The “Hello World” strings can go

    Reply
  4. Thanks for this tutorial. Very helpful.
    Just one mention regarding the DHT11 library – temperature and humidity are now properties so if you want to refer to them don’t use the parenthesis:

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

    to:
    temp = sensor.temperature
    hum = sensor.humidity

    Hope it helps.

    Reply
  5. May be too late but my experiences showed, that a pullup-resistor to Vcc is essential for reading. I put a 10k resistor from GPIO14 to 3.3V and it works.

    Reply
  6. Are the links in this tutorial still working? I keep trying to just use the 2 microdot.py files mentioned but they aren’t available. I’ve tried to use some of the library files for asyncio but I keep getting errors like these:
    File “main.py”, line 4, in
    File “microdot_asyncio.py”, line 8, in getattr
    File “asyncio/init.py”, line 1, in getattr

    Any reading this, can you help? I’m trying to have my esp32s running some sort of templated API system and I am at a complete roadblock. Also tried the esp32 – microWebSrv github situation and not much better luck with that though I was able to get the API server to startup.

    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.