from machine import Pin
import utime
import dht
# LED
red = Pin(4, Pin.OUT)
yellow = Pin(3, Pin.OUT)
green = Pin(2, Pin.OUT)
# 感測器
sensor = dht.DHT22(Pin(28))
pir = Pin(19, Pin.IN)
traffic_states = [
[1, 0, 0, 4],
[0, 0, 1, 3],
[0, 1, 0, 1],
]
state = 0
print(">>> 交通燈狀態機啟動...")
while True:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
r, y, g, duration = traffic_states[state]
# 只在綠燈狀態判斷
if state == 1 and temp > 30:
duration = 1
red.value(r)
yellow.value(y)
green.value(g)
state_names = ["🔴 紅燈", "🟢 綠燈", "🟡 黃燈"]
print(f"{state_names[state]} | {temp:.1f}°C {hum:.1f}% | {duration}s")
utime.sleep(duration)
state = (state + 1) % len(traffic_states)
# PIR 偵測
if pir.value() == 1:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print(f"⚠️ 偵測到移動!溫度:{temp:.1f}°C 濕度:{hum:.1f}%")
utime.sleep(3)