RGB LED

The RGB LED will be controlled by software PWM. When different values are set to the legs, they make different colors.

Hardware

Component List

  • Raspberry Pi 3 B+ x 1
  • GPIO Extension Board and GPIO Cable x 1 (If you do not have an Extension Board, connect Raspberry Pi and breadboard directly with jumper wires.)
  • Breadboard x 1
  • RGB LED x 1 (This is a common anode RGB LED. If you have a common cathode RGB LED, the circuit should be different.)
  • Resistor 220Ω x 3 (Check your RGB LED specification for the correct resistor to use.)
  • Jumper Wire x 4

Schematic Diagram

Breadboard Diagram

Note that the longest leg of the LED needs to be connected to the positive. It is the second to the left as shown in the diagram. The sequence of the legs, from left to right is R, (+), G, and B.

Program

Create a Console Project.

Add NuGet package Unosquare.Raspberry.IO.

Main Program: Program.cs

using Unosquare.RaspberryIO;
using Unosquare.RaspberryIO.Gpio;

... 

GpioPin pinR = Pi.Gpio.Pin25;    // pin 37, GPIO26
GpioPin pinG = Pi.Gpio.Pin24;    // pin 35, GPIO19
GpioPin pinB = Pi.Gpio.Pin23;    // pin 33, GPIO13

if (pinR.IsInSoftPwmMode == false)
{
    pinR.StartSoftPwm(100, 100);
}

if (pinG.IsInSoftPwmMode == false)
{
    pinG.StartSoftPwm(100, 100);
}

if (pinB.IsInSoftPwmMode == false)
{
    pinB.StartSoftPwm(100, 100);
}

// white
pinR.SoftPwmValue = 0;
pinG.SoftPwmValue = 0;
pinB.SoftPwmValue = 0;
System.Threading.Thread.Sleep(2000);

// red
pinR.SoftPwmValue = 0;
pinG.SoftPwmValue = 100;
pinB.SoftPwmValue = 100;
System.Threading.Thread.Sleep(2000);

// green
pinR.SoftPwmValue = 100;
pinG.SoftPwmValue = 0;
pinB.SoftPwmValue = 100;
System.Threading.Thread.Sleep(2000);

// blue
pinR.SoftPwmValue = 100;
pinG.SoftPwmValue = 100;
pinB.SoftPwmValue = 0;
System.Threading.Thread.Sleep(2000);

// yellow
pinR.SoftPwmValue = 0;
pinG.SoftPwmValue = 0;
pinB.SoftPwmValue = 100;
System.Threading.Thread.Sleep(2000);

int steps = 5;

// varying colors
for (int r = 0; r <= steps; r++)
{
    pinR.SoftPwmValue = r * 100 / steps;

    for (int g = 0; g <= steps; g++)
    {
        pinG.SoftPwmValue = g * 100 / steps;

        for (int b = 0; b <= steps; b++)
        {
            pinB.SoftPwmValue = b * 100 / steps;

            System.Threading.Thread.Sleep(150);
        }
    }
}

Unosquare.Raspberry.IO uses the pin number the same as Wiring Pi. At Terminal, enter command gpio readall to see pin number mapping. Use the number in column wPi to address the pins.

Leave a Reply