Introduction to Python and Microcontrollers

Hygrothermograph (DHT11)

Read temperature and humidity from a DHT11 sensor and print both to the Shell.

New Concepts

DHT11

The DHT11 is a combined temperature and humidity sensor whose output is already calibrated by the manufacturer — no formulas or lookup tables needed, unlike the Thermistor. It uses a custom single-wire protocol to send data, so reading it relies on the dht driver module rather than a plain GPIO read.

DHT11 component

Pin Description
VCC Power, 3.3V–5.5V
SDA Data pin — single-wire communication
NC Not connected — has no function and should be left unwired
GND Ground

The sensor takes about 1 second to initialize after power-up.

Component List

Components

Circuit

Disconnect all power before building the circuit. Reconnect once verified.

Wiring Diagram

Wiring Diagram

Connections:

Schematic Diagram

Schematic Diagram

Code

File: 03_sensors/code/Hygrothermograph.py

import machine
import time
import dht

DHT = dht.DHT11(machine.Pin(21))

while True:
    try:
        DHT.measure()
        print('temperature:',DHT.temperature(),'humidity:',DHT.humidity())
        time.sleep_ms(2000)
    except:
        pass

How to Run

Online

  1. Open Thonny → 03_sensors/code/.
  2. Double-click Hygrothermograph.py.
  3. Click Run current script — temperature and humidity print to the Shell every 2 seconds.

Code Explanation

Associate the sensor with a pin

DHT = dht.DHT11(machine.Pin(21))

Creates a DHT11 object on GPIO21, the pin wired to the sensor’s SDA line.

Take a reading

DHT.measure()
print('temperature:',DHT.temperature(),'humidity:',DHT.humidity())

measure() triggers a fresh reading over the single-wire protocol; temperature() and humidity() then return the two values from that reading.

Wrap in try/except

while True:
    try:
        DHT.measure()
        ...
    except:
        pass

DHT11 reads occasionally fail (the single-wire timing is sensitive to interference). Wrapping each attempt in try/except means one failed read is silently skipped instead of crashing the loop.


Key Concepts

See Class dht for the full API reference.

Further Exploration

Back to Module

Adapted from Python_Tutorial.pdf Project 24.1