Built-in project · Raspberry Pi Pico W

Pico W ten-second game with a tilt switch

MicroPython on a Pico W: shake a tilt switch on GP16 to start and stop a stopwatch on a four-digit display; stop it on exactly 10.00 to win. The whole build, a Raspberry Pi Pico W and 8 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.

Teaching? Assign it to your class in one click.

Intermediate About 30 minutes to build and run. Runs in your browser. Free, and no account needed.

The parts retail for about $7.90. On Mokxi they're free.

Pico W ten-second game with a tilt switch · Raspberry Pi Pico Wlive0.000 s 0.00x
Press Run, then tip the switch to start and again to stop
The circuit itself, running here on the simulator. Press what can be pressed; click anything else to open it in the editor.

What you'll learn

  • Interrupts that set a flag
  • Debouncing a switch with timestamps
  • Using ticks_ms and ticks_diff for timing
  • Multiplexing a four-digit display
  • Sending a byte to a shift register
  • Difficulty: Intermediate
  • Time: About 30 minutes
  • Board: Raspberry Pi Pico W
  • Parts: 12

How it works

Shake the tilt switch on GP16 to start a stopwatch, and shake it again to stop. The four-digit display shows seconds and hundredths, like 07.42. Stop it at exactly 10.00 and the Shell prints You win!

The tilt switch triggers an interrupt that only sets a flag. The main loop then checks the flag, ignores shakes less than 300 ms apart, and starts or stops the clock. A 74HC595 sets the segments and GP10 to GP13 pick each digit in turn.

Parts list

12 parts, plus the jumper wires. They retail for about $7.90; on Mokxi they're free.

Kits that can build it

This starter kit has every part in the circuit. Each kit's page lists what else it can build.

Wiring table

Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.

Part and pinConnects to
Resistor, 220 Ω (1) pin 2Raspberry Pi Pico W pin GP10
Resistor, 220 Ω (2) pin 2Raspberry Pi Pico W pin GP11
Resistor, 220 Ω (3) pin 2Raspberry Pi Pico W pin GP12
Resistor, 220 Ω (4) pin 2Raspberry Pi Pico W pin GP13
74HC595 shift register pin SHCPRaspberry Pi Pico W pin GP20
74HC595 shift register pin STCPRaspberry Pi Pico W pin GP19
74HC595 shift register pin DSRaspberry Pi Pico W pin GP18
Tilt switch pin 2Raspberry Pi Pico W pin GP16
Resistor, 10k Ω pin 1Raspberry Pi Pico W pin GP16
Four-digit seven segment, multiplexed pin B74HC595 shift register pin Q1
Four-digit seven segment, multiplexed pin C74HC595 shift register pin Q2
Four-digit seven segment, multiplexed pin D74HC595 shift register pin Q3
Four-digit seven segment, multiplexed pin E74HC595 shift register pin Q4
Four-digit seven segment, multiplexed pin F74HC595 shift register pin Q5
Four-digit seven segment, multiplexed pin G74HC595 shift register pin Q6
Four-digit seven segment, multiplexed pin DP74HC595 shift register pin Q7
74HC595 shift register pin GNDGround
74HC595 shift register pin MR3.3 V
74HC595 shift register pin OEGround
Four-digit seven segment, multiplexed pin A74HC595 shift register pin Q0
74HC595 shift register pin VCC3.3 V
Resistor, 220 Ω (4) pin 1Four-digit seven segment, multiplexed pin DIG4
Resistor, 220 Ω (3) pin 1Four-digit seven segment, multiplexed pin DIG3
Resistor, 220 Ω (2) pin 1Four-digit seven segment, multiplexed pin DIG2
Resistor, 220 Ω (1) pin 1Four-digit seven segment, multiplexed pin DIG1
Tilt switch pin 13.3 V
Resistor, 10k Ω pin 2Ground

The code

The MicroPython code exactly as the editor opens it. Change a line there and press Run: the board runs it on the official MicroPython firmware, with nothing to compile.

main.py · Raspberry Pi Pico W
# GAME: 10 seconds. Shake the tilt switch (GP16) to start a stopwatch,
# shake it again to stop. Stop it on exactly 10.00 seconds to win.
from machine import Pin
import time

DIGITS = [0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F]
ds = Pin(18, Pin.OUT)
latch = Pin(19, Pin.OUT)
clock = Pin(20, Pin.OUT)
selects = [Pin(n, Pin.OUT, value=1) for n in (10, 11, 12, 13)]   # digit 1 to 4

