The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

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

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


Click the green flag, and watch the traffic lights
go through their sequence. Press the push-button
switch: at first it will look like nothing is happening,
but once the sequence has reached its end – with
just the yellow LED lit – the traffic lights will go off
and stay off, thanks to your ‘pushed’ variable.
All that’s left to do is make your pedestrian crossing
button actually do something other than turn the lights
off. In the main block stack, find the else block and
drag a set gpio 25 to output high block into it –
remembering to change the default GPIO pin number
to match the pin your red LED is connected to.
Beneath that, still in the else block, create a
pattern for the buzzer: drag a repeat 10 block,
then fill it with set gpio 15 to output high ,
wait 0.2 secs , set gpio 15 to output low , and
wait 0.2 secs blocks, again changing the GPIO pin
values to match the pin for the buzzer component.
Finally, beneath the bottom of your repeat 10
block but still in the else block, add a
set gpio 25 to output low block and a
set pushed to 0 block – the last block resetting the
variable that stores the button press, so the buzzer
sequence doesn’t just repeat forever.
Click the green flag, then push the switch on your
breadboard. After the sequence has completed,
you’ll see the red light go on and the buzzer sound
to let pedestrians know it’s safe to cross. After a
couple of seconds, the buzzer will stop and the
traffic light sequence will start again and continue
until the next time you press the button.
Congratulations: you have programmed your own
fully functional set of traffic lights, complete with
pedestrian crossing!


when clicked
setgpio 2 toinput
forever
if pushed = 0 then
setgpio^25 tooutput high
wait^5 secs
setgpio^8 tooutput high
wait 2 secs
setgpio^25 tooutput low
setgpio 8 tooutput low
setgpio^7 tooutput high
wait 5 secs
setgpio^7 tooutput low
setgpio 8 tooutput high
wait^5 secs
setgpio 8 tooutput low
else
setgpio^25 tooutput high
repeat^10
setgpio 15 tooutput high
wait 0.2secs
setgpio 15 tooutput low
wait 0.2secs

setgpio^25 tooutput low
set pushed to^0

when clicked
forever
if not gpio^2 ishigh? then
set pushed to 1

CHALLENGE: CAN YOU IMPROVE IT?
Can you change the program to give the pedestrian longer
to cross? Can you find information about other countries’
traffic light patterns and reprogram your lights to match?
How could you make the LEDs less bright?
Free download pdf