Writing a Program

To make the LED cycle through a range of colors, we can write a short program. First, exit the Python console by typing:
Download: file
>>> exit()
This should take you back to the Linux prompt.

Enter the following command to create a new files called fade.py
Download: file
nano fade.py
Now paste the code below into the editor window.
Download: file
import Adafruit_BBIO.PWM as PWM
import time

red = "P8_13"
green = "P8_19"
blue = "P9_14"

PWM.start(red, 0)
PWM.start(blue, 0)
PWM.start(green, 0)

def fade(colorA, colorB, ignore_color):
    PWM.set_duty_cycle(ignore_color, 100)
    for i in range(0, 100):
	    PWM.set_duty_cycle(colorA, i)
	    PWM.set_duty_cycle(colorB, 100-i)
while True:
    fade(red, green, blue)
    fade(green, blue, red)
    fade(blue, red, green)
Save and exit the editor using CTRL-x and the Y to confirm.

To start the program, enter the command:
Download: file
$ python fade.py
When you want to stop the program, use CTRL-c.

You will notice that the LED will remain frozen in its last color. Since we are not stopping the PWM channels, they will run in the background.

The program fades colors in pairs. First from red to green, then from green to blue and finally from blue to red, before continuing the cycle again.

The set_duty_cycle changes the brightness of the led color. In the Adafruit_BBIO.PWM library, brightest is 0 and 100 means the LED for that color is off.

The program above assumes that you are using a common cathode LED. If you are using a common anode LED, then change these lines:
Download: file
PWM.set_duty_cycle(ignore_color, 100)

PWM.set_duty_cycle(colorA, i)
PWM.set_duty_cycle(colorB, 100-i)
to look like this:
Download: file
PWM.set_duty_cycle(ignore_color, 0)

PWM.set_duty_cycle(colorA, 100-i)
PWM.set_duty_cycle(colorB, i)
This guide was first published on Jul 09, 2013. It was last updated on Jul 09, 2013. This page (Writing a Program) was last updated on Feb 20, 2020.