from machine import Pin, Timer
import time
# ======================
# 配置
# ======================
DELAY_SEC = 5
CHECK_MS = 200
PIR_PIN = 13
RADAR_PIN = 15
RELAY_PIN = 14
# ======================
# 硬件初始化(关键修复!)
# ======================
# 传感器都用 PULL_DOWN 下拉,防止开机误判
pir = Pin(PIR_PIN, Pin.IN, Pin.PULL_DOWN)
radar = Pin(RADAR_PIN, Pin.IN, Pin.PULL_DOWN)
relay = Pin(RELAY_PIN, Pin.OUT, value=0)
# ======================
# 计时变量
# ======================
last_pir = time.ticks_ms()
last_radar = time.ticks_ms()
light_on = False
# ======================
# 核心检测
# ======================
def check_sensors(t):
global last_pir, last_radar, light_on
now = time.ticks_ms()
# ======================
# 正确电平:没人=0,有人=1
# 你之前反了!!!
# ======================
pir_occupied = pir.value() == 1
radar_occupied = radar.value() == 1
# 有人 → 刷新时间
if pir_occupied:
last_pir = now
if radar_occupied:
last_radar = now
# 判断超时
pir_timeout = time.ticks_diff(now, last_pir) > DELAY_SEC * 1000
radar_timeout = time.ticks_diff(now, last_radar) > DELAY_SEC * 1000
someone = not pir_timeout or not radar_timeout
# 开灯
if someone and not light_on:
relay.value(1)
light_on = True
print("[开灯] 检测到人体")
# 关灯
elif not someone and light_on:
relay.value(0)
light_on = False
print(f"[关灯] {DELAY_SEC}秒无人")
# 状态打印
if light_on:
print(f"PIR: {'有人' if pir_occupied else '无人'} | 雷达: {'有人' if radar_occupied else '无人'} | 灯亮")
# ======================
# 启动
# ======================
tim = Timer(0)
tim.init(period=CHECK_MS, mode=Timer.PERIODIC, callback=check_sensors)
print("==================================")
print(" 双传感器 最终正确版")
print(" 开机不会误触发")
print("==================================")