Skip to content

Instantly share code, notes, and snippets.

@ice09
Created January 31, 2024 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ice09/14f9be35a174b91c64172860f05fd4d7 to your computer and use it in GitHub Desktop.
Save ice09/14f9be35a174b91c64172860f05fd4d7 to your computer and use it in GitHub Desktop.
Ampelgehampel in Micropython for Raspberry Pico
# Transfer with Thonny
from machine import Pin, Timer
import utime
# Initialize LEDs
led1_r = Pin(2, Pin.OUT)
led1_y = Pin(3, Pin.OUT)
led1_g = Pin(4, Pin.OUT)
led2_r = Pin(6, Pin.OUT)
led2_y = Pin(7, Pin.OUT)
led2_g = Pin(8, Pin.OUT)
led3_r = Pin(21, Pin.OUT)
led3_y = Pin(20, Pin.OUT)
led3_g = Pin(19, Pin.OUT)
led4_r = Pin(26, Pin.OUT)
led4_y = Pin(27, Pin.OUT)
led4_g = Pin(22, Pin.OUT)
timer = Timer()
# States and Timing
state = 1
state_durations = [3, 1, 3, 1] # Duration for each state in seconds
state_timer = 0
def update_lights(state):
if state == 1: # 1 and 3 red, 2 and 4 green
set_lights(led1_r, led3_r, True)
set_lights(led2_g, led4_g, True)
set_lights(led1_g, led1_y, led3_g, led3_y, led2_r, led2_y, led4_r, led4_y, False)
elif state == 2: # All yellow
set_all_lights(False)
set_lights(led1_y, led2_y, led3_y, led4_y, True)
elif state == 3: # 1 and 3 green, 2 and 4 red
set_lights(led1_g, led3_g, True)
set_lights(led2_r, led4_r, True)
set_lights(led1_r, led1_y, led3_r, led3_y, led2_g, led2_y, led4_g, led4_y, False)
elif state == 4: # All yellow (second yellow stage)
set_all_lights(False)
set_lights(led1_y, led2_y, led3_y, led4_y, True)
def set_all_lights(value):
set_lights(led1_r, led1_y, led1_g, led2_r, led2_y, led2_g, led3_r, led3_y, led3_g, led4_r, led4_y, led4_g, value=value)
def set_lights(*leds, value):
for led in leds:
led.value(value)
def tick(timer):
global state, state_timer
update_lights(state)
state_timer += 1
if state_timer >= state_durations[state - 1]:
state_timer = 0
state = (state % 4) + 1 # Cycle through states 1 to 4
# Initialize all lights on for 3 seconds before starting the loop
set_all_lights(True)
utime.sleep(3) # Keep all lights on for 3 seconds
timer.init(freq=1, mode=Timer.PERIODIC, callback=tick) # Frequency set to 1 Hz (one tick per second)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment