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

(singke) #1

When the program is running, you should see the LED blink on and off. Congratulations! You just
programmed your first digital output signal!


Creating a Fancy Blinker


You had to write a lot of code just to get the LED to blink. Fortunately, the GPIO has a feature that
can help make that easier.


PWM is a technique used in the digital world mainly to control the speed of motors using a digital
signal. You can apply it to your blinking project as well. With PWM, you control the amount of time
the HIGH/LOW signals repeat (called the frequency) and the amount of time the signal stays in the
HIGH state (called the duty cycle).


It just so happens that the Broadcom GPIO signal 18 doubles as a PWM signal. You can set the GPIO
18 signal to PWM mode by using the GPIO.PWM() method, as shown here:


Click here to view code image


blink = GPIO.PWM(channel, frequency)

After you set up the GPIO 18 signal, you can start and stop it by using the start() and stop()
methods, as shown here:


blink.start(50)
blink.stop()

The start() method specifies the duty cycle (from 1 to 100). After you start the PWM signal, your
program can go off and do other things. The GPIO 18 continues to send the PWM signal until you stop
it.


Listing 24.2 shows the script2402.py program, which demonstrates using PWM to blink the
LED.


LISTING 24.2 The script2402.py Program Code


Click here to view code image


1: #!/usr/bin/python3
2:
3: import RPi.GPIO as GPIO
4: GPIO.setmode(GPIO.BCM)
5: GPIO.setup(18, GPIO.OUT)
6: blink = GPIO.PWM(18, 1)
7: try:
8: blink.start(50)
9: while True:
10: pass
11: except KeyboardInterrupt:
12: blink.stop()
13: GPIO.cleanup()

The code starts the PWM signal on GPIO 18, at 1Hz (line 6), and then it goes into an endless while
loop doing nothing (using the pass command on line 10). You set the loop in a try code block to
catch the Ctrl+C keyboard interrupt to stop things.


After you start the program (using sudo), the LED should blink once per second (because of the 1Hz

Free download pdf