def segments(byte):
    for i in range(7, -1, -1):
        ds.value((byte >> i) & 1)
        clock.value(1)
        clock.value(0)
    latch.value(1)
    latch.value(0)

def show(text):
    # text is four characters, digits or spaces, with an optional "." after
    # one of them. Each digit is lit for a moment in turn, fast enough
    # that the eye sees all four.
    cells = []
    for ch in text:
        if ch == "." and cells:
            cells[-1] |= 0x80
        else:
            cells.append(DIGITS[int(ch)] if ch.isdigit() else 0)
    for n, byte in enumerate(cells[-4:]):
        segments(byte)
        selects[n].value(0)
        time.sleep_ms(2)
        selects[n].value(1)

running = False
began = 0
elapsed = 0
shaken = False

def shake(pin):
    global shaken
    shaken = True

Pin(16, Pin.IN).irq(trigger=Pin.IRQ_RISING, handler=shake)
last = time.ticks_add(time.ticks_ms(), -1000)
print("shake to start")

while True:
    if shaken:
        shaken = False
        now = time.ticks_ms()
        if time.ticks_diff(now, last) > 300:      # one shake, not its bounces
            last = now
            if running:
                running = False
                elapsed = time.ticks_diff(now, began)
                print("stopped at %.2f s" % (elapsed / 1000))
                print("You win!" if elapsed // 10 == 1000 else "Try again")
            else:
                running = True
                began = now
                print("go")
    if running:
        elapsed = time.ticks_diff(time.ticks_ms(), began)
    hundredths = elapsed // 10 % 10000
    show("%02d.%02d" % (hundredths // 100, hundredths % 100))

Code walkthrough

The key functions of the sketch, and what each one does.

segments main.py

Sends one byte to the 74HC595, one bit at a time, from bit 7 down to bit 0, pulsing the clock after each. Then it pulses the latch so all eight outputs change together.

def segments(byte):
    for i in range(7, -1, -1):
        ds.value((byte >> i) & 1)
        clock.value(1)
        clock.value(0)
    latch.value(1)
    latch.value(0)

show main.py

Turns a four character string into segment bytes, adding the decimal point when it sees a dot. Then it lights each digit for 2 ms in turn. Done repeatedly, all four look lit.

def show(text):
    # text is four characters, digits or spaces, with an optional "." after
    # one of them. Each digit is lit for a moment in turn, fast enough
    # that the eye sees all four.
    cells = []
    for ch in text:
        if ch == "." and cells:
            cells[-1] |= 0x80
        else:
            cells.append(DIGITS[int(ch)] if ch.isdigit() else 0)
    for n, byte in enumerate(cells[-4:]):
        segments(byte)
        selects[n].value(0)
        time.sleep_ms(2)
        selects[n].value(1)

shake main.py

The interrupt handler. It only sets shaken to True and returns, so the interrupt stays short. The main loop does the real work.

def shake(pin):
    global shaken
    shaken = True

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • One shake counts as two This project
    Switches bounce. The 300 ms check in the loop ignores the extra pulses, so keep it.
  • Shaking does nothing This project
    Check that the tilt switch connects GP16 to 3.3 V, and the 10k resistor pulls GP16 to ground.
  • Outputs show garbage, or the register never clears. 74HC595 shift register
    Tie OE low and SRCLR (pin 10) high. Left floating, these pins make the chip behave randomly. Then pulse the latch pin after shifting the byte.
  • The bits come out in the wrong order, or LEDs are dim. 74HC595 shift register
    Choose MSBFIRST or LSBFIRST in shiftOut to flip the order. Give each LED its own resistor, since each output can source only about 6 mA safely.
  • Digits look dim, flicker, or show ghosts of other digits. Four-digit seven segment
    Refresh each digit quickly in a loop, at least 100 Hz for the whole set. Turn all segments off before switching digits. Do not use delay() for long pauses while displaying.
  • Segments burn out or the pins are overloaded. Four-digit seven segment
    Use a resistor of about 220 ohms on each segment line. Check whether the display is common cathode or common anode, since that sets which level turns a segment on.
  • The LED is dim, burns out, or the pin reads wrong because the resistor value is off. Resistor
    Read the color bands again. A 220 ohm to 330 ohm resistor suits a typical LED on 5 V. 10k is a common pull-up or pull-down value. Check with a multimeter if unsure.
  • A pull-up or pull-down resistor is missing, so the input floats and reads random values. Resistor
    Tie the input to 5 V or ground through about 10k. Or use INPUT_PULLUP and wire the switch to ground.

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.