RGB LED (Analog)

In the previous project, we learned how to control an RGB LED using digitalWrite. By using digitalWrite, we could turn the internal red, green, and blue LEDs on or off, creating 8 possible color combinations (including off). In today’s project, instead of just two states for each LED, we will adjust the brightness of each LED. This allows for a wider range of colors.

const int redLed = 22;
const int greenLed = 21;
const int blueLed = 19;

void setRGBLed(uint8_t redValue, uint8_t greenValue, uint8_t blueValue) {
    analogWrite(redLed,redValue);
    analogWrite(greenLed,greenValue);
    analogWrite(blueLed,blueValue);
    delay(1000); // Delay 1 second
}

void setup() {
    pinMode(redLed,OUTPUT);
    pinMode(greenLed,OUTPUT);
    pinMode(blueLed,OUTPUT);

    setRGBLed(128,0,0);//50% brightness for Red
    setRGBLed(0,128,0); //50% brightness for Green
    setRGBLed(0,0,128); //50% brightness for Blue
    setRGBLed(0,0,0); //off
}

void loop() {
    uint8_t redValue = random(0,256); // Generates 0 to 255
    uint8_t greenValue = random(0,256);
    uint8_t blueValue = random(0,256);
    setRGBLed(redValue, greenValue, blueValue);
}
C++
analogWrite(pin, value);
C++

The analogWrite() function in Arduino (and in ESP32’s Arduino core) is used to output a Pulse Width Modulation (PWM) signal to control the brightness of LEDs, the speed of motors, and other similar applications. While the function name suggests analog output, it actually produces a digital signal that simulates an analog output by rapidly switching between HIGH (on) and LOW (off) states at a certain frequency.

PWM (Pulse Width Modulation) is a technique used to simulate analog signals using a digital output. It involves turning a signal on and off rapidly in a periodic manner, with the fraction of time the signal stays on called the duty cycle. The duty cycle determines how “bright” or “strong” the output appears. A higher duty cycle means the output is on more often, making it appear brighter or stronger.

It works by switching the signal between HIGH and LOW very quickly, controlling how long the signal stays HIGH (on) compared to LOW (off) within a given time frame.

The pin number to which you want to send the PWM signal (must be a PWM-capable pin). A value between 0 and 255 that defines the duty cycle.

  • 0: Pin always LOW (off).
  • 255: Pin always HIGH (on).
  • Values in between give a proportionate duty cycle (brightness level).

For example:

  • analogWrite(pin, 128); gives a 50% duty cycle (LED brightness at 50%).
  • analogWrite(pin, 64); gives a 25% duty cycle (LED brightness at 25%).
uint8_t redValue, uint8_t greenValue, uint8_t blueValue
C++

uint8_t is an unsigned 8-bit integer data type. It can store values from 0 to 255 and is commonly used for small numbers or controlling things like LED brightness in embedded programming. It is 1 byte in size and ensures consistent, memory-efficient storage.

RELATED ARTICLES