The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1

136 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE


Reading a button in Python
Click the New button in Thonny to start a new project, and the Save button to save it as Button
Input. Using a GPIO pin as an input for a button is very similar to using a pin as an output for
an LED, but you need to import a different part of the GPIO Zero library. Type the following into
the script area:

from gpiozero import Button
button = Button( 2 )

To have code run when the button is pressed, GPIO Zero provides the wait_for_press
function. Type the following:

button.wait_for_press()
print("You pushed me!")

Click the Run button, then press the push-button switch. Your message will print to the
Python shell at the bottom of the Thonny window: you’ve successfully read an input from
the GPIO pin! If you want to try your program again, you’ll need to click the Run button again;
because there’s no loop in the program, it quits as soon as it has finished printing the message
to the shell.
To extend your program further, add the LED and resistor back into the circuit if you haven’t
already done so: 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.
To control an LED as well as read a button, you’ll need to import both the Button and LED
functions from the GPIO Zero library. You’ll also need the sleep function from the time
library. Go back to the top of your program, and type in the following as the new first two lines:

from gpiozero import LED
from time import sleep

Below the line button = Button(2), type:

led = LED( 25 )

Delete the line print("You pushed me!") and replace it with:

led.on()
sleep( 3 )
led.off()
Free download pdf