Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
>>>

If this doesn’t work, you need to make sure that you started the Python v3 command prompt using the
sudo command. If ensuring that you use sudo doesn’t help, you may have to double-check your
wiring to make sure it’s all okay.


Watch Out!: Resetting the GPIO Interface
It’s always a good idea to use the cleanup() method when you’re done with the
GPIO signals. It places all the GPIO pins in a LOW status, so no extraneous signals are
present on the interface. If you do not use the cleanup() function, the RPi.GPIO
module produces a warning message if you try to set up a GPIO signal that is already
assigned a signal value.

Blinking the LED


Now you’re ready to start writing some Python code. Listing 24.1 shows the script2401.py
program, which toggles the GPIO 18 signal LED 10 times, causing the LED to blink 10 times. Just
open your editor and enter the code shown in the Listing.


LISTING 24.1 The script2401.py Program Code


Click here to view code image


#!/usr/bin/python3

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.LOW)
blinks = 0
print('Start of blinking...')
while (blinks < 10):
GPIO.output(18, GPIO.HIGH)
time.sleep(1.0)
GPIO.output(18, GPIO.LOW)
time.sleep(1.0)
blinks = blinks + 1
GPIO.output(18, GPIO.LOW)
GPIO.cleanup()
print('End of blinking')

After you save this code, you need to use the chmod command to change the permissions so you can
run the code from the command line. Because the script accesses direct memory, you need to use the
sudo command to run it, as shown here:


Click here to view code image


pi@raspberrypi ~ $ chmod +x script2401.py
pi@raspberrypi ~ $ sudo ./script2401.py
Start of blinking...
End of blinking
pi@raspberrypi ~ $
Free download pdf