Welcome to ESP32 Core Board repository
8. PWM Breathing LED
PWM Breathing LED
PWM Breathing LED1. PWM Breathing LED Overview2. Core Concepts2.1 PWM Principle2.2 Breathing Algorithm: Triangular Wave3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Details5.1 Macro Definitions and Global Variables5.2 setup() — Initialize PWM5.3 loop() — Breathing Algorithm6. Operation Flow6.1 Build and Flash6.2 Normal Phenomena6.3 Verification Methods7. Common Issues
1. PWM Breathing LED Overview
PWM (Pulse Width Modulation) controls LED brightness by changing the ratio of high/low level time. This experiment uses analogWrite on GPIO43 to generate PWM waves, changing the duty cycle in a triangular wave pattern to achieve an LED fade-in/fade-out "breathing" effect.
Typical Application Scenarios:
| Application Type | Example |
|---|---|
| LED Control | Breathing light, keyboard backlight, ambient light brightness adjustment |
| Motor Drive | DC motor speed control, servo angle control, stepper motor micro-stepping |
| Audio Generation | Generate simple DAC / analog audio output with low-pass filter |
| Power Management | DC-DC converter control signals, charging IC enable modulation |
Three Core Parameters of PWM
① Period: The time for one complete "on→off" cycle, in seconds. Period = 1 / Frequency.
② Frequency: How many "on→off" cycles per second, in Hz. How high should the frequency be?
Too low (<50Hz): Human eye can detect LED flickering, motor will shake
Moderate (~1kHz): LED appears stable, ordinary motor runs smoothly — this experiment uses 1kHz
Too high (>20kHz): Beyond human hearing range, suitable for quiet motor drive scenarios, but switching loss increases
③ Duty Cycle: In one cycle, the ratio of "high level time" to "entire cycle time".
xDuty Cycle = (High Level Time / Period) × 100%For example, frequency 1kHz (period = 1ms):25% duty cycle = 0.25ms high + 0.75ms low → average voltage ≈ 0.825V50% duty cycle = 0.50ms high + 0.50ms low → average voltage = 1.65V80% duty cycle = 0.80ms high + 0.20ms low → average voltage = 2.64V
The beauty of PWM is: you only change the "on/off" time ratio (duty cycle), but the load feels like the voltage is changing continuously. This is the "area equivalent principle" — the average area value of a high-frequency square wave is equivalent to a constant analog voltage value.
2. Core Concepts
2.1 PWM Principle
PWM signal is determined by two parameters: period and duty cycle:
xxxxxxxxxxPeriod = 1/frequency (fixed, e.g. 5000Hz → 200μs)Duty Cycle = High Level Time / Period × 100%0% duty cycle: ▏▁▁▁▁▁▁▁▁▏ — always low50% duty cycle: ▏▔▔▔▔▁▁▁▁▏ — half high half low100% duty cycle:▏▔▔▔▔▔▔▔▔▏ — always high
ESP32-S3 uses LEDC (LED PWM Controller) peripheral, supporting up to 16-bit resolution. Arduino's analogWrite wraps LEDC, with duty cycle range 0~255 (8-bit effective).
2.2 Breathing Algorithm: Triangular Wave
xxxxxxxxxxBrightness255 ┤ ╱╲ ╱╲│ ╱ ╲ ╱ ╲│ ╱ ╲ ╱ ╲│ ╱ ╲ ╱ ╲0 ┤────╱ ╲╱ ╲──── TimeFade dim Fade bright Fade dim
Each iteration updates the brightness value by the step size, reverses direction downward when hitting the upper limit, and reverses direction upward when hitting the lower limit. breathStep controls the change speed (larger = faster but more stepping artifacts), delayMs controls the animation rhythm.
3. Hardware Dependencies
| Pin | Peripheral | Configuration | Description |
|---|---|---|---|
| GPIO43 | LED | OUTPUT | Common anode connection, PWM=LOW = on |
With common anode connection, duty cycle is inversely related to brightness:
analogWrite(0)= always low = LED brightest;analogWrite(255)= always high = LED off.
4. Project Architecture and Flow
xxxxxxxxxxsetup()├─ pinMode(43, OUTPUT) // Configure GPIO as output└─ analogWrite(43, 0) // Initial duty cycle 0 = LED brightestloop()├─ brightness += direction * step // Update brightness by direction├─ if brightness >= 255 → clamp + reverse direction (downward)├─ if brightness <= 0 → clamp + reverse direction (upward)├─ analogWrite(43, brightness) // Output PWM└─ delay(10ms) // Control change rate
5. Source Code Details
Complete source code: Source Code → Arduino → 1.Basic Peripherals → 8.PWM_LED → 8.PWM_LED.ino
5.1 Macro Definitions and Global Variables
Three parameters control the breathing rhythm. direction of +1 means fade in, -1 means fade out.
xxxxxxxxxx
const int breathStep = 5; // Step size: change of 5 units per 10msconst int delayMs = 10; // Delay per step: 10msconst int maxBrightness = 255; // Maximum duty cycle
int currentBrightness = 0; // Current brightnessint direction = 1; // Direction: +1 fade in, -1 fade outComplete breathing cycle ≈ (256/5) × 10ms × 2 ≈ 1024ms ≈ 1 second. Modify
breathStepanddelayMsto adjust speed.
5.2 setup() — Initialize PWM
analogWrite(0) sets initial duty cycle to 0, corresponding to LED brightest.
xxxxxxxxxxvoid setup() { pinMode(LED0_PIN, OUTPUT); analogWrite(LED0_PIN, 0); // 0% duty cycle = always low = LED brightest}After setting
pinModetoOUTPUT,analogWriteautomatically assigns LEDC channel and configures PWM parameters for that pin, no additional initialization needed.
5.3 loop() — Breathing Algorithm
Core of triangular wave brightness: reverse direction when hitting boundaries.
xxxxxxxxxxvoid loop() { currentBrightness += direction * breathStep;
if (currentBrightness >= maxBrightness) { currentBrightness = maxBrightness; direction = -1; // At top → reverse downward } else if (currentBrightness <= 0) { currentBrightness = 0; direction = 1; // At bottom → reverse upward }
analogWrite(LED0_PIN, currentBrightness); delay(delayMs);}The purpose of clamping
currentBrightnessis to prevent the brightness from getting "stuck" outside the boundary when the step size does not divide evenly into 255.
6. Operation Flow
6.1 Build and Flash
Arduino flash process: See Arduino → 1. Before Development → 2. Build and Flash.
6.2 Normal Phenomena
After powering on, the LED cycles fade-in→fade-out with approximately 1 second period, simulating a breathing effect.
6.3 Verification Methods
| Operation | Expected Result |
|---|---|
| Power on and observe | LED fades in and out smoothly, no flickering |
Change breathStep = 5 to breathStep = 20 | Breathing speeds up, stepping artifacts more noticeable |
Change delayMs = 10 to delayMs = 30 | Breathing slows down, smoother |
7. Common Issues
| Phenomenon | Cause | Solution |
|---|---|---|
| LED not lit | Incorrect analogWrite value (with common anode, 255=off) | Confirm initial value is 0 not 255 |
| Obvious stepping artifacts in breathing | Step size too large or delay too short | Decrease breathStep or increase delayMs |
| Low PWM frequency causing flicker | Default LEDC frequency ~5kHz, not perceivable by eye | Normal, no adjustment needed |