RGB LED

Project 6: RGB LED

What you will need:

  • Raspberry Pi
  • Breadboard
  • 1 RGB LED
  • 3 220Ω Resistors —[III I]—
  • 4 Female to Male Jumper Wires
  • 1 Male to Male Jumper Wire

Instructions:

The previous projects my son and I have done have dealt exclusively with simple LEDs that represent a single color. This project, however, is using an RGB LED which hosts a Red, Green, and a Blue Light Emitting Diode in a single housing. The RGB LED we are using has a common shared cathode () connection and a separate anode (+) connection for each of the three colors. Our LED’s cathode is leg 2 while the Red, Green, and Blue legs are 1, 3, and 4. Check the datasheet for your specific RGB LED in order to correctly connect it within the circuit.

To keep things simple, we are using 3 220Ω resistors to limit current to each anode and to prevent the LED from burning out. Several other RGB LED tutorials online calculate the specific resistance required for each anode in order to equalize each color’s brightness. For our purpose, however, 220Ω to 330Ω resistors will work fine.

Most of the RGB tutorials we found were simply toggling each color LED on or off by setting each GPIO pin’s state from HIGH to LOW. For this project, however, we decided to utilize the Raspberry Pi Python Library’s software-based Pulse Width Modulation (PWM) functions to control individual brightness levels.

As with our previous projects, after you have completed the breadboard layout above, use your favorite editor to create the following Python script:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  RGB_LED.py
#
# A short program to control an RGB LED by utilizing
# the PWM functions within the Python GPIO module
#
#  Copyright 2015  Ken Powers
#   

# Import the modules used in the script
import random, time
import RPi.GPIO as GPIO

# Set GPIO to Broadcom system and set RGB Pin numbers
RUNNING = True
GPIO.setmode(GPIO.BCM)
red = 17
green = 18
blue = 27

# Set pins to output mode
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)

Freq = 100 #Hz

# Setup all the LED colors with an initial
# duty cycle of 0 which is off
RED = GPIO.PWM(red, Freq)
RED.start(0)
GREEN = GPIO.PWM(green, Freq)
GREEN.start(0)
BLUE = GPIO.PWM(blue, Freq)
BLUE.start(0)

# Define a simple function to turn on the LED colors
def color(R, G, B, on_time):
	# Color brightness range is 0-100%
	RED.ChangeDutyCycle(R)
	GREEN.ChangeDutyCycle(G)
	BLUE.ChangeDutyCycle(B)
	time.sleep(on_time)

	# Turn all LEDs off after on_time seconds
	RED.ChangeDutyCycle(0)
	GREEN.ChangeDutyCycle(0)
	BLUE.ChangeDutyCycle(0)

print("Light It Up!")
print("Press CTRL + C to quit.\n")
print(" R  G  B\n---------")

# Main loop
try:
    while RUNNING:
		for x in range(0,2):
			for y in range(0,2):
				for z in range(0,2):
					print (x,y,z)
					# Slowly ramp up power percentage of each active color
					for i in range(0,101):
						color((x*i),(y*i),(z*i), .02)

# If CTRL+C is pressed the main loop is broken
except KeyboardInterrupt:
    RUNNING = False
    print "\Quitting"

# Actions under 'finally' will always be called
# regardless of what stopped the program
finally:
    # Stop and cleanup so the pins
    # are available to be used again
    GPIO.cleanup()

Code Analysis:

Our Python script begins by letting the interpreter know which language we are using and by making a few comments as to the script’s functionality.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  RGB_LED.py
#
# A short program to control an RGB LED by utilizing
# the PWM functions within the Python GPIO module
#
#  Copyright 2015  Ken Powers
#

Next, we import the modules we will be using.

# Import the modules used in the script
import random, time
import RPi.GPIO as GPIO

We then define our constants. At this point, we are creating a variable that helps us know when to terminate our main loop. Then, we define which GPIO pins we will be using by assigning them to corresponding color-named variables. We also decided to use the GPIO.setmode command to put our GPIO into Broadcom mode so we could use our preferred numbering system.

# Set GPIO to Broadcom system and set RGB Pin numbers
RUNNING = True
GPIO.setmode(GPIO.BCM)
red = 17
green = 18
blue = 27

Next, we set each of our LED’s GPIO pins to output mode. We also define a constant called Freq to 100Hz as this is required by the PWM function we will be using.

# Set pins to output mode
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)

Freq = 100 #Hz

This section of code defines a simple function that utilizes the GPIO PWM function to turn each Red, Green, or Blue LED on for a specific amount of time and at a brightness level of 0% to 100%. Then, it turns each LED off.

# Define a simple function to turn on the LED colors
def color(R, G, B, on_time):
	# Color brightness range is 0-100%
	RED.ChangeDutyCycle(R)
	GREEN.ChangeDutyCycle(G)
	BLUE.ChangeDutyCycle(B)
	time.sleep(on_time)

	# Turn all LEDs off after on_time seconds
	RED.ChangeDutyCycle(0)
	GREEN.ChangeDutyCycle(0)
	BLUE.ChangeDutyCycle(0)

The next section of code sets everything up to use the GPIO library’s PWM function and gives each LED an initial duty cycle of 0% power which is the equivalent of turning the particular LED off.

# Setup all the LED colors with an initial
# duty cycle of 0 which is off
RED = GPIO.PWM(red, Freq)
RED.start(0)
GREEN = GPIO.PWM(green, Freq)
GREEN.start(0)
BLUE = GPIO.PWM(blue, Freq)
BLUE.start(0)

Usually, I don’t mention much about the simple print statements we have been including in our Python scripts. This time, however, we decided to not only print a statement that indicates the program has begun but we also indicate which LED colors are being lit at any given time by displaying a 1 (on) or a 0 (off) in a table.

Our main program loop simply toggles each LED color on and off in order to supply every combination of Red, Green, and Blue. The for i in range(0,101): loop uses our color function to ramp the chosen LED combinations up from 0% to 100% brightness.

The main loop continues until Ctrl + C is pressed. Then, the GPIO.cleanup() function is called so our GPIO pins will be ready for the next program.

print("Light It Up!")
print("Press CTRL + C to quit.\n")
print(" R  G  B\n---------")

# Main loop
try:
    while RUNNING:
		for x in range(0,2):
			for y in range(0,2):
				for z in range(0,2):
					print (x,y,z)
					# Slowly ramp up power percentage of each active color
					for i in range(0,101):
						color((x*i),(y*i),(z*i), .02)

# If CTRL+C is pressed the main loop is broken
except KeyboardInterrupt:
    RUNNING = False
    print "\Quitting"

# Actions under 'finally' will always be called
# regardless of what stopped the program
finally:
    # Stop and cleanup so the pins
    # are available to be used again
    GPIO.cleanup()

As can be seen from the above code, the RGB LED could simply have each color turned off or on. Instead, we chose to use the Raspberry Pi’s GPIO PWM function to change the LEDs’ individual brightness levels. An additional fun project might be to modify the Python script to display every combination of Red, Green, and Blue LED at every possible brightness combination for each individual color. Have fun playing around with the code!



Leave a Reply