Build a reaction timer on a 4-digit display with the Raspberry Pi Pico

Build a reaction timer with the Raspberry Pi Pico: the display goes dark, the time starts at a random moment, and you press the button as fast as you can. You learn how timer interrupts drive a multiplexed 4-digit display,...
  • Level:Advanced
  • Duration: 1 h 30 min
  • Ages 12+
  • Platform: Raspberry Pi
Build a reaction timer on a 4-digit display with the Raspberry Pi Pico – EEMENTOR STEM™ lesson

How fast are you? In this project the Raspberry Pi Pico becomes a reaction timer. Press the button and the display goes dark. After a random wait of two to five seconds the numbers start counting, and you press again as fast as you can. The display stops on your reaction time, such as 0.245 seconds, and the Pico remembers your best score even after you unplug it. Press too early and you get Err: a false start. Behind the game are two ideas that make microcontrollers fast and reliable: a timer interrupt that keeps the display lit while your program does other things, and pin interrupts that catch a button press the moment it happens.

What you'll learn

  • How a 4-digit display shows four numbers with only 12 pins, by multiplexing
  • How a machine.Timer runs a function 1,000 times a second in the background
  • How Pin.irq() reacts to a button press and how to ignore switch bounce
  • How to time things with time.ticks_ms() and ticks_diff(), the safe way
  • How to build a program as a small state machine

What you need

  • Raspberry Pi Pico with MicroPython and header pins, a micro-USB cable and a computer with Thonny (see the previous lesson)
  • 4-digit 7-segment display, common cathode (ESP32 IoT Starter Kit)
  • 4 resistors, 220 Ω (ESP32 IoT Starter Kit)
  • 2 push buttons (ESP32 IoT Starter Kit)
  • Breadboard and jumper wires (ESP32 IoT Starter Kit)

Look after your Pico: a Pico pin can only supply a few milliamps. That is why the resistors go on the four digit pins: each one limits a whole digit to about 6 mA, shared by all its lit segments, and only one digit is on at any moment. The trade-off is that an 8 looks a little dimmer than a 1. Never connect the display without these resistors, and unplug the USB cable before you change the wiring.

Wiring

Push the display across the middle gap of the breadboard with the decimal points at the bottom. Most 12-pin displays number their pins like a chip: pin 1 is bottom-left, and the numbers run along the bottom to pin 6, then back along the top from pin 7 to pin 12. Bottom row, left to right: e, d, dp, c, g, D4. Top row, left to right: D1, a, f, D2, D3, b. If yours is different, look up the part number printed on its side.

Breadboard wiring diagram: 4-digit common-cathode 7-segment display with segments a to g on GP16 to GP22 and dp on GP26, digits D1 to D4 through 220 ohm resistors to GP10 to GP13, Go button on GP14 and Best button on GP15, both buttons to GND (pin 23) of a Raspberry Pi Pico.
Breadboard view. Check each connection against the wiring table below.
From To (Pico)
Segments a, b, c, d, e, f, g GP16, GP17, GP18, GP19, GP20, GP21, GP22 (pins 21, 22, 24, 25, 26, 27, 29)
Segment dp (decimal point) GP26 (pin 31)
Digit D1 → 220 Ω resistor GP10 (pin 14)
Digit D2 → 220 Ω resistor GP11 (pin 15)
Digit D3 → 220 Ω resistor GP12 (pin 16)
Digit D4 → 220 Ω resistor GP13 (pin 17)
Go button, one leg GP14 (pin 19)
Best button, one leg GP15 (pin 20)
Both buttons, the diagonally opposite leg The blue (−) rail → GND (pin 23)

The program

Open Thonny with the Pico connected, paste the program into a new file and save it on the Pico as main.py, so the game starts whenever the Pico gets power, even from a USB power bank. Click Run.

# Reaction timer on a 4-digit 7-segment display (common cathode) with the Raspberry Pi Pico.
# A timer interrupt lights one digit at a time; the buttons use pin interrupts.
from machine import Pin, Timer
import random
import time

