Raspblocks

Raspberry Pi

Code Generator

Raspberry Raspberry pi
Home Projects Start Coding

Raspberry Pi - RGB Led

In this tutorial, we're going to be using an RGB LED. The R, G, and B stand for red, green, and blue, respectively, and the single RGB LED actually contains three LEDs within the single bulb. These are the primary colors for light; that is, you can theoretically create any color of light using some combination of these three. Mixing pure red with pure blue will result in magenta, blue and green in cyan, while red and green make yellow and all three make white.

You'll also notice that RGB LEDs have four leads instead of two. As I mentioned before, the RGB LED is actually a very small circuit consisting of three different LEDs. Now, this is where things can get a bit tricky. RGB LEDs come in two types: common anode and common cathode. On the common anode type, the longest lead is attached to the positive terminal and allows current to flow to all three LEDs inside while leads 1, 3, and 4 are are the ground leads for red, green, and blue respectively. On the other hand, common cathode types share a ground lead; the three shorter leads are each individually hooked up to the positive terminal in the same order.

Hardware Required

- Raspberry Pi

- RGB LED

- 3*220 Ohm Resistor

- Breadbord

- hook-up wires

Resistors are important because they prevent the LED from sending too much current through your Pi, something that they will do if given the opportunity. This could result in you blowing your LED, frying a GPIO pin, and/or destroying your Pi. ALWAYS use a resistor when connecting outputs to the Pi, even if they are low-level.

Circuit

So, with that out of the way, we are ready to hook up our RGB Led.

Raspblocks raspberry rgb
Code - Blocks
Raspblocks raspberry rgb
Code - Python

Create new python file rgb.py and enter following code. To run the code, open the terminal and go to directory where you code is located and enter the command sudo python rgb.py and hit enter.

import RPi.GPIO as GPIO 
import time 
GPIO.setmode(GPIO.BCM) 
GPIO.setup(13, GPIO.OUT) 
GPIO.setup(19, GPIO.OUT) 
GPIO.setup(24, GPIO.OUT) 
 
PWMR1=GPIO.PWM(5,100); 
PWMG1=GPIO.PWM(6,100); 
PWMB1=GPIO.PWM(13,100); 
PWMR1.start(100) 
PWMG1.start(100) 
PWMB1.start(100) 
while True: 
    PWMR1.ChangeDutyCycle(0) 
    PWMG1.ChangeDutyCycle(100) 
    PWMB1.ChangeDutyCycle(100) 
    time.sleep(1) 
    PWMR1.ChangeDutyCycle(80) 
    PWMG1.ChangeDutyCycle(20) 
    PWMB1.ChangeDutyCycle(100) 
    time.sleep(1) 
    PWMR1.ChangeDutyCycle(80) 
    PWMG1.ChangeDutyCycle(80) 
    PWMB1.ChangeDutyCycle(0) 
    time.sleep(1) 
    PWMR1.ChangeDutyCycle(0) 
    PWMG1.ChangeDutyCycle(20) 
    PWMB1.ChangeDutyCycle(100) 
    time.sleep(1)