import machine
import dht
import time
# DHT11 on GP15 (better than GP28)
sensor = dht.DHT11(machine.Pin(28))
# LEDs
led_cold = machine.Pin(14, machine.Pin.OUT)
led_moderate = machine.Pin(13, machine.Pin.OUT)
led_hot = machine.Pin(12, machine.Pin.OUT)
# Temperature thresholds (°C)
cold_max = 19 # <=19°C → Cold
moderate_min = 20 # 20–30°C → Moderate
moderate_max = 30
hot_min = 31 # >=31°C → Hot
while True:
try:
sensor.measure() # Take a reading
temp = sensor.temperature()
hum = sensor.humidity()
# Some sanity check
if temp > 60 or temp < 0:
print("Invalid temperature reading, retrying...")
time.sleep(2)
continue
print("Temperature:", temp, "°C Humidity:", hum, "%")
# Turn off all LEDs first
led_cold.value(0)
led_moderate.value(0)
led_hot.value(0)
# Turn on LED based on temperature
if temp <= cold_max:
led_cold.value(1)
print("Status: Cold")
elif moderate_min <= temp <= moderate_max:
led_moderate.value(1)
print("Status: Moderate")
elif temp >= hot_min:
led_hot.value(1)
print("Status: Hot")
except OSError as e:
print("Failed to read sensor:", e)
time.sleep(2) # DHT11 needs at least 1-2s between reads