import time
from machine import Pin, Timer
# 設定 LED 和按鈕接腳
red_led = Pin(19, Pin.OUT) # 紅燈
green_led = Pin(2, Pin.OUT) # 綠燈
yellow_led = Pin(16, Pin.OUT) # 黃燈
led_pins = [red_led, green_led, yellow_led]
# 設定控制接鈕
mode_button = Pin(14, Pin.IN, Pin.PULL_UP) # 按鈕A (切換模式)
red_button = Pin(26, Pin.IN, Pin.PULL_UP) # 紅燈按鈕
green_button = Pin(13, Pin.IN, Pin.PULL_UP) # 綠燈按鈕
yellow_button = Pin(27, Pin.IN, Pin.PULL_UP) # 黃燈按鈕
button_pins = [red_button, green_button, yellow_button]
# 定義每個 LED 的持續時間 (毫秒)
auto_led_times = [2000, 3000, 1000] # 紅燈2秒, 綠燈3秒, 黃燈1秒
manual_led_times = [0, 0, 1000] # 黃燈1秒用於切換提示
# 計時器
timer = Timer(-1)
current_led = None
mode = "auto" # 初始為自動模式
last_pressed = 0
def switch_mode(pin): #按鈕A的設定
global mode, last_pressed
current_time = time.ticks_ms()
if current_time - last_pressed > 500: # 設置防抖間隔 (500 毫秒)
last_pressed = current_time
for led in led_pins: #關燈
led.off()
if mode == "auto":
mode = "manual"
switch_to_manual_mode() #手動模式
else:
mode = "auto"
switch_to_auto_mode() #自動模式
def switch_to_red(timer=None):
yellow_led.off()
red_led.on()
def switch_to_manual_mode(): #手動程式碼
global current_led
# 確保所有 LED 都關閉
for led in led_pins:
led.off()
if current_led != 0:
yellow_led.on()
timer.init(period=manual_led_times[2], mode=Timer.ONE_SHOT, callback=switch_to_red)
current_led = 0
else:
switch_to_red()
current_led = 0
def switch_to_auto_mode(): #自動程式碼
global current_led
# 確保所有 LED 都關閉
for led in led_pins:
led.off()
current_led = 0 # 重置當前 LED 為紅燈
red_led.on()
timer.init(period=auto_led_times[0], mode=Timer.ONE_SHOT, callback=lambda t: auto_cycle())
def auto_cycle(): #自動程式碼循環順序
global current_led
if mode == "auto":
if current_led is not None:
led_pins[current_led].off()
# 循環運行紅綠燈
current_led = (current_led + 1) % 3 if current_led is not None else 0
led_pins[current_led].on()
timer.init(period=auto_led_times[current_led], mode=Timer.ONE_SHOT, callback=lambda t: auto_cycle())
def manual_button_isr(pin):
global current_led, last_pressed
current_time = time.ticks_ms()
if current_time - last_pressed > 500: # 500 毫秒防抖動間隔
last_pressed = current_time
if mode == "manual":
index = button_pins.index(pin)
# 只有在按下其他顏色的按鈕時才關閉先前亮著的燈
if current_led is not None and current_led != index:
led_pins[current_led].off()
# 開啟新按鈕對應的燈
led_pins[index].on()
current_led = index
# 設定按鈕中斷
for button in button_pins:
button.irq(trigger=Pin.IRQ_FALLING, handler=manual_button_isr)
# 設定模式切換按鈕中斷
mode_button.irq(trigger=Pin.IRQ_FALLING, handler=switch_mode)
# 啟動初始的自動循環
auto_cycle()