The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

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

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


Your finished program should look like this:
from gpiozero import LED
from time import sleep
from gpiozero import Button

button = Button( 2 )
led = LED( 25 )
button.wait_for_press()
led.on()
sleep( 3 )
led.off()

Click the Run button, then press the push-button switch: the LED will come on for three
seconds, then turn off again and the program will exit. Congratulations: you can control an LED
using a button input in Python!


CHALLENGE: ADD A LOOP
How would you add a loop to make the program repeat
instead of exiting after one button press? 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