0
0
Raspberry Piprogramming~10 mins

Reaction time game in Raspberry Pi

Choose your learning style9 modes available
Introduction

A reaction time game helps you practice how fast you can respond to a signal. It is fun and trains your reflexes.

To test how quickly you can press a button after a light turns on.
To practice improving your hand-eye coordination.
To create a simple game for friends or family to compete on reaction speed.
To learn how to use buttons and LEDs with a Raspberry Pi.
To understand timing and delays in programming.
Syntax
Raspberry Pi
import time
import random
import RPi.GPIO as GPIO

# Setup pins
LED_PIN = 18
BUTTON_PIN = 23

GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Game logic
# 1. Wait random time
# 2. Turn on LED
# 3. Measure time until button press
# 4. Show reaction time

GPIO.output(LED_PIN, GPIO.LOW)

Use GPIO.setup to set pins as input or output.

Use GPIO.input to read button state and GPIO.output to control LED.

Examples
This turns the LED on and off.
Raspberry Pi
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.output(LED_PIN, GPIO.HIGH)  # Turn LED on
GPIO.output(LED_PIN, GPIO.LOW)   # Turn LED off
This reads the button state. The button is connected with a pull-up resistor.
Raspberry Pi
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
button_state = GPIO.input(BUTTON_PIN)
Sample Program

This program waits a random time, then lights an LED. When you press the button, it measures how fast you reacted and shows the time.

Raspberry Pi
import time
import random
import RPi.GPIO as GPIO

LED_PIN = 18
BUTTON_PIN = 23

GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

try:
    print("Get ready...")
    GPIO.output(LED_PIN, GPIO.LOW)
    time.sleep(random.uniform(2, 5))  # Wait random time between 2 and 5 seconds

    print("Go! Press the button as fast as you can!")
    GPIO.output(LED_PIN, GPIO.HIGH)  # Turn LED on
    start_time = time.time()

    # Wait for button press
    while GPIO.input(BUTTON_PIN):
        pass  # Button not pressed yet

    reaction_time = time.time() - start_time
    GPIO.output(LED_PIN, GPIO.LOW)  # Turn LED off

    print(f"Your reaction time is {reaction_time:.3f} seconds.")

finally:
    GPIO.cleanup()
OutputSuccess
Important Notes

Make sure your button is connected correctly with a pull-up or pull-down resistor to avoid false readings.

Use GPIO.cleanup() to reset pins when the program ends.

Try to keep your hand ready to press the button quickly after the LED lights up.

Summary

A reaction time game measures how fast you press a button after a signal.

Use Raspberry Pi GPIO pins to control an LED and read a button press.

Timing and waiting for input are key parts of this simple game.