SEG_PINS = (16, 17, 18, 19, 20, 21, 22, 26)   # segments a, b, c, d, e, f, g, dp
DIGIT_PINS = (10, 11, 12, 13)                 # digits D1-D4, each through a 220 ohm resistor
segments = [Pin(p, Pin.OUT, value=0) for p in SEG_PINS]
digits = [Pin(p, Pin.OUT, value=1) for p in DIGIT_PINS]   # HIGH = digit off (common cathode)
go_button = Pin(14, Pin.IN, Pin.PULL_UP)      # pressed = LOW
best_button = Pin(15, Pin.IN, Pin.PULL_UP)

# Which segments light up for each character (bit 0 = a ... bit 6 = g, bit 7 = dp)
FONT = {"0": 0x3F, "1": 0x06, "2": 0x5B, "3": 0x4F, "4": 0x66, "5": 0x6D, "6": 0x7D,
        "7": 0x07, "8": 0x7F, "9": 0x6F, " ": 0x00, "-": 0x40, "E": 0x79, "r": 0x50,
        "b": 0x7C, "o": 0x5C, "n": 0x54}

shown = [0, 0, 0, 0]       # the pattern for each digit, read by the timer interrupt
current = 0                # the digit that is lit right now

def encode(text):
    """Turn text such as '0.245' into four segment patterns, right-aligned."""
    out = []
    for ch in text:
        if ch == "." and out:
            out[-1] |= 0x80            # a dot joins the character before it
        else:
            out.append(FONT.get(ch, 0))
    return ([0, 0, 0, 0] + out)[-4:]

def show(text):
    patterns = encode(text)
    for i in range(4):
        shown[i] = patterns[i]

def refresh(timer):
    """Runs 1000 times a second: switch off the lit digit, light the next one."""
    global current
    digits[current].value(1)
    current = (current + 1) % 4
    pattern = shown[current]
    for i in range(8):
        segments[i].value((pattern >> i) & 1)
    digits[current].value(0)

# Button interrupts: note the time of each press, ignore bounces closer than 150 ms
pressed = [False, False]
press_time = [0, 0]

def make_handler(index):
    def handler(pin):
        now = time.ticks_ms()
        if time.ticks_diff(now, press_time[index]) > 150:
            press_time[index] = now
            pressed[index] = True
    return handler

go_button.irq(trigger=Pin.IRQ_FALLING, handler=make_handler(0))
best_button.irq(trigger=Pin.IRQ_FALLING, handler=make_handler(1))

def take(index):
    """True once for every press of a button."""
    if pressed[index]:
        pressed[index] = False
        return True
    return False

