from machine import Pin, Timer
import utime

# 定義一個包含顏色和引腳號碼元組的列表
color_and_pin_list = [('red', 23), ('yellow', 22), ('green', 21)]
# 使用字典理解來創建 'leds' 字典
leds = {color: Pin(pin, Pin.OUT) for color, pin in color_and_pin_list}

# 定義一個包含按鈕顏色和引腳號碼元組的列表
button_and_pin_list = [('red_b', 32), ('yellow_b', 33), ('green_b', 25), ('blue_b', 4)]
# 使用字典理解來創建 'buttons' 字典
buttons = {color: Pin(pin, Pin.IN, Pin.PULL_UP) for color, pin in button_and_pin_list}

auto_mode = True

# 定義更改交通燈的回調函數
def change_light(t):
    if leds['red'].value():
        leds['red'].off()
        leds['green'].on()
        auto_mode_timer.init(period=700, mode=Timer.ONE_SHOT, callback=change_light)
    elif leds['green'].value():
        leds['green'].off()
        leds['yellow'].on()
        auto_mode_timer.init(period=200, mode=Timer.ONE_SHOT, callback=change_light)
    else:
        leds['yellow'].off()
        leds['red'].on()
        auto_mode_timer.init(period=500, mode=Timer.ONE_SHOT, callback=change_light)

# 定義檢查按鈕的回調函數
def check_buttons(t):
    if not buttons['red_b'].value():
        leds['red'].on()
        leds['yellow'].off()
        leds['green'].off()
    elif not buttons['yellow_b'].value():
        leds['red'].off()
        leds['yellow'].on()
        leds['green'].off()
    elif not buttons['green_b'].value():
        leds['red'].off()
        leds['yellow'].off()
        leds['green'].on()

# 初始化自動模式計時器
auto_mode_timer = Timer(0)
leds['green'].on()
auto_mode_timer.init(period=700, mode=Timer.ONE_SHOT, callback=change_light)

# 初始化按鈕檢查計時器
button_check_timer = Timer(1)
# button_check_timer.init(period=100, mode=Timer.PERIODIC, callback=check_buttons)

irq_isenable = True
def enable_irq(timer):  # Function to re-enable IRQ
    global irq_isenable  # Access global variable
    irq_isenable = True  # Re-enable IRQ

# 定義切換自動模式的ISR函數
def toggle_auto_mode(pin):
    global auto_mode, irq_isenable
    
    if irq_isenable:
        auto_mode = not auto_mode
        irq_isenable = False
        Timer(-1).init(mode=Timer.ONE_SHOT, period=200, callback=enable_irq)  # Start a one-shot timer
        if auto_mode:
           button_check_timer.deinit()
           auto_mode_timer.init(period=700, mode=Timer.ONE_SHOT, callback=change_light)
        else:
           auto_mode_timer.deinit()
           button_check_timer.init(period=50, mode=Timer.PERIODIC, callback=check_buttons)        
        print("自動模式:", auto_mode)

# 附加ISR到藍色按鈕(引腳4)
blue_button = buttons['blue_b']
blue_button.irq(trigger=Pin.IRQ_FALLING, handler=toggle_auto_mode)

print("自動模式:", auto_mode)
# 主循環保持空白,因為它現在是非阻塞的,不需要任何主動工作。
while True:
    utime.sleep_ms(50)