from machine import Pin
import time
# 初始化 3 個 LED 和 3 個按鈕
leds = [Pin(2, Pin.OUT), Pin(12, Pin.OUT), Pin(16, Pin.OUT)] # 綠燈、紅燈、黃燈分別連接到 GPIO 2, 12, 16
buttons = [Pin(4, Pin.IN, Pin.PULL_UP), Pin(13, Pin.IN, Pin.PULL_UP), Pin(18, Pin.IN, Pin.PULL_UP)] # 按鈕連接到 GPIO 4, 13, 18
# 每個燈的亮燈時間:綠燈 3 秒,紅燈 2 秒,黃燈 1 秒
durations = [3, 2, 1]
# 用於記錄當前的燈索引和是否開始循環
current_index = 0
start_cycle = False
interrupt_triggered = False
def button_handler(pin):
global current_index, start_cycle, interrupt_triggered
# 根據哪個按鈕被按下設置起始的燈
if pin == buttons[0]: # 綠燈按鈕
current_index = 0
elif pin == buttons[1]: # 紅燈按鈕
current_index = 1
elif pin == buttons[2]: # 黃燈按鈕
current_index = 2
start_cycle = True # 開始燈循環
interrupt_triggered = True # 中斷燈循環,從新開始
# 設置中斷處理程序
buttons[0].irq(trigger=Pin.IRQ_FALLING, handler=button_handler)
buttons[1].irq(trigger=Pin.IRQ_FALLING, handler=button_handler)
buttons[2].irq(trigger=Pin.IRQ_FALLING, handler=button_handler)
def cycle_lights():
global current_index, interrupt_triggered
while start_cycle:
# 若有中斷觸發,跳出循環重新開始
if interrupt_triggered:
interrupt_triggered = False
continue # 重新開始循環
# 熄滅所有燈
for led in leds:
led.off()
# 亮起當前燈
leds[current_index].on()
time.sleep(durations[current_index])
leds[current_index].off()
# 移動到下一個燈
current_index = (current_index + 1) % 3
while True:
if start_cycle:
cycle_lights()