The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

134 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


when clicked


set gpio^2 to input


If you click the green flag now, nothing will happen. That’s because you’ve told Scratch to
use the pin as an input, but not what to do with that input. Drag a forever block to the end of
your sequence, then drag an if then else block inside it. Find the gpio is high? block, drag it
into the diamond-shaped white space in the if then part of the block, and use the drop-down
to select the number 2 to tell it which GPIO pin to check. Finally, drag a say hello! for 2 secs
block into the else part of the block and edit it to say ‘Button pushed!’. Leave the ‘if then’ part
of the block empty for now.

when clicked


set gpio^2 to input


forever


if gpio^2 ishigh? then


else


say Button pushed! for^2 secs


There’s a lot going on there, but start by testing it: click the green flag, then push the button
on your breadboard. Your sprite should tell you that the button has been pushed: you’ve
successfully read an input from the GPIO pin!
You may have noticed that the if gpio 2 is high? then part of the block is empty. The code
that runs when the button is actually pushed, meanwhile is in the else part of the block. That
seems confusing, as surely pressing the button makes it go high? In fact, it’s the opposite: the
Raspberry Pi’s GPIO pins are normally high, or on, when set as an input, and pushing the button
pulls them down to low.
Look at your circuit again: see how the button is connected to the GPIO 2 pin, which is
providing the positive part of the circuit, and the ground pin. When the button is pushed, the
voltage on the GPIO pin is pulled low through the ground pin, and your Scratch program stops
Free download pdf