The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

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

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


running the code in your if gpio 2 is high? then block and instead runs the code in the else
part of the block.
If that all sounds perplexing, just remember this: a button on a Raspberry Pi GPIO pin is
pushed when the pin goes low, not when it goes high!
To extend your program further, add the LED and resistor back into the circuit: remember to
connect the resistor to the GPIO 25 pin and the long leg of the LED, and the shorter leg of the
LED to the ground rail on your breadboard.
Drag the say Button pushed! for 2 secs block off the scripts area to the block palette to
delete it, then replace it with a set gpio 25 to output high block – remembering that you’ll
have to change the GPIO number using the drop-down arrow. Add a set gpio 25 to output low
block – remembering to change the values – to the currently empty if gpio 2 is high? then
part of the block.


when clicked


setgpio^2 to input


forever


if gpio^2 ishigh? then


setgpio^25 to output low


else


setgpio^25 to output high


Click the green flag and push the button. The LED will light up as long as you’re holding the
button down; let go, and it will go dark again. Congratulations: you’re controlling one GPIO pin
based on an input from another!


CHALLENGE: MAKE IT STAY LIT
How would you change the program to make the LED stay
on for a few seconds, even after you let go of the button?
What would you need to change to have the LED on while
you’re not pressing the button and off while you are?
Free download pdf