Lesson 16. Controlling an RGB LED

Continuing to master the PWM, this time to control the color of the RGB LED.

Essentially, an RGB LED is a combination of three common LEDs - red, green and blue.

Accordingly, an RGB LED has 4 legs: one leg is used to control each of the colors and one common leg (usually the longest). Common can be both the cathode (-) and the anode (+). The diagram shows an example for a circuit with a common anode.

It is noteworthy that by mixing these 3 colors you can get almost any other color. If you light all 3 LEDs at the same time, you get white.

Now about the implementation, I got an LED with a common cathode, the rated current, which according to the datasheet was 20mA. However, there is a small nuance, each color has its own ignition threshold. For example, for a red LED, 20mA corresponds to a voltage of 2.1V, green and blue - a voltage of 3.2V. In general, the leg of the microcontroller must withstand such a current, so you can safely connect it to the microcontroller through current-limiting resistors.
I used pnp transistors, but I do not impose this idea on anyone.

Atmega8 has 3 PWM channels: two channels on timer1 (legs PB.1 - OCR1A, PB.2 - OCR1B) and one timer2 (legs PB.3 - OCR2). By adjusting the PWM filling, we adjust the voltage on the LED, respectively, its brightness.

Create a new project, set up a timer 2.

Since OCR2 is 8-bit and OCR1 is 10-bit, the maximum value of OCR2 = 0xFF (255), and OCR1A / B = 0x3FF (1023), i.e. 4 times more. We take this feature into account, therefore, so that the channels are regulated in the same way, we set the timer frequency 4 times more. Accordingly, the maximum brightness for OCR2 will be at 0xFF, and for OCR1 at 0x3FF.

Set up the PB1-PB3 legs as an exit. In the main loop of the program, we add a code that smoothly lights up red from 0 to 255, and then smoothly extinguishes it from 255 to 0.

while (OCR1A<0x3FF) { OCR1A++; delay_ms(2); } while(OCR1A>0x00) (OCR1A--; delay_ms (2);)

Result:

If you need to get some specific color, for example purple, open some kind of graphics editor, for example Paint.net go into the palette, click on the color you like, on the right, where RGB is written, its numerical values ​​R = 255, B = 220 will be displayed.

Channel R is on OCR2, so we can safely write 0xFF (255) in OCR2, channel B on OCR1A, but since the maximum value is 1023, then we recalculate the proportion:

(220 * 1023) / 255 = 882 so we boldly shove it into OCR1A, the result is pretty similar.