RGB LEDs are special LEDs that combine Red, Green, and Blue in one package. By adjusting the brightness of each color, you can create millions of colors 🌈.
In this tutorial, you’ll learn:
This project is beginner-friendly and helps you understand analogWrite (PWM) on ESP8266.
There are two types of RGB LEDs:
👉 For simplicity, we’ll use Common Cathode in this tutorial.
Text diagram (NodeMCU pins):
// RGB LED with ESP8266 (NodeMCU/Wemos)
// Common Cathode RGB LED example
int redPin = D1; // GPIO5
int greenPin = D2; // GPIO4
int bluePin = D3; // GPIO0
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
// Function to set color
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue); // 0 - 1023
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}
void loop() {
setColor(1023, 0, 0); // Red
delay(1000);
setColor(0, 1023, 0); // Green
delay(1000);
setColor(0, 0, 1023); // Blue
delay(1000);
setColor(1023, 1023, 0); // Yellow (Red + Green)
delay(1000);
setColor(0, 1023, 1023); // Cyan (Green + Blue)
delay(1000);
setColor(1023, 0, 1023); // Magenta (Red + Blue)
delay(1000);
setColor(1023, 1023, 1023); // White (All ON)
delay(1000);
setColor(0, 0, 0); // OFF
delay(1000);
}
Define pins
int redPin = D1;
int greenPin = D2;
int bluePin = D3;
Pins Setup
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Custom Function
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}
analogWrite()
generates a PWM signal (0–1023 on ESP8266).Loop colors
With just a few lines of code, you learned how to control an RGB LED with ESP8266. Using PWM and color mixing, you can create endless lighting effects for your IoT projects.
Next, you can expand this project by:
Yes, ESP8266 supports software PWM on all digital pins.
analogWrite()
accepts values from 0 (OFF) to 1023 (FULL brightness).
You might be using a Common Anode LED. In that case, use 1023 - value
in analogWrite.