capteur-dht.py

Raspberry Pi Pico · File : capteur-dht.py · Language : Python · Use case : Relever température et humidité avec un capteur DHT

The dht module built into MicroPython drives DHT11/DHT22 sensors on any pin. The script measures every 2 s (the sensor minimum rate), catches frame errors and prints temperature and humidity.

Hardware

A Raspberry Pi Pico (RP2040 dual Cortex-M0+ @ 133 MHz) with MicroPython installed, powered over USB. 1 DHT22 (or DHT11) sensor in a 3 or 4-pin package + 10 kΩ resistor for bare sensors.

Wiring

VDD to 3V3 (or 5 V per sensor), GND, DATA to GP4 with a 10 kΩ pull-up to VDD. On 3-pin modules the resistor is built in.

How it works

capteur.measure() sends the start pulse then decodes the 1-wire frame; temperature()/humidity() return the latest values. An OSError means a lost frame, retried next cycle.

Running it

Install MicroPython if needed (hold BOOTSEL, plug USB, drop the .uf2 file), then copy the script to the board drive or via Thonny. The script auto-starts when named main.py.

Variants

Switch to the DHT11 (less accurate but cheaper) by changing the class, or log readings to CSV with the logging script.

capteur-dht.py

# Temperature + humidite avec DHT11/DHT22 via le module dht de MicroPython.
import dht
import machine
import time

# DHT22 sur GP4 (remplacer par dht.DHT11 pour un DHT11).
capteur = dht.DHT22(machine.Pin(4))

print("Lecture toutes les 2 s (Ctrl-C pour arreter)")

while True:
    try:
        capteur.measure()   # declenche la trame 1-fil
        t = capteur.temperature()      # degres Celsius
        h = capteur.humidity()         # % HR
        print("T = %.1f C | HR = %.1f %%" % (t, h))
    except OSError:
        # Trame corrompue (capteur occupe, cabling, alim instable).
        print("Echec de lecture, nouvelle tentative...")
    time.sleep(2)  # le DHT22 demande >= 2 s entre deux mesures

# Le module dht est inclus dans les images MicroPython officielles : 
# aucune bibliotheque externe a installer.

← Back to the board