DHT22 on an ESP32 with MicroPython
MicroPython’s built-in dht module on an ESP32 DevKit: a DHT22 on D4 prints the temperature and humidity every two seconds in the Serial Monitor. The whole build, an ESP32 DevKit and 1 more part, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $13. On Mokxi they're free.
The code
The MicroPython code exactly as the editor opens it. Change a line there and press Run: the board runs it on the official MicroPython firmware, with nothing to compile.
# MicroPython on an ESP32 DevKit: a DHT22 temperature and humidity sensor.
# DATA is on D4; the module has its own pull-up.
from machine import Pin
import dht
import time
sensor = dht.DHT22(Pin(4))
time.sleep(2) # the DHT22 needs a moment after power-up
while True:
try:
sensor.measure()
print("Temperature: %.1f C Humidity: %.1f %%" % (sensor.temperature(), sensor.humidity()))
except OSError as e:
print("Could not read the DHT22:", e)
time.sleep(2) # a DHT22 gives a new reading every two seconds
Parts list
3 parts, plus the jumper wires. They retail for about $13; on Mokxi they're free.
How it is wired
3 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- ESP32 DevKit V1 pin D4; Temperature and humidity, DHT22 pin DATA
- 3.3 V: Temperature and humidity, DHT22 pin VCC
- Ground: Temperature and humidity, DHT22 pin GND
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.