The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

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

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


This pattern matches that used by traffic lights in the UK; you can edit the sequence to match
patterns in other countries, if you wish.
To simulate a pedestrian crossing, you need your program to watch for the button being
pressed. Click the red octagon to stop your program, if it’s currently running. Drag an if then else
block onto your script area and connect it so it’s directly beneath your forever block, with your
traffic light sequence in the ‘if then’ section. Leave the diamond-shaped gap empty for now.


when clicked
set gpio 2 to input
forever
if then
setgpio 25 to output high
wait^5 secs
setgpio^8 to output high
wait 2 secs
setgpio^25 to output low
setgpio^8 to output low
setgpio^7 to output high
wait^5 secs
setgpio^7 to output low
setgpio^8 to output high
wait 5 secs
setgpio^8 to output low
else

A real pedestrian crossing doesn’t change the light to red as soon as the button is pushed,
but instead waits for the next red light in the sequence. To build that into your own program,
drag a second when clicked block onto the scripts area, followed by a forever block.
Drag an if then block below your forever block, and fill the diamond-shaped blank with a
not Operator block followed by a gpio 2 is high? block – remembering to use the drop-
down category to change the GPIO pin number. Finally, create a new variable called ‘pushed’
and place a set pushed to 1 block inside the if then block.

Free download pdf