def seconds(ms):
    ms = min(ms, 9999)
    return "{}.{:03d}".format(ms // 1000, ms % 1000)

def load_best():
    try:
        with open("best.txt") as f:
            return int(f.read())
    except (OSError, ValueError):
        return None

def save_best(ms):
    with open("best.txt", "w") as f:     # written only for a new record, so the flash lasts
        f.write(str(ms))

best = load_best()
state = "idle"
wait_until = 0
started = 0
best_until = 0
last = "----"              # what the display showed after the last round

def set_last(text):
    global last
    last = text

def tick():
    """One step of the game. Returns the state, so the tests can follow it."""
    global state, wait_until, started, best, best_until
    now = time.ticks_ms()
    if state in ("idle", "done"):
        if take(1):                                  # show the best time for 2 seconds
            show(seconds(best) if best is not None else "----")
            best_until = time.ticks_add(now, 2000)
        if take(0):
            show("    ")                             # dark: get ready...
            wait_until = time.ticks_add(now, random.randint(2000, 5000))
            state = "wait"
        elif best_until and time.ticks_diff(now, best_until) >= 0:
            best_until = 0
            show("----" if state == "idle" else last)
    elif state == "wait":
        if take(0):
            show("Err")                              # false start: pressed too early
            state = "done"
            set_last("Err")
        elif time.ticks_diff(now, wait_until) >= 0:
            started = now
            state = "go"
    elif state == "go":
        if take(0):
            reaction = time.ticks_diff(press_time[0], started)
            show(seconds(reaction))
            set_last(seconds(reaction))
            if best is None or reaction < best:
                best = reaction
                save_best(best)
            state = "done"
        else:
            show(seconds(time.ticks_diff(now, started)))   # the time runs while you wait
    return state

display = Timer(mode=Timer.PERIODIC, freq=1000, callback=refresh)
show("----")

if __name__ == "__main__":
    while True:
        tick()
        time.sleep_ms(5)

Play it

  1. The display shows ----. Press the Go button: the display goes dark.
  2. Wait. At a random moment between two and five seconds the time starts running: 0.000, 0.001, 0.002…
  3. Press Go as fast as you can. The display freezes on your reaction time. Most people manage 0.200 to 0.300 seconds.
  4. Pressed while it was still dark? The display shows Err. Press Go to try again.
  5. Press the Best button at any time between rounds to see your best time for two seconds.

What you should see

The display in four stages: four dashes when ready, dark while you wait, 0.245 as the reaction time, and Err after a false start.
Ready, wait in the dark, press when the clock runs. Too early gives Err.

How it works

How it works: the four digits are lit one after another every millisecond, a 1000 Hz timer runs refresh(), a falling-edge pin interrupt notes the press time, and the game moves through the states idle, wait, go and done.
A timer keeps the display lit, interrupts catch the press.

Multiplexing. All four digits share the same eight segment wires, so the Pico can only show one digit at a time. refresh() switches the lit digit off, sets the segment pins for the next digit and switches that digit on: its common cathode goes LOW, so current flows from the segment pins through the LEDs to the digit pin. Each digit is lit for one millisecond, then the next one, 250 times a second for each digit. Your eyes can't follow that fast, so you see all four digits at once.

The timer interrupt. Timer(mode=Timer.PERIODIC, freq=1000, callback=refresh) calls refresh() 1,000 times a second, whatever the rest of the program is doing. The main loop never has to remember to update the display. It only changes the list shown, and the next refresh picks up the new pattern. Interrupt functions must be quick, so refresh() does nothing but switch nine pins.

Pin interrupts and bounce. go_button.irq(trigger=Pin.IRQ_FALLING, …) runs the handler the moment the pin falls from HIGH to LOW, which is when you press the button (the internal pull-up keeps it HIGH otherwise). The handler notes the time straight away, so the reaction time is measured from the press itself, not from whenever the main loop next looks. A button's metal contacts bounce for a few milliseconds and create several falling edges, so the handler ignores any press within 150 ms of the last one.

Safe timing. time.ticks_ms() counts milliseconds and wraps around to zero after a while. ticks_diff() and ticks_add() do the maths correctly even across the wrap, which a simple subtraction doesn't.

The state machine. The game is always in one of four states: idle, wait, go or done. tick() looks at the state and the buttons and decides what happens next. A press during wait means a false start; a press during go stops the clock. The best time is saved in best.txt on the Pico's flash only when you beat it, so the flash isn't worn out by constant writing.

Try this next

  • Add a passive buzzer that beeps when the time starts, and test whether people react faster to a sound or a light.
  • Make it a two-player game: one button per player, and the display shows who was first.
  • Hold the Best button for three seconds to reset the best score (delete best.txt with os.remove()).

Troubleshooting

  • Nothing lights up: check that the display is common cathode (CC). A common-anode display needs the opposite logic. Check the 220 Ω resistors are on the digit pins.
  • Wrong segments light up, or numbers look like letters: your display uses a different pin order. Find its datasheet, or test each pin by lighting one segment at a time from the Thonny Shell.
  • Digits flicker: make sure no long time.sleep() or printing was added inside refresh(). It must stay short.
  • Every press shows Err: the button may be wired to the wrong pair of legs and always closed. Use legs that are diagonally opposite.
  • One press counts twice: raise the 150 ms debounce time in make_handler().

Next lesson

Previous: Set up the Raspberry Pi Pico as an analog sensor hub for the Pi. Next: Build a Pico temperature logger that survives power cuts.