from machine import Pin, Timer
import utime

# Define a list to hold the color and pin number tuples
color_and_pin_list = [('red', 23), ('yellow', 22), ('green', 21)]
# Use a dictionary comprehension to create the 'leds' dictionary
leds = {color: Pin(pin, Pin.OUT) for color, pin in color_and_pin_list}

# Define a list to hold the button color and pin number tuples
button_and_pin_list = [('red_b', 32), ('yellow_b', 33), ('green_b', 25), ('blue_b', 4)]
# Use a dictionary comprehension to create the 'buttons' dictionary
buttons = {color: Pin(pin, Pin.IN, Pin.PULL_UP) for color, pin in button_and_pin_list}

def change_light(t):
    if leds['red'].value():      # If red is ON
        leds['red'].off()
        leds['green'].on()
        auto_mode_timer.init(period=700, mode=Timer.ONE_SHOT, callback=change_light)
    elif leds['green'].value():  # If green is ON
        leds['green'].off()
        leds['yellow'].on()
        auto_mode_timer.init(period=200, mode=Timer.ONE_SHOT, callback=change_light)
    else:                        # If yellow is ON
        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()

# Initialize timer
auto_mode_timer = Timer(0)
# Initialize the starting state and start the timer
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)

auto_mode = True

# Define the debounce time (in milliseconds)
debounce_time_ms = 150  # Adjust this value as needed
# Define the last button press time
last_button_press_time = 0

# Define the ISR function to toggle the auto_mode flag
def toggle_auto_mode(pin):
    global auto_mode, last_button_press_time
    current_time = utime.ticks_ms()
    press_time_diff = utime.ticks_diff(current_time, last_button_press_time)
    if  press_time_diff >= debounce_time_ms:
        last_button_press_time = current_time
        auto_mode = not auto_mode
        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)

# Attach the ISR to the blue button (Pin 5)
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)