The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

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

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


Together, these two lines give Python the ability to control LEDs connected to the Raspberry
Pi’s GPIO pins and tell it which pin – or pins, if you have more than one LED in your circuit –
to control. To actually control the LED, type the following:


led.on()

To switch the LED off again, type:

led.off()

Congratulations, you now have control over the Raspberry Pi’s GPIO pins in Python! Try
typing those two instructions again. If the LED is already off, led.off() won’t do anything;
the same is true if the LED is already on and you type led.on().
To make a true program, type the following into the script area:


from gpiozero import LED
from time import sleep

led = LED( 25 )

while True:
led.on()
sleep( 1 )
led.off()
sleep( 1 )

This program imports the LED function from the gpiozero (GPIO Zero) library and the
sleep function from the time library, then constructs an infinite loop to turn the LED on for a
second, turn it off for a second, and to repeat. Click the Run button to see it in action: your LED
will begin to flash. As with the Scratch program, make a note of the behaviour when you click
the Stop button while the LED is on versus while the LED is off.


CHALLENGE: LONGER LIGHT-UP
How would you change the program to make the LED
stay on for longer? What about staying off for longer?
What’s the smallest delay you can use while still seeing
the LED switch on and off?
Free download pdf