ESP32 LED Fade with PWM
Smoothly changing the brightness of the LED from 0 to max, from max to 0. We control PWM with analogWrite() as in Arduino - the same syntax as ESP32 Arduino Core 3.0+ works without problems. Pin definition + pinMode + analogWrite is enough.

Video
Elektr sxemasi

Manba kodi
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// ESP32 LED Fade with PWM
4// ─────────────────────────────────────────
5// Uses analogWrite() PWM to raise the LED brightness smoothly from 0 to
6// 255, then lower it smoothly back to 0.
7//
8// Pins:
9// GPIO 5 -> Blue LED (with a 330 ohm resistor)
10// GND -> LED short leg (cathode)
11
12const int LED_PIN = 5; // PWM output
13
14void setup() {
15 pinMode(LED_PIN, OUTPUT);
16}
17
18void loop() {
19 // Fade in
20 for (int brightness = 0; brightness <= 255; brightness++) {
21 analogWrite(LED_PIN, brightness);
22 delay(8); // 8 ms per step, ~2 s in total
23 }
24 // Fade out
25 for (int brightness = 255; brightness >= 0; brightness--) {
26 analogWrite(LED_PIN, brightness);
27 delay(8);
28 }
29}
30
Ko‘p so‘raladigan savollar
Does `analogWrite` actually work on the ESP32?
Yes, analogWrite() is supported in ESP32 Arduino Core 3.x as well as some 2.x versions, and it uses the LEDC hardware. Check support for the core version you are using; ledcSetup and ledcAttachPin are not required in all 2.x versions.
Which pins support PWM?
Almost all GPIO pins on the ESP32 that can function as outputs can generate PWM. GPIO pins 34–39 cannot generate PWM because they are input-only.
The change in brightness doesn't appear to be linear—why?
Eye brightness is perceived logarithmically; changes at low values are more noticeable. If you transform the values using a gamma table, the transition looks more natural.
Can I change the PWM frequency?
Yes, you can adjust the frequency and resolution using the analogWriteFrequency() or LEDC functions. A high frequency, such as 5 kHz, completely eliminates flickering in the LED.
