import dht
from machine import Pin
import utime
# ① 初始化感測器與 LED
pir = Pin(28, Pin.IN) # PIR 接 GP28
led = Pin(2, Pin.OUT) # LED 接 GP2
sensor = dht.DHT22(Pin(20)) # DHT22 接 GP20
print(">>> 智慧燈控與環境監測系統啟動...")
while True:
# 偵測 PIR 狀態
if pir.value() == 1:
led.on()
try:
# ② 讀取溫濕度
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
# ③ 輸出資訊
print(f"🔴 偵測到移動![環境資訊] 溫度:{t:.1f}°C,濕度:{h:.1f}%")
except OSError as e:
print("🔴 偵測到移動!(但 DHT22 讀取失敗)")
# ④ 燈維持亮 3 秒,這段時間不會重複偵測
utime.sleep(3)
else:
led.off()
# 靜止狀態下,減少 print 頻率,避免洗板
# 可以選擇不 print 或加入極短延遲
pass
utime.sleep_ms(200) # 降低 CPU 負擔