import RPi.GPIO as gpio from time import sleep, clock from random import randint # [Start button, reflex button] digins = [19, 16] digouts = [12] result = 0 ### State Functions ### def standby (): ''' Wait for the game to begin! ''' # gpio.LOW means button pressed because inputs have pull-up resistors if gpio. input (digins[0]) == gpio.LOW: return 'game' else : return 'standby' def game (): ''' The main event ''' global result false_start = False # Add 1 to 6 seconds to the current clock time to randomize the game wait_time = clock() + randint(1, 6) # Wait for the clock to run out, watch for false starts while not false_start and clock() < wait_time: false_start = gpio. input (digins[0]) == gpio.HIGH if not false_start: # Turn on the LEDs gpio.output(digouts, gpio.HIGH) start_time = clock() while gpio. input (digins[1]) == gpio.HIGH: pass # wait until it is pressed # The time it took is the current clock time minus the start time result = clock() - start_time # Turn off the LEDs gpio.output(digouts, gpio.LOW) else : result = 0 return 'results' if result > 0 else 'false_start' def results (): ''' Display how good --or bad-- you did ''' global result print ( 'Your reflex time was: %s seconds!' %(result)) return 'standby' def false_start (): ''' Sometimes we jump the gun ''' # Add more retorts to let people know that, just because we all have false starts, it isn't right and you should be ashamed retorts = [ 'Sometimes it is better to take too long than to be too early' , \ 'You lose! Black and white, clear as crystal. Good day, sir' , \ 'False start, buddy' ] retort = retorts[randint(0, len (retorts)) - 1] print (retort) return 'standby' # Hold all of the states so it is easy to keep track of what to be doing STATES = { \ 'standby' :standby, \ 'game' :game, \ 'results' :results, \ 'false_start' :false_start \ } # This try-finally block is important to free up the gpio pins for other processes in the future try : gpio.setmode(gpio.BCM) for i in digins: gpio.setup(i, gpio.IN, pull_up_down=gpio.PUD_UP) for i in digouts: gpio.setup(i, gpio.OUT, initial=gpio.LOW) # Each state returns which state to enter next next_state = 'standby' # Loop forever, use ctrl+c to exit while True : next_state = STATES[next_state]() sleep(0.02) finally : gpio.cleanup()