Practical Electronics ProjectsPractical Electronics Projects  By Mike, K4ICY 

Weekend Radio 
Click Here for More Electronics Projects and Tutorials By Mike Maynard, K4ICY

.
It Comes In Any Color You Wish… - Fun with the FULL-COLOR "RGB" LED

  Originally published in The Printed Circuit, Newsletter of the Tallahassee Amateur Radio Society,  May 2013, page 16
   [VISIT HERE]    Edited/Updated December 2023

.
       Dimming and Current Control for LED’s

       An LED (Light Emitting Diode) that comes in every color of the rainbow, and then some?  As a high school youth in a three-year electronics magnet program surrounded by other youth familiar with, and very interested in electronics, this kind of 21st century marvel was science fiction and a ‘Holy Grail’ of LED’s.  During our first year, the only LED colors possible were red and green and anything in between and not that bright.  The blue LED was invented by our third year and wasn't really usable, but I still remember a few kids talking about it.  I worked for an electronics contract manufacturer in the early 1990's where I had acquaintance with electrical engineers and access to any part available.  I dreamt of self-contained Red/Green/Blue LED's and their potential years before they were reality.

       It's hard now [in the 2020's] to imagine the absence of what we now take for granted and that the major advancements in LED lighting technology are really more recent.  Not only do LED’s come in a wide array of photon output wavelengths from UV to IR, but many are bright enough to burn things in their light path and are now ubiquitously used in most applications of lighting including home lighting, commercial and street lighting, smart automotive headlamp assemblies and indicator lights, the main source of illumination for most of our portable devices such as smartphones and tablets as well as television displays, and on and on.  They also consume a fraction of the power as they are very efficient, and with that, have been the replacement for all lighting fixtures with most conventional incandescent lamps illegal to sell in many countries commercially.

       Full-color LED's, now generally called "RGB's," which are actually three separate LED's housed in one package, are now a common commodity for decorative lighting, in living spaces, art and gaming PC's and many have self-contained microcontroller addressability.  There’s not much complexity to using RGB LED’s in your own projects.  Essentially just diodes, they only allow current to pass in one direction.  When I first wrote this article in 2013, RGB LED's were most easily available at Radio Shack for $3.50 a piece but now you can get them in 100 piece bulk packages for $9 (or 5 to 10 cents a piece) on Amazon, AliExpress, eBay and etc. and can be had in many package varieties from 5mm, 3mm, 5050 smd, LED strips and many types of addressable models.  But the basic 5mm RGB LED has four leads with either the anode or cathode of each individual color element tied together as common.
.

Diode Current Curve

.
        Unlike old-fashioned incandescent bulbs where you could connect a battery right up to it for light, an LED is a semiconductor and requires a finite range of voltage and current allowance to produce light as desired without breaching its design specs and burning it out.  As you can see by the chart, there is a non-linearity between voltage applied and the current it consumes.  An LED has to reach an ‘on’ voltage level before it will emit photons and the value of illuminated light (lumens) is not constant through the safe voltage range.  Also, the amount of current consumed within the voltage range, typically between 2-3 volts is not easy to quantify.  But as you experiment with one and use an applicable current-limiting resistor in series, you can get close.

       An LED typically needs a current-limiting resistor and without it would fail.  As an LED reaches its maximum light output the internal resistance of the LED is greatly reduced so aside from any method used to ‘dim’ and LED, it’s going to need a resistor in series with it.  But what value resistor?  Figuring what value of current-limiting resistor to use while getting you the most brightness allowed from an LED takes knowing what the specification of that LED is along with a small formula for calculating the value for you particular operating voltage, but I would suggest using one of the many online LED Resistor Calculators to save time [Try the one provided by Digi-Key.]  There are two important pieces of information given in the specs for any LED: forward operating voltage (typ. 2-3 volts,) and maximum current (mA).  The LED’s voltage is the desired voltage when at or below its rated current max (milliamps.)  I would suggest staying below the rated max amps in the use of an LED, or you may shorten its life.  As a rule of thumb, a typical LED used in a common 5 volt circuit would require a limiting resistor in the range of 330 to 1,000 ohms depending on desired brightness.
.
RGB LED Color Control Setup
.
       If you wish for a quick and easy formula; use Resistance = (Volts supplied - Foward voltage) / Foward current [ R = (Vs-Vf) / Af ].  R is the resistance that should be used to keep your LED running cool and safe but it should be a common resistor chosen at the next-highest component value.  Vs is the source voltage (ie: 12 volts), and Vf is the load voltage figure (LED’s rated foward voltage.)  So if the data sheet says that the LED is rated at 2.3 volts for a max of 20 ma (A = 0.02), using the formula, R = 486, or just use a common 560 ohm resistor or larger.  Try some experimenting before using an LED in a circuit. If the LED gets too warm, you'll need to increase the resistor's value.  Also keep in mind to use a resistor wattage size capable of handling the current so just use Ohm’s Law.  For example, for a 20 ma LED on a 12 volt circuit at full brightness you would use a ½ watt resistor, because at the 0.25 watts of power drawn for it, you would burn up a smaller ¼ watt resistor.  Please note that each color element of an RGB LED will consume a different amount of current due to each element's material composition and other factors.  Blue and Green LED elements may consume around 14 ma while the Red may consume over 20 ma.

       Working the Range with Brute Force

       Can an LED be dimmed with a potentiometer?  To some degree, you can in fact ‘dim’ or control the light output of an LED using resistors while working within its safe operation voltage range.  Keep in mind not to reduce the in-series resistance to less than the chosen limiting resistor value.  So can we use resistors to create any desired color with an RGB LED?  If you look at my schematic you’ll notice that I have my base-level limiting resistors plus a potentiometer (pot) in series with each cathode leg of the LED.  By changing the value of each trimmer, by brute force, we can control the light output level of each internal LED element and thus control the perceivable color output of the LED.  If you take a look at my experimental LED color chart, each color of LED light was configured by different resistance values added to the limiting resistor value of each LED segment. Some very cool results in deed!
.
RGB LED Current Control
.
       Is this good practice?  No, not really.  Since an LED’s function is not linear and each manufacturer offerings and types have different operating current/voltage ratings, any and every LED used may have to have its resistor values tweaked just right to get a desired result, especially if you are ganging-up multiple LED’s.  Also, you’ll notice by turning the pot (10K Ohms or more) that first, there is a very tight area in the rotation when the LED goes from so-so bright to really-bright, second, it will also seem that after it gets somewhat dim from more resistance, it seems that even after you add more resistance, even a lot, it’s hard to extinguish it’s light completely.  This is because an LED can efficiently produce photons from a very small voltage, especially the Blue ones.  An LED is definitely a non-linear device and for some color combinations it will be best to apply no resistance or to open the LED element circuit completely.  But there is another method of control that can come close (see the next circuit.)
.
RGB LED Color Control Using Current Limiting Resistors

The values given above are in Ohms. “~” indicates an open condition. “0” indicates no resistance. Values are approximate on top of any current limiting
resistance and results are not typical of course, but feel free to try it out for yourself


.
       This is a question with an obvious answer, but what can we use a color or brightness controlled RGB LED (or 'cob' of LED's) for anyway?  In two examples in my experiment, I was able to make an approximation of 'black body radiators' including incandescent (candle or warm) bulb light and that of a fluorescent bulb or mercury vapor style bulb (daylight or cool) light.  These would be great replacements for lamps in the front panels of your vintage radio gear, and they would virtually last forever.  Though, LED's of these colors are commonly available with just two leads and they are essentially blue LED's with a yellow phosphor filter layer on top to produce these white-ish colors.  For more colorful uses, I’ve configured RGB LED’s to change color to reflect the status of various operations in my homebuilt radio gear.  In one QRP amplifier, with its indicator RGB LED, I used an aqua color when the amplifier was in standby, and it shined red when it detected RF, which was a good indicator from a distance.  There are reasons for dimming LED’s too.  Many LED’s are manufactured to be extremely efficient and bright for the energy used and using an extremely bright LED, dimmed to a low level will allow you to use indicators in certain circuits where energy consumption should stay low, plus they will last forever.

       Now You Have Control… Use Pulse Width Modulation to Control LED’s, Motors, Etc.

       With the above method, we attempted to vary the brightness of a non-linear semiconductor LED device by applying in-series current-limiting resistance.  While it’s practical to go this route for simple applications, controlling accuracy and efficiency is difficult.  In the following circuit we'll use a common '555' timer/oscillator IC to control light output by implementation of pulse width modulation, or PWM.  Amateur Radio operators are familiar with different types of radio frequency modulation, from amplitude modulation to frequency modulation.  A few rare modes use PWM and so do many class-D and E amplifier circuits.  Those familiar with remote control devices know about PWM to reproduce control levels at the controlled device.  Though not digital by intended application, a PWM signal varies the ratio between a signal's high and low levels (called ‘marks’ and ‘spaces’) on a constant oscillation frequency.  Each ‘high’ level often represents a full voltage potential and the ‘low’s' represent no voltage.  When the PWM signal is averaged out over time a predictable intermediate-level voltage is obtained, varied by the relationship between marks and spaces.
.
PWM Duty Cycle
.
       PWM voltage control is often used in power-hungry and high initial current devices such as motors and power supplies where the device is not efficient or operable at lower voltage yet varied or lower power or speed is desired to be produced.  By applying quick pulses of full-power into a motor over small intervals of time, there’s still enough current to overcome the winding's reactance and the cumulative power to kick the motor’s windings into operation, yet with less available duration of power you can spin the motor slower.  Without PWM a motor would require more current to flow to work as opposed to the lower available voltage.  When used in power supplies, a PWM signal at a very high frequency, when averaged, allows for the supply to save space by using a smaller power transformer and even transfer more power efficiently while not wasting some as heat into a tradition linear transformer.

       PWM is the preferred method of light-level control for LED’s...  As mentioned above, LED’s are non-linear devices where the voltage verses current required to produce an amount of light does not seem to be in concert.  By applying the suggested voltage source to an LED but in small varied-duration burst, and do this faster than the human eye can see (due to persistence of vision,) we both satisfy the operational limits of the LED and provide a way to control the level of (apparent) light output.

       The "Old School" Method...

       The easiest and tried and true method for an experimenter to PWM control an LED is to use the venerable '555' timer/oscillator IC.  In the following circuit, it's used in an ‘astable multivibrator’ configuration and is set to around 2 kHz which will pulse an LED on its output quicker than the eye can see.  C1 (.01uF) can be changed to adjust the timing.  The D1 and D2 (1N4148) pair are used to route charging and discharging through the pot R2 to set the PWM duty cycle, which again, is the ratio of ‘mark’ and ‘space’ durations within a repeated block of time.  As the 'on' (mark) pulses get quicker while the 'off' (spaces) get respectively longer, the duty cycle gets lower, and as they trade durations, the cycle gets higher.  Think of it as a ham operator sitting at their station having a long 'rag chew'.  If they're long-winded their duty cycle will be higher and their transmitter will run hotter, and if the other guy is the talker, then vice-versa.  More information on operating the '555' is sure to be found online.  As pin 3 outputs the determined PWM signal, transistor Q1 is switched on to follow suit.  By itself, pin 3 of the timer could run an LED, but it is not suggested.  I used a 2N4401 in my experiment circuit as it can handle up to 600 milliamps which could be up to 20 or 30 regular red LED’s at once if I wanted.
.
RGB LED PWM Control using 555
.
       Can a motor be used instead of an LED?  You can if the motor’s peak-surge current spike does not breach the max rating of the transistor.  Any transistor or power MOSFET can be used to control whatever it will handle considering the specs of the transistor or MOSFET to match that of the application.  Again, online examples are available in abundance to help you get your motors running if you wish.  You can gang LED’s in series and parallel minding whatever type of current protection resistors are used to properly run those LED’s.  And of course, you can use more transistors to control more transistors if bulk is desired.  There’s another advantage of using PWM, and that is consistency.  Whether at 10% or 90% duty cycle, power is applied the same if you’re using an LED as it would be a large motor, so you should be able to host many LED’s of varying types together to a unified result.  You'll still have to consider the proper current limiting resistor value for the host device's peak full-on brightness, and because the device's internal heating and subsequent heat dissipation duration is correlated to the duty cycle, you'll see a smaller resistor value often used to bring more brightness to an LED which is designed for low duty cycles such as with "Charlie-plexing."

       Nothing’s perfect, though.  Once you construct this simple 555-based PWM LED control circuit, you’ll notice a fault right off the bat in that part of the adjustment range on the pot's sweep doesn’t seem to do anything, and when you adjust the pot for minimal brightness the LED doesn’t go completely dark.  This behavior is inherit of the workings of the 555.  Because the oscillator, considering the 555's comparators setup must have something to cycle with, a 555-based PWM signal usually gives you a range between 5% and 95% duty cycle at best and it is not completely linear due to the circuit's capacitor charge/discharge curve.  This means that at the bright end of the scale, the LED will not be at its true full brightness and will be still apparently lit at the low end.  Adding the optional C4, a 0.1 uF capacitor, from the base of the transistor to ground will allow you to bring the LED to a completely ‘off’-state at the low end of the control.  By adding the capacitor, the base of Q1 can only switch on according to the state of charge on C4. Since there is a time factor involved in charging that capacitor, as the pulses get shorter, the power to Q1 starts to diminish and eventually there is nothing going to the LED.  At this point we are destroying any benefit to PWM and we are now augmenting the current level through the host LED, plus this will not work so well on motors or any other high-load device.  In effect, this creates more of a saw-tooth shaped-pulse rather than a square wave and is more of a pseudo-PWM.  You'll have to of course wire up three of these 555 PWM circuits to get full-color control of an RGB LED.

       The "New School" Method...

       By now, most electronics enthusiasts and newbie learners have heard of Arduino and the use of microcontrollers to more easily do any task a conventional discrete logic circuit could do.  All one has to do now is plug an Arduino development board like the UNO R3 into your PC's USB port, launch the Arduino IDE software, wire up their RGB LED's color element anodes to three digital I/O ports of their board in series through appropriate current-limiting resistors, write and upload a "sketch" program and "Bob's you uncle!"  To go a step further, you can wire up a WS2811 addressable RGB LED using only one wire for data then write a sketch with the FastLED library.  Well yes, it's that easy.  In fact, we can use the Arduino to upload a sketch to an even smaller microcontroller IC such as the ATTiny85 which has the identical shape and pin count as a 555 and get an exact duty cycle range between 0% and 100% on all three colors!
.
       This microcontroller method is pretty straight forward if you follow the below instructions.:
.
Arduino Uno Setup For Controlling an RGB LED with PWM
// Sketch for PWM controlling an RGB LED with potentiometer input 

// Define the pins for RGB LED
const int redPin = 11;    // Red LED connected to PWM pin 11
const int greenPin = 10;  // Green LED connected to PWM pin 10
const int bluePin = 9;    // Blue LED connected to PWM pin 9

// Define the analog input pins for potentiometers
const int redPotPin = A0;    // Potentiometer for red connected to analog pin A0
const int greenPotPin = A1;  // Potentiometer for green connected to analog pin A1
const int bluePotPin = A2;   // Potentiometer for blue connected to analog pin A2


void setup() {

  // Set RGB LED pins as outputs
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop() {

  // Read the analog values from potentiometers
  int redValue = analogRead(redPotPin);
  int greenValue = analogRead(greenPotPin);
  int blueValue = analogRead(bluePotPin);

  // Map the potentiometer values (0-1023) to PWM range (0-255)
  int redBrightness = map(redValue, 0, 1023, 0, 255);
  int greenBrightness = map(greenValue, 0, 1023, 0, 255);
  int blueBrightness = map(blueValue, 0, 1023, 0, 255);

  // Set the brightness of the RGB LED using PWM
  analogWrite(redPin, redBrightness);
  analogWrite(greenPin, greenBrightness);
  analogWrite(bluePin, blueBrightness);
 
  delay(10); // Adjust delay as needed for responsiveness
}
.
       Shown on the right is an example of an Arduino sketch that controls a common cathode RGB LED using three potentiometers connected to analog pins for adjusting the perceived luminescence of each RGB channel independently.  You will need any Arduino or Arduino clone model such as the UNO R3, the Nano, the Mega or any related model - keeping in mind the required pin assignments.  You will also need 3 resistors, each anywhere from 220 ohm to 1k ohm and three potentiometers (variable resistors or "pots".)  The value of the pots is not crucial as the ADC (Analog to Digital Converter) simply reads the voltage in which the pot acts as a resistor pad network giving you a selectable voltage between that of the Vcc (5 volts) and ground potential., but anything between 5k ohms and 100k ohms will be fine.  You'll also need some Dupont style jumper wires.

       Copy and paste the sketch above into the Arduino IDE and upload to your Arduino.  Since this article is about controlling an RGB LED, any training or help you should require for the setup and operation of an Arduino can be found readily on YouTube or Arduino.org and is beyond the scope of this article.  It is also possible to use an ATTiny85 but that requires an extra bit of expertise as only certain pins can be made to run PWM.

       For wiring, connect the common cathode of the RGB LED to the GND pin of the Arduino Uno then the anodes of the red, green, and blue LED elements to PWM-enabled pins 11, 10, and 9 respectively. Connect each potentiometer's middle pin to the analog input pins A0, A1, and A2, and connect their other two pins to 5V and GND respectively.

       The sketch reads the analog values from the potentiometers, maps these values to a range suitable for PWM (0-255,) and sets the brightness of the corresponding LED channels accordingly. Adjust the potentiometers to control the perceived luminescence of each RGB channel independently.  Upload the sketch to the Arduino and "taste the rainbow" as they say. (LED's are not Skittles, so keep them out of the reach of children.) Since this is a microcontroller, feel free to augment and write your own code!  First, try printing to the serial monitor, the potentiometer ADC values as well as the PWM output values.  You can use any chosen value later on in other projects to get that perfect color.  Next, you can try omitting the pots and using loops and delays to produce your own little light show.  I would offer more suggestion, but this is a juicy can of worms you'll never be able to close once you open it!

       Addressable RGB LED's...

       Using an addressable RGB LED, commonly known as "NeoPixels," WS2811, WS2812 and etc., with an Arduino opens up a world of colorful possibilities for lighting projects.  These LED's allow individual control of each LED within a strip or matrix via one or two wires, enabling a wide and complex range of dynamic lighting effects.  Again, using them is outside the scope of this article but I'll share a basic primer.  Please refer to YouTube and other sources for better information.  But to begin using them, you'll need a WS2811 LED or compatible addressible LED strip and the FastLED library installed in the Arduino IDE.  Firstly, wire the WS2811 LED or LED strip to your Arduino.  Typically, connect the data-in (DiN) pin of the LED strip to one of the digital pins on the Arduino (like pin 6, for instance,) make sure to run a small-value resistor in series with this line to protect the LED's sensitive onboard chip input (use a 470 ohm reisitor,) then install the FastLED library by navigating to the Arduino IDE's Library Manager and searching for 'FastLED' to install it.
.
#include <FastLED.h>  // Make sure to install this library first

#define LED_PIN 6
#define NUM_LEDS 60  // Change this number to match the number of LEDs in your strip

CRGB leds[NUM_LEDS];  // This is an array that holds color values for each LED

void setup() {
  FastLED.addLeds<WS2811, LED_PIN, GRB>(leds, NUM_LEDS);

    // "WS2811" is the LED type and "GRB" is the part's RGB order
    //  and on some models you would put 'RGB'. If the colors are wildly off, consider this the issue.
}

void loop() {

  // We'll just show a simple example...

  // Fill the first half of the strip with red color
  for (int i = 0; i < NUM_LEDS / 2; i++) {
    leds[i] = CRGB::Red;   // The FastLED library has a few ways for programming a certain color
  }                        //  from pre-set names, to hue, to r,g,b values.

  // Fill the second half of the strip with blue color
  for (int i = NUM_LEDS / 2; i < NUM_LEDS; i++) {
    leds[i] = CRGB::Blue;
  }

  FastLED.show();   // This command sends all the color data down the chain of LED's
  delay(1000);      // Display for 1 second before changing colors
}
.
     Oh, and NEVER connect the (+) power lead of addressable LED's to the Arduino's 5v source because you will quickly fry your Arduino.  Connect it's power to an independent source such as the power supply that runs everything, but make sure to bond all the ground lines together.  Once the library is installed, you can access various examples and functions provided by FastLED to control the LEDs.  A common starting point is to use the 'FastLED.show()' function to display colors on the LED strip.  For instance, you can set individual LEDs to specific colors using arrays and loops.  There's a neat example sketch with the FastLED library called the Show Reel which will try out all kinds of effects on your multi LED strips or panels.
.
Addressable LED's
.
       In this article, I presented the modern miracle that is the RGB Full-Color LED, some information on the nature of controlling these devices and presented three levels of achieving that control.  Hopefully, you learned a little as well or at least are now familiar with the requirements for using RGB LED's.  Each approach shown is applicable to different problems.  You wouldn't need an Arduino board to give you that perfect shade of aqua blue on a panel LED, but you'll certainly need one for controlling wall panel arrays of addressable "erga-bleds." (RGB LED's).  The 555 is of course, one of the most useful building-block parts ever invented and why write and upload a program to a device powered by a regulated supply if you don't have to?  RGB LED's are really useful in many projects, are cheap as chips these days and are worth experimenting with.   
.
       The weekend is here so go and build something!
.
       73! DE Mike, K4ICY  MikeK4ICY@gmail.com


.

Edited: 12/03/23

(C) 2013, 2023 Copyright - Michael A. Maynard