from machine import Pin
from time import ticks_ms
# Define pin assignments
button = Pin(18, Pin.IN, Pin.PULL_DOWN) # Button with pull-down
red = Pin(27, Pin.OUT) # Red LED
orange = Pin(26, Pin.OUT) # Orange LED
green = Pin(25, Pin.OUT) # Green LED
# Variables to track state
blinking_mode = True # Start in blinking mode
button_last_state = 0
button_press_time = ticks_ms()
last_blink_time = ticks_ms()
blink_on = False
# Cycle timers
cycle_state = 0
cycle_start_time = 0
def check_button():
global blinking_mode, button_last_state, button_press_time
button_state = button.value()
# Toggle mode when the button is pressed
if button_state == 1 and button_last_state == 0 and ticks_ms() - button_press_time > 200:
blinking_mode = not blinking_mode
button_press_time = ticks_ms() # Record the last button press time
button_last_state = button_state
def handle_blinking():
global last_blink_time, blink_on
# Handle non-blocking blinking for the orange LED
if ticks_ms() - last_blink_time >= 500: # 500ms interval
blink_on = not blink_on # Toggle LED state
orange.value(blink_on) # Update LED state
last_blink_time = ticks_ms() # Reset blink timer
def handle_led_cycle():
global cycle_state, cycle_start_time
elapsed = ticks_ms() - cycle_start_time
# Cycle through red, orange, and green LEDs based on state
if cycle_state == 0:
red.value(1)
if elapsed >= 5000: # Red LED for 5 seconds
red.value(0)
cycle_state = 1
cycle_start_time = ticks_ms()
elif cycle_state == 1:
orange.value(1)
if elapsed >= 1000: # Orange LED for 1 second
orange.value(0)
cycle_state = 2
cycle_start_time = ticks_ms()
elif cycle_state == 2:
green.value(1)
if elapsed >= 3000: # Green LED for 3 seconds
green.value(0)
cycle_state = 0 # Reset cycle
cycle_start_time = ticks_ms()
# Initialize cycle start time
cycle_start_time = ticks_ms()
while True:
check_button()
if blinking_mode:
# In blinking mode, blink the orange LED, others off
red.value(0)
green.value(0)
handle_blinking()
else:
# In cycle mode, cycle through the red, orange, and green LEDs
handle_led_cycle()