CodeRigor

GUIDED LESSON / 4 OF 6

Read the device at a sensible interval

Connect the tested decision to DHT11 reads and LED outputs.

What moves through this step
  1. 01Measure
  2. 02Catch read failure
  3. 03Choose state
  4. 04Sleep 2 seconds

Transfer the two application files

Copy policy.py and main.py to the Pico using Thonny's device file browser. Run main.py interactively before relying on its automatic startup behavior.

Python
"""MicroPython on Pico W. DHT11 GP16; LED+resistor GP14/GP15 to GND."""
from machine import Pin
import dht
import json
import time
from policy import state_for

sensor = dht.DHT11(Pin(16))
green, red = Pin(14, Pin.OUT, value=0), Pin(15, Pin.OUT, value=0)
state = "unknown"
try:
    while True:
        temperature = humidity = None
        try:
            sensor.measure()
            temperature, humidity = sensor.temperature(), sensor.humidity()
        except OSError:
            pass
        state = state_for(temperature, humidity, state)
        green.value(state == "ok")
        red.value(state == "warm")
        print(json.dumps({"temperature_c": temperature, "humidity_pct": humidity, "state": state}))
        time.sleep_ms(2000)
finally:
    green.off()
    red.off()

The DHT11 uses a timed digital protocol. The two-second interval is deliberately slower than the documented one-second maximum sampling frequency. Repeated reads as fast as the loop can run would not create useful higher-frequency measurements.

A sensor read can raise OSError. That iteration emits a JSON record with missing values and unknown, and both LEDs turn off. The next iteration retries after the interval. The finally block turns both LEDs off when the running script exits through a normal exception or keyboard interrupt; pulling power simply removes power.

Observe one complete record

The REPL should show a line containing temperature_c, humidity_pct and state. Compare it with the LED. An object containing null readings is different from a valid zero-degree reading.

Try it

Disconnect USB power, remove the sensor's data wire, then reconnect USB and observe the missing-reading behavior. Restore the wiring with power unplugged and confirm that valid readings recover. Record what actually happened on your device; the host tests cannot establish these electrical behaviors.