from machine import Pin, Timer
# 設定 LED 和按鈕引腳
led_pins = [Pin(2, Pin.OUT), Pin(16, Pin.OUT), Pin(19, Pin.OUT)] # 綠燈、黃燈、紅燈
button_pins = [Pin(13, Pin.IN, Pin.PULL_UP), Pin(27, Pin.IN, Pin.PULL_UP), Pin(26, Pin.IN, Pin.PULL_UP)] # 對應按鈕
# 定義每個按鈕對應的 LED 持續時間 (毫秒)
led_times = [3000, 1000, 2000]
# 使用單一計時器
timer = Timer(-1)
current_led = None
def button_isr(pin):
global current_led
# 找到按下的按鈕對應的 LED 索引
index = button_pins.index(pin)
# 關閉當前亮著的 LED
if current_led is not None:
led_pins[current_led].off()
# 開啟新按下按鈕對應的 LED 並啟動計時器
led_pins[index].on()
current_led = index
timer.init(period=led_times[index], mode=Timer.ONE_SHOT, callback=lambda t: led_pins[index].off())
# 設定按鈕中斷
for button in button_pins:
button.irq(trigger=Pin.IRQ_FALLING, handler=button_isr)