Arduino IDE: RGB LED, for, while, do while loops #7

Arduino IDE

Welcome back to our programming tutorial using the Arduino IDE. Today we will deal with loops to operate color changing on a RGB LED.

You can take a look at the previous chapters of the course here:

RGB LEDs can be a sparkling way to add originality and fun to your project.

The RGB LED can be considered as the union of three LEDs (one red, one green and one blue LED) in a singular structure. The use and connection (both electronically and programmatically) is not very different compared to traditional LEDs.

There are two different versions of RGB LEDs on the market, the first with common anode, and the second with common cathode. The version with common anode uses 5V on the pin, while the second version with common cathode uses GND grounding on the pin.

In order for the correct operation of the RGB LED to occur, we use three resistors to limit the current passing through it.

An RGB LED is a LED that has 3 different semiconductors inside, each capable of emitting a different color and in particular red, green and blue. As is well known, all the colors of the spectrum can be made from a combination of the fundamental colors red green and blue.

RGB LED Arduino

We use PWM (pulse width modulation) to vary the brightness of the LEDs. As the Arduino PWM can manage values ​​from 0 to 255, we can associate this value with the amount of each color component to form different tints. For example, by setting the PWM of red to 128 and the PWM of blue to 255 we can obtain purple.

Pulse Width Modulation (PWM) is a technique for controlling input/putput varying the duty cycle of a square wave with the voltage of the signal. In this case PWM is used to control the brightness of each individual LED. The pulse is controlled by the analogWrite function.

The RGB LED will be programmed to first turn on with the red color state, then it will change to green, and finally it will emit blue light, and cyclically return back to the red color.

List of the required components:

Everything you need is available in the Elegoo Advanced Starter Kit.

The connection diagram is as follows:

RGB LED Arduino

The wiring diagram is as follows:

RGB LED Arduino

There are several ways to write the code using different iterative structures.

Code with for loops:

Code with the while() loop:

Code with the do…while() loop:

 

Previous articles:

Follow us to keep yourself updated with the news!

Simone Candido è un ragazzo appassionato del mondo tech nella sua totalità. Simone ama immedesimarsi in nuove esperienze, la sua filosofia si basa sulla irrefrenabile voglia di ampliare a 360° le sue conoscenze abbracciando tutti i campi del sapere, in quanto ritiene che il sapere umano sia il connubio perfetto tra cultura umanistica e scientifica.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.