The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 6 Physical computing with Scratch and Python 147

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


Start a new project in Thonny and save it as Reaction Game. You’re going to be using the
LED and button functions from the GPIO Zero library, and the sleep function from the time
library. Rather than importing the two GPIO Zero functions on two separate lines, though, you
can save time and import them together using a comma symbol (,) to separate them. Type
the following in the script area:


from gpiozero import LED, Button
from time import sleep

As before, you’ll need to tell GPIO Zero which pins the two buttons and the LED are
connected to. Type the following:


led = LED( 4 )
right_button = Button( 15 )
left_button = Button( 14 )

Now add instructions to turn the LED on and off, so you can check it’s working correctly:

led.on()
sleep( 5 )
led.off()

Click the Run button: the LED will turn on for five seconds, then turn off and the program
will quit. For the purposes of a reaction game, though, having the LED go off after exactly
5 seconds every time is a bit predictable. Add the following below the line from time
import sleep:


from random import uniform

The random library, as its name suggests, lets you generate random numbers (here with a
uniform distribution – see rpf.io/uniform). Find the line sleep(5) and change it to read:


sleep(uniform( 5 , 10 ))

Click the Run button again: this time the LED will stay lit for a random number of seconds
between 5 and 10. Count to see how long it takes for the LED to go off, then click the Run
button a few more times: you’ll see the time is different for each run, making the program
less predictable.
To turn the buttons into triggers for each player, you’ll need to add a function. Go to the very
bottom of your program and type the following:

Free download pdf