Hardware Reference
In-Depth Information
Reading Inputs with Code
As you saw earlier, you can control outputs using the function digital_write . Logically,
as you might expect, to get the value of inputs, you use the digital_read function. Let's
write a simple example:
1. Type the following Python code interactively:
import piface.pfio as pfio
pfio.init()
pfio.digital_read(0)
Python prints 0 .
2. Hold down button number S1 and type pfio.digital_read(0) again.
Python prints 1 .
3. Now read the next button along (S2). Type pfio.digital_read(1) . Notice how
the argument of the function speciies which input to read.
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 ind out if you've got fast ingers 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()
Search WWH ::




Custom Search