This is the first project with Raspberry Pi Pico on Maker Pico. I used to developed this game with Micropython on ESP8266. As Pico has significant I/O pins than ESP8266, i believe this simple game will run even better. Maker Pico is a breakout board that enable easy access to Pico I/O pins to jump straight-to-the code than wiring.
The aim of this game is to stop the running led exactly on the target point (pulsing led). Let’s get started. Import library that we want to use. Then arrange the I/O pins for led in a list for simpler pin mode assignment. Spare some pins for button and buzzer.
#Andi Dinata #1 Mar 2021 #LED Running Game, MIT License from machine import Pin, PWM import utime import _thread import urandom ios=[2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,21,22,26,27,28] for pin in ios: Pin(pin, Pin.OUT) stopbtn=Pin(20, Pin.IN, Pin.PULL_UP) buzzer = PWM(Pin(18)) pwmpin=urandom.choice(ios)
Add the audio tune when we are on target or get missed. These are variables that will be used as buzzer’s frequency.
C4 = 262 D4 = 294 E4 = 330 E7 = 2637 C7 = 2093 G7 = 3136 happy = [E7, E7, 0, E7, 0, C7, E7, 0, G7, 0, 0, 0] sad = [C4,D4,E4,0] def tune(notes): for i in notes: if i == 0: buzzer.duty_u16(0) else: buzzer.freq(i) buzzer.duty_u16(19660) utime.sleep(0.15)
Next we create a function for the target led and pulse the light.
def pulse(pwmpin): pwm=PWM(Pin(pwmpin)) pwm.freq(1000) pwm.duty_u16(0) while True: for duty in range(0,65025,5): pwm.duty_u16(duty) utime.sleep(0.0001) for duty in range(65025,0,-5): pwm.duty_u16(duty) utime.sleep(0.0001)
Last function is to make the running led. In this function button status can be read to check if the running led hits the target. When it does, the happy tune will be played, otherwise the sad tune will sound before the code breaks to mark the stop of the entire code.
def running(): count=0 while True: Pin(ios[count]).value(1) utime.sleep(0.02) if stopbtn.value() == 0: if pwmpin == ios[count]: tune(happy) else: tune(sad) break Pin(ios[count]).value(0) utime.sleep(0.01) if count >= len(ios)-1: count=0 count += 1
To run both the running and pulsing led at the same time, Pico’s dual processor RP2040 supports the multithreading.
_thread.start_new_thread(running,()) _thread.start_new_thread(pulse(pwmpin),()) #end of code
Check how the game run on my IG post. Let me know if you plan to make one.
Until next post. Thank you