PWM

A final feature is PWM or Pulse Width Modulation. This refers to toggling an output pin at different rates and duty cycles. With an LED, for example, this can be used to make it flash or to adjust the perceived brightness. The library has support for this, although it is done in software and does not currently take advantage of the Raspberry Pi's hardware PWM capability.

To use it, you set the toggle frequency of the channel (in Hertz), keeping the returned handle:

p = GPIO.PWM(channel, frequency)

You start PWM mode by calling start with a duty cycle from 0 to 100 percent:

p.start(dc)

At any time you can change the frequency or duty cycle:


p.ChangeFrequency(freq)
p.ChangeDutyCycle(dc)

And finally, when done, to stop PWM we can call:

p.stop()

In our final example using the RPi.GPIO library on a Raspberry Pi, we utilize PWM to independently control the brightness of each of the three LEDs connected to the GPIO pins. It also uses a callback so that the program immediately exits at any time when the pushbutton is pressed.

import sys
import time
import RPi.GPIO as GPIO

# Callback called when switch is pressed.
def switch_callback(pin):
    print('Switch pressed, exiting.')
    GPIO.cleanup()
    sys.exit(0)

led1 = 18  # Red
led2 = 22  # Green
led3 = 29  # Yellow
switch = 31
GPIO.setmode(GPIO.BOARD)
GPIO.setup(led1, GPIO.OUT)
GPIO.setup(led2, GPIO.OUT)
GPIO.setup(led3, GPIO.OUT)
GPIO.setup(switch, GPIO.IN)
GPIO.add_event_detect(switch, GPIO.FALLING, callback=switch_callback)
while True:
    for pin in [led1, led2, led3]:
        p = GPIO.PWM(pin, 50)
        p.start(0)
    for dc in range(0, 101, 5):
        p.ChangeDutyCycle(dc)
        time.sleep(0.05)
    for dc in range(100, -1, -5):
        p.ChangeDutyCycle(dc)
        time.sleep(0.05)

There are some additional functions provided by the Rpi.GPIO library that you can read about in the Wiki documentation. Overall, it is quite simple and easy to use.