from machine import Pin, Timer
import time
import random
# --------- Settings ---------
MIN_WAIT_MS = 2000 # minimum random wait
MAX_WAIT_MS = 5000 # maximum random wait
DEBOUNCE_MS = 200 # button debounce
LED_PIN = 2
BUTTON_PIN = 14
# --------- Hardware Setup ---------
led = Pin(LED_PIN, Pin.OUT)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)
# --------- State Variables ---------
last_press = 0
game_active = False # waiting for player reaction
request_start = False # start game request
reaction_start = 0
# Timer for delayed LED start
t_start = Timer(0)
# --------- Interrupt Function ---------
def button_pressed(pin):
global last_press, game_active
now = time.ticks_ms()
if time.ticks_diff(now, last_press)> DEBOUNCE_MS:
#Check game active
if game_active:
reaction_time = time.ticks_diff(now, reaction_start)
print("reaction time: ", reaction_time)
led.off()
game_active = False
print("get ready for next round")
start_game()
last_press = now
# --------- Timer Callback ---------
def led_on(timer):
global game_active, reaction_start
led.on()
game_active = True
reaction_start = time.ticks_ms()
print("PRESS NOW")
# --------- Helper Function ---------
def start_game():
wait_time = random.randint(MIN_WAIT_MS, MAX_WAIT_MS)
print("Wait for the led....")
t_start.init(
period = wait_time,
mode = Timer.ONE_SHOT,
callback = led_on
)
# Attach interrupt
button.irq(trigger = Pin.IRQ_FALLING,handler = button_pressed)
# --------- Main Program ---------
print("Reaction Time Game Started")
print("Press button ONLY when LED turns on")
start_game()
while True:
# main loop stays free
time.sleep_ms(10)