Hardware Reference
In-Depth Information
You have seen how easy it is to read an input. Next, you are going to combine turning a light
on and reading an input to build a reaction timer.
The Reaction Timer
Now is the time to find out if you've got fast fingers by building a reaction timer game.
Type the following code in a new window and then save it as reactionTimer.py:
from time import sleep, time
from random import uniform
import piface.pfio as pfio
#Initialise the interface
pfio.init()
print “press button one when the light comes on”
#Sleep for a random period between 3 and 10 seconds
sleep(uniform(3,10))
#Turn LED on
pfio.digital_write(0,1)
#Record the current time
startTime = time()
#Wait while button is not pressed
while(pfio.digital_read(0)==0):
continue #continue round the loop
#Button must have been pressed as we've left loop
#Read time now
stopTime = time()
#Time taken is difference between times
elapsedTime = stopTime-startTime
#Display the time taken. str is required to convert
#elaspedTime into a string for printing
print “Your reaction time was: “ + str(elapsedTime)
#Turn LED off when finished
pfio.digital_write(1,0)
Run the code by pressing F5 from IDLE.
All the lights will go out. Wait until the LED comes on and then press button 0 as fast as you
can. The program will print your reaction time.
Next, you'll see if your reactions are any faster with a big red button as you wire up a simple
circuit.
Search WWH ::




Custom Search