The Pico plays a sequence of lights and notes. Repeat it on the buttons, and it plays it again with one more step. How long a sequence can you remember? This project uses outputs, inputs, PWM to make musical notes, lists, and a file to keep your best score even when the Pico is unplugged.
What you need
- A Raspberry Pi Pico of any kind, with headers, and a USB cable that carries data
- Four LEDs: red, yellow, green and blue
- Four resistors: 330 Ω (orange, orange, brown) for the red and yellow LEDs, and 100 Ω (brown, black, brown) for the green and blue
- Four tactile push buttons
- A passive piezo buzzer
- A large breadboard (or two small ones), jumper wires, and Thonny on your computer
Shopping list (8 items)
Some shop links are affiliate links (Amazon UK, Tooled Up): if you buy through one we may earn a small commission, at no extra cost to you. As an Amazon Associate I earn from qualifying purchases. It never changes which products we recommend, and no shop has paid to be included.
Everything for this build, in one place. One resistor kit and one LED pack cover this project and the others on the site.
- 1×
- 1×
- 1×
- 1×Resistor kit, 1/4 W (0.25 W) assorted valuesOne kit covers every resistor in our projects, and is cheaper than buying values one at a time.
- 4×Tactile push button, 6 mm, four legsThe small square breadboard kind. Packs of 10 or more are the cheapest way to buy them.
- 1×Passive piezo buzzerPassive, not active: the code plays tones, which needs a passive buzzer. A bare buzzer or a buzzer module both work.
- 1×Full-size breadboard (830 points)Or two 400-point boards side by side.
- 1×
- FreeThonnyThe free Python editor. Nothing to buy.
Each button opens that shop's page for the part, checked when we wrote the list; if one shop is out of stock, try the next. Any equivalent part with the same value works.
Starting from nothing? A starter kit gives you the board, a breadboard and many of these parts in one box.
Why these values
The Pico's pins run at 3.3 V. Red and yellow LEDs drop about 2 V, so 330 Ω gives (3.3 − 2) ÷ 330 ≈ 4 mA. Blue LEDs, and many green ones, drop about 3 V, which leaves too little voltage for 330 Ω to light them well, so they use 100 Ω for about 3 mA. If your green LED is a standard yellow-green type and looks much brighter than the others, use 330 Ω for it instead.
The buttons use the Pico's built-in pull-up resistors, so they need no resistors of their own: each reads 1 normally and 0 while pressed. A small passive piezo buzzer draws very little current and can go straight on a pin. A larger magnetic buzzer would need a transistor.
The circuit
| Part | Pico GPIO | Physical pin |
|---|---|---|
| Red LED (through 330 Ω) | GP10 | 14 |
| Yellow LED (through 330 Ω) | GP11 | 15 |
| Green LED (through 100 Ω) | GP12 | 16 |
| Blue LED (through 100 Ω) | GP13 | 17 |
| Red button | GP2 | 4 |
| Yellow button | GP3 | 5 |
| Green button | GP4 | 6 |
| Blue button | GP5 | 7 |
| Buzzer + | GP15 | 20 |
| All LED short legs, the other side of every button, and buzzer − | GND | 3, 8, 13 or 18 |
- Unplug the Pico and push it into the breadboard across the centre gap. Run a jumper from a GND pin to the blue (−) rail.
- For each LED: a resistor from its GPIO pin to an empty row, the LED's long leg in that row, and its short leg in the ground rail.
- For each button: put it across a gap, wire one leg to its GPIO pin and the diagonally opposite leg to the ground rail. Place each button next to its LED so you know which is which.
- Wire the buzzer from GP15 to the ground rail.
Our Pico pinout guide shows where each pin is.
Step 1: test the parts
Run this in Thonny with MicroPython selected. Each LED should light in turn with a note, then the shell prints the number of any button you press.
from machine import Pin, PWM
import time
leds = [Pin(p, Pin.OUT) for p in (10, 11, 12, 13)]
buttons = [Pin(p, Pin.IN, Pin.PULL_UP) for p in (2, 3, 4, 5)]
buzzer = PWM(Pin(15))
for led, note in zip(leds, (262, 330, 392, 523)):
led.on()
buzzer.freq(note)
buzzer.duty_u16(32768)
time.sleep(0.4)
buzzer.duty_u16(0)
led.off()
while True:
for i, b in enumerate(buttons):
if b.value() == 0:
print("button", i)
time.sleep(0.1)
Buttons are numbered 0 to 3 in the order red, yellow, green, blue. Press Stop when everything works.
Step 2: the game
Paste this into a new file and save it to the Pico as main.py, so the game starts whenever the Pico has power, then click Run.
# Memory game for a Raspberry Pi Pico: watch the sequence of lights
# and tones, then repeat it on the buttons. Each round adds one more step.
from machine import Pin, PWM
import time
import random
LED_PINS = (10, 11, 12, 13) # red, yellow, green, blue LEDs
BUTTON_PINS = (2, 3, 4, 5) # one button per LED, wired to GND
NOTES = (262, 330, 392, 523) # C, E, G and high C, in hertz
leds = [Pin(p, Pin.OUT) for p in LED_PINS]
buttons = [Pin(p, Pin.IN, Pin.PULL_UP) for p in BUTTON_PINS]
buzzer = PWM(Pin(15))
buzzer.duty_u16(0) # silent to start with
TIMEOUT_MS = 3000 # how long you get for each press
def play(i, ms):
"""Light LED i and sound its note for ms milliseconds."""
leds[i].on()
buzzer.freq(NOTES[i])
buzzer.duty_u16(32768) # 50% duty: loudest for a piezo
time.sleep_ms(ms)
buzzer.duty_u16(0)
leds[i].off()
def read_press():
"""Wait for one press. Returns the button number, or None if too slow."""
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < TIMEOUT_MS:
for i, b in enumerate(buttons):
if b.value() == 0: # pressed
leds[i].on()
buzzer.freq(NOTES[i])
buzzer.duty_u16(32768)
while b.value() == 0: # wait for release
time.sleep_ms(10)
buzzer.duty_u16(0)
leds[i].off()
time.sleep_ms(50) # let the contacts stop bouncing
return i
time.sleep_ms(5)
return None
def game_over(score):
buzzer.freq(110) # low buzz
buzzer.duty_u16(32768)
for led in leds:
led.on()
time.sleep_ms(800)
buzzer.duty_u16(0)
for led in leds:
led.off()
print("Game over. Score:", score)
def load_best():
try:
with open("best.txt") as f:
return int(f.read())
except (OSError, ValueError): # no file yet, or it's damaged
return 0
best = load_best()
print("Best so far:", best)
while True:
print("Press any button to start")
while read_press() is None:
pass
time.sleep_ms(500)
sequence = []
while True:
sequence.append(random.randint(0, 3)) # add one more step
speed = max(150, 500 - 25 * len(sequence)) # play faster as it gets longer
for step in sequence:
play(step, speed)
time.sleep_ms(speed // 2)
correct = True
for step in sequence:
if read_press() != step: # wrong button, or too slow
correct = False
break
if not correct:
break
time.sleep_ms(600) # pause before the next round
score = len(sequence) - 1 # rounds completed
game_over(score)
if score > best:
best = score
with open("best.txt", "w") as f:
f.write(str(best))
print("New best score!")
time.sleep_ms(1000)
Press any button to start. Watch the first light, then press its button. Each round adds one more step and plays a little faster. Press the wrong button, or take more than 3 seconds, and the game buzzes, lights everything and shows your score in the shell.
How it works
- Notes with PWM. PWM switches a pin on and off very fast.
buzzer.freq(262)sets 262 times a second, the note middle C, andduty_u16(32768)makes it on for half of each cycle, which gives a piezo its loudest sound. A duty of 0 silences it. The four notes, C, E, G and the C above, make a pleasant chord whatever order they come in. - The sequence.
sequenceis a list that grows by one random step each round, usingrandom.randint(0, 3). The game plays the whole list, then checks your presses against it one by one. - Reading a press.
read_press()watches all four buttons. When one goes to 0, it lights that LED and plays its note until you let go, then waits 50 ms for the contacts to stop bouncing.time.ticks_diff()measures the 3-second limit correctly even when the Pico's millisecond counter wraps round. - Saving your best score. The best score goes in a file called
best.txton the Pico's flash, so it survives being unplugged. If the file doesn't exist yet, or is damaged,load_best()starts from 0 rather than crashing. - Tested. We ran this exact code on a simulated Pico with a simulated player who copies the lights, makes a deliberate mistake at a chosen round, and lets one game time out. The scores and the saved best score came out right every time.
Troubleshooting
- A button lights the wrong LED: its wire goes to the wrong GPIO. Use the test code to check the numbering.
- A game starts or ends on its own: a button is wired across legs that are always connected. Use diagonally opposite legs.
- No sound: check the buzzer is on GP15 (pin 20). An active buzzer will make one fixed pitch rather than four notes, so use a passive one.
- Best score won't reset: delete
best.txtfrom the Pico in Thonny's Files pane (View, then Files).
Take it further
- Show the score on an LED bar, or add a small display.
- Make a two-player version where players take turns adding a step to the sequence.
- Read our guide to Python lists and dictionaries to see more you can do with the
sequencelist.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.