
The ESP8266 does not have a true analog output, but it uses PWM (Pulse Width Modulation) to simulate it. With PWM, you can adjust the LED brightness smoothly instead of just turning it ON or OFF.
In this tutorial, you will learn:
PWM stands for Pulse Width Modulation.
On ESP8266, the PWM value range is 0 – 1023:
0 → LED completely OFF512 → LED at 50% brightness1023 → LED fully ONText description (using NodeMCU / Wemos D1 Mini):

// LED Brightness Control using PWM on ESP8266
int ledPin = D2; // GPIO4
void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as output
}
void loop() {
// Fade IN
for (int brightness = 0; brightness <= 1023; brightness++) {
analogWrite(ledPin, brightness); // Set LED brightness
delay(5); // Small delay for smooth fading
}
// Fade OUT
for (int brightness = 1023; brightness >= 0; brightness--) {
analogWrite(ledPin, brightness);
delay(5);
}
}
Define LED pin
int ledPin = D2;
Setup pin as output
pinMode(ledPin, OUTPUT);
Fade in loop
for (int brightness = 0; brightness <= 1023; brightness++) {
analogWrite(ledPin, brightness);
delay(5);
}
Fade out loop
for (int brightness = 1023; brightness >= 0; brightness--) {
analogWrite(ledPin, brightness);
delay(5);
}
Decreases brightness back to 0.
🔆 Result: The LED smoothly fades in and out continuously.
With just a few lines of code, you can control LED brightness using PWM on ESP8266. You learned:
Next, you can expand this project to:
Yes, all digital GPIOs support software PWM.
Default is 1 kHz, but it can be changed using analogWriteFreq().
Yes, you can use different GPIO pins for multiple PWM outputs.






