Skip to content

Tutorial

MicroPython DHT11 and DHT22 on ESP32: Wiring, Code and Accurate Readings

Read temperature and humidity from a DHT11 or DHT22 with MicroPython on an ESP32: wiring, a reliable reading loop, DHT11 vs DHT22, dew point, accuracy and fixes.

  • 11 min read
  • Updated November 14, 2026
MicroPython DHT11 and DHT22 on ESP32: Wiring, Code and Accurate Readings

Quick answer: MicroPython on the ESP32 has a built-in dht module, so no library install is needed. Wire the sensor's DATA pin to a GPIO such as GPIO4, power it from 3.3 V, and add a 10 kΩ pull-up from DATA to 3.3 V if you have a bare 4-pin sensor (modules already have one). Then:

main.py
import dht
from machine import Pin

sensor = dht.DHT22(Pin(4))     # or dht.DHT11(Pin(4))
sensor.measure()
print(sensor.temperature(), "C", sensor.humidity(), "%")

Read a DHT22 at most every 2 seconds and a DHT11 every 1 second, and wrap measure() in try/except OSError, because occasional failed reads are normal. Below: wiring, a robust reading loop, DHT11 vs DHT22, heat index and dew point, a fix table, and where to send the data next.

What you needNotes
ESP32 running MicroPythonInstall MicroPython
DHT22 (AM2302) or DHT113-pin modules include the pull-up resistor
10 kΩ resistorOnly for bare 4-pin sensors
Jumper wires, breadboardKeep the data wire under about 20 cm for a first test

DHT11 vs DHT22

DHT11 (blue)DHT22 / AM2302 (white)
Temperature range0 to 50 °C−40 to 80 °C
Temperature accuracy±2 °C±0.5 °C
Humidity range20–90 % RH0–100 % RH
Humidity accuracy±5 % RH±2–5 % RH
Resolution1 °C, 1 %0.1 °C, 0.1 %
Fastest readingOnce per secondOnce every 2 seconds
Supply3.3–5.5 V3.3–6 V
PriceCheapestA little more

Pick the DHT22 for anything you'll actually look at: indoor climate, greenhouses, outdoor (sheltered) logging. The DHT11 is fine for learning and "is it humid?" checks. For better accuracy and I2C convenience, consider a BME280 or SHT31 (BME280 vs BMP280).

1. Wire the sensor

Sensor pinESP32
VCC (+)3.3 V
DATA (OUT)GPIO4
GND (−)GND
(bare sensor pin 3)Not connected

For a bare 4-pin DHT22, put a 10 kΩ resistor between DATA and 3.3 V. Avoid input-only pins (GPIO34–39 have no internal pull-up and the DHT needs to be driven) and the boot-strapping pins 0, 2, 12 and 15. GPIO4, 5, 13, 14, 16–19, 21–23, 25–27, 32 and 33 are all fine. Full map: ESP32 pinout.

2. A robust reading loop

Save this as main.py so it runs at boot:

main.py
import dht, time
from machine import Pin
sensor = dht.DHT22(Pin(4))
INTERVAL_S = 5
# >= 2 s for DHT22, >= 1 s for DHT11
def read_once(retries=3):
    for attempt in range(retries):
        try:
            sensor.measure()
            t, h = sensor.temperature(), sensor.humidity()
            if -40 <= t <= 80 and 0 <= h <= 100:
                # reject impossible values
                return t, h
            except OSError as e:
                # ETIMEDOUT: no or garbled answer
                print("Read failed:", e)
                time.sleep(2)
                return None, None
                while True:
                    t, h = read_once()
                    if t is None:
                        print("Sensor not responding")
                    else:
                        print("Temperature: {:.1f} C
                        Humidity: {:.1f} %".format(t, h))
                        time.sleep(INTERVAL_S)

Expected output in the Thonny shell:

Output
Temperature: 24.6 C   Humidity: 51.3 %
Temperature: 24.6 C   Humidity: 51.2 %

Why the retries and checks? The DHT protocol is timing-sensitive, and an occasional read fails with OSError: [Errno 116] ETIMEDOUT, especially on long wires or right after power-up. Retrying a couple of times hides those blips; a sensor that fails every time has a wiring problem. Never replace a failed reading with 0, because that looks like a real (and alarming) value.

3. Useful derived values: dew point and heat index

main.py
import math
def dew_point(t, rh):
    a, b = 17.62, 243.12
    # Magnus formula constants
    g = (a * t) / (b + t) + math.log(rh / 100)
    return (b * g) / (a - g)
    def heat_index_c(t, rh):
        # Rothfusz regression (valid above ~27 C and 40 % RH)
        f = t * 9 / 5 + 32
        hi = (-42.379 + 2.04901523 * f + 10.14333127 * rh - 0.22475541 * f * rh
        - 6.83783e-3 * f * f - 5.481717e-2 * rh * rh + 1.22874e-3 * f * f * rh
        + 8.5282e-4 * f * rh * rh - 1.99e-6 * f * f * rh * rh)
        return (hi - 32) * 5 / 9
        t, h = 30.0, 60.0
        print("Dew point {:.1f} C, feels like {:.1f} C".format(dew_point(t, h), heat_index_c(t, h)))

The dew point tells you when surfaces will get damp (useful for basements and 3D-printer filament storage); the heat index says how hot it feels. At 30 °C and 60 % RH you should see a dew point of about 21 °C and a heat index of about 33 °C.

Log readings to a CSV file on the board

The ESP32's flash has a small filesystem, handy for logging without Wi-Fi. This appends one line per minute and keeps the file from growing forever:

main.py
import dht, time, os
from machine import Pin
sensor = dht.DHT22(Pin(4))
LOG = "log.csv"
MAX_BYTES = 100_000
# about 4,000 lines
while True:
    try:
        sensor.measure()
        line = "{},{:.1f},{:.1f}\n".format(time.time(), sensor.temperature(), sensor.humidity())
        if LOG in os.listdir() and os.stat(LOG)[6] > MAX_BYTES:
            os.rename(LOG, "log_old.csv")
            # keep one previous file
            with open(LOG, "a") as f:
                f.write(line)
            except OSError as e:
                print("Skipped:", e)
                time.sleep(60)

Copy log.csv to your computer from Thonny's file panel and open it in a spreadsheet. time.time() counts seconds since the board's epoch; sync the clock with ntptime.settime() after connecting to Wi-Fi if you need real dates. Flash has a limited number of write cycles, so log every minute or slower rather than every second.

How the DHT protocol works

The DHT sensors use a custom one-wire protocol, not I2C. The ESP32 pulls the data line low for a few milliseconds to say "measure now"; the sensor answers with 40 bits (humidity, temperature and a checksum), where the length of each high pulse encodes a 0 or a 1, measured in microseconds. MicroPython's dht module does this timing in C for you.

That explains the typical problems: long wires, weak pull-ups, or a busy CPU distort the pulse lengths, the checksum fails, and measure() raises OSError. It's also why the sensors can only be read every 1–2 seconds: each reading triggers a new internal measurement.

4. Getting accurate readings

  • Keep the sensor away from the ESP32. The board's regulator and radio warm the air by a degree or more; a 10–20 cm cable fixes it.
  • Give it airflow and keep it out of direct sun. Outdoors, use a ventilated radiation shield.
  • Let it settle. After power-up or a move, wait a few minutes before trusting the numbers.
  • Check against a reference. Compare with a known-good thermometer/hygrometer for an hour and note the offset. A constant offset can be subtracted in code; a drifting one means a worn or damaged sensor.
  • Avoid condensation. DHT sensors don't like being wet; long periods above 90 % RH can shift readings.

5. Troubleshooting

SymptomLikely causeFix
OSError: [Errno 116] ETIMEDOUT every timeWrong pin, no power, missing pull-up, DHT11/DHT22 class mismatchCheck wiring; add 10 kΩ pull-up on bare sensors; use the right class
Occasional ETIMEDOUTNormal glitch, long wire or reading too oftenRetry as shown; read every 2 s or slower
DHT22 always reads e.g. 0.0 / 25.5 / odd stepsUsing dht.DHT11 for a DHT22Use dht.DHT22
Temperature a few °C highSelf-heating from the ESP32 nearbyMove the sensor away on a cable
Humidity stuck at 99.9 %Condensation, or a damaged sensorDry it out; replace if it doesn't recover
Works on USB, fails on batterySupply drooping during Wi-Fi burstsBetter regulator or capacitor; power the sensor from 3.3 V
ImportError: no module named 'dht'Unusual firmware buildFlash the standard ESP32 MicroPython firmware
Fails on GPIO34–39Input-only pinsUse GPIO4 or another output-capable pin

Validate readings and protect the sensor in a real installation

A successful measure() call only proves that the ESP32 received a valid response. It does not prove that the reading represents the room accurately. Placement, airflow, supply quality and the sensor's limitations matter just as much as the code.

A practical validation routine

  1. Place the DHT sensor beside a trusted thermometer and hygrometer, away from sunlight, windows, fans and the ESP32 regulator.
  2. Power both devices for several minutes before comparing values. The DHT package and its surroundings need time to settle.
  3. Record readings at the permitted interval for at least 30–60 minutes. Compare the trend as well as individual samples; a single matching value is not a calibration.
  4. Note any consistent offset, but do not use a correction factor to hide large or changing errors. If the offset drifts, inspect placement, condensation, wiring and sensor condition.
  5. Repeat the comparison after moving the sensor or changing its enclosure.

The DHT11 and DHT22 are low-cost learning sensors, not laboratory instruments. Their response is relatively slow, their accuracy is limited, and they should not be used as the only input for safety-critical temperature or humidity control. For a controlled greenhouse, storage room or equipment enclosure, compare the DHT against a better reference and consider a sensor with a published calibration specification.

Power and wiring details that prevent intermittent faults

The ESP32 uses 3.3 V logic. A bare DHT sensor normally needs a pull-up resistor from DATA to the sensor's supply. Many three-pin breakout modules already include that resistor, so adding another one may be unnecessary. Check the board's schematic or inspect the module before changing the circuit.

Be especially careful with breakout boards powered from 5 V: some modules pull DATA up to their VCC rail. A 5 V data level must not be applied directly to an ESP32 GPIO. Use a 3.3 V supply when the module supports it, or use a suitable level-shifting arrangement and verify the actual DATA voltage with a meter. Share ground between the sensor and ESP32, and keep the data lead short for the first test.

Make the application resilient

Keep the last known-good reading separate from a failed sample. If a read fails, log the error and mark the new sample unavailable; do not silently substitute zero or reuse an old value without a timestamp. For a dashboard or MQTT publisher, include a sample timestamp or sequence number so consumers can tell a fresh measurement from stale data.

Use a sensible reporting interval. Reading a DHT22 faster than its specified interval does not produce better data and can increase errors. If the project needs smooth display values, apply a small rolling average to valid readings while retaining the raw value for diagnosis. Averages reduce short-term noise but cannot correct a badly placed or inaccurate sensor.

FAQ

Do I need a library for DHT22 in MicroPython? No. The dht module is built into the ESP32, ESP8266 and Pico MicroPython firmware.

Can I use several DHT sensors? Yes, one GPIO per sensor: dht.DHT22(Pin(4)), dht.DHT22(Pin(5))…

DHT22 or BME280? The BME280 is more accurate, adds pressure, uses I2C and is faster to read. The DHT22 is cheaper and simpler.

How long can the wire be? A few metres usually works with a stiff 4.7–10 kΩ pull-up and a 5 V supply; keep it short on 3.3 V.

Does this work on a Raspberry Pi Pico? Yes: same code, any Pico GPIO, e.g. dht.DHT22(Pin(15)).

Next steps

Official reference: MicroPython DHT driver.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.