from machine import Pin
import time
# 定義 LED 和按鈕的 GPIO 接腳
led_pins = [12, 14, 27] # 分別對應紅燈、黃燈、綠燈
button_pins = [17, 16, 4, 18] # 分別對應紅燈按鈕、黃燈按鈕、綠燈按鈕、模式切換按鈕
# 初始化 LED 和按鈕
leds = [Pin(pin, Pin.OUT) for pin in led_pins]
buttons = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in button_pins]
# 初始化變數
mode = "AUTO"
auto_stage = 0 # 自動模式階段
auto_timer = time.ticks_ms()
debounce_time = [0] * len(button_pins) # 去彈跳計時
# 持續時間設定(毫秒)
durations = [1000, 3000, 3000] # 紅燈、綠燈、黃燈的持續時間,按順序排列
switch_yellow_duration = 2000 # 切換到手動模式時黃燈亮2秒
# 去彈跳處理
def debounce(index):
if time.ticks_diff(time.ticks_ms(), debounce_time[index]) > 200 and not buttons[index].value():
debounce_time[index] = time.ticks_ms()
return True
return False
# 關閉所有 LED 燈
def turn_off_all():
for led in leds:
led.off()
# 自動模式
def auto_mode():
global auto_stage, auto_timer
now = time.ticks_ms()
# 控制當前燈光(紅燈 -> 綠燈 -> 黃燈)
turn_off_all()
if auto_stage == 0:
leds[0].on() # 紅燈亮
elif auto_stage == 1:
leds[2].on() # 綠燈亮
else:
leds[1].on() # 黃燈亮
# 切換到下一個燈光
if time.ticks_diff(now, auto_timer) > durations[auto_stage]:
auto_stage = (auto_stage + 1) % 3 # 循環切換:紅 -> 綠 -> 黃
auto_timer = now
# 手動模式
def manual_mode():
for i in range(3): # 0:紅燈, 1:黃燈, 2:綠燈
if debounce(i):
turn_off_all()
leds[i].on()
# 切換模式
def switch_mode():
global mode, auto_stage, auto_timer
if debounce(3): # 第4個按鈕是模式切換按鈕
if mode == "AUTO":
mode = "MANUAL"
print("切換至手動模式")
turn_off_all() # 關閉所有燈
leds[1].on() # 黃燈亮2秒
time.sleep_ms(switch_yellow_duration)
turn_off_all()
leds[0].on() # 黃燈後紅燈亮
else:
mode = "AUTO"
print("切換至自動模式")
turn_off_all() # 確保所有燈都被關閉
auto_stage = 0
auto_timer = time.ticks_ms()
# 主循環
while True:
switch_mode()
if mode == "AUTO":
auto_mode()
else:
manual_mode()