-
PWM_pin: The GPIO pin you want to use as PWM output (e.g., GPIO 16).
-
channel: The channel number you configured in Step 1.
Step 3: Set the Duty Cycle (ledcWrite())
This function outputs the PWM signal with the specified duty cycle to the attached pin.
ledcWrite(channel, duty_value);
-
channel: The channel number.
-
duty_value: An integer value between 0 and (2^resolution – 1). For 8-bit resolution, this is 0-255.
Practical Example: Fading an LED
Let’s put theory into practice by creating a classic fading LED effect.
Components Needed:
Circuit Connection:
Connect the anode of the LED (long leg) through the 220Ω resistor to GPIO 16. Connect the cathode (short leg) to GND.
Code:
// Define the PWM Channel, GPIO Pin, and PWM parameters
const int pwmChannel = 0; // Select PWM channel 0
const int pwmPin = 16; // GPIO 16 for PWM output
const int freq = 5000; // PWM frequency of 5 KHz
const int resolution = 8; // 8-bit resolution (duty cycle 0-255)
void setup() {
// Configure the PWM functionalit
ledcSetup(pwmChannel, freq, resolution);
// Attach the channel to the GPIO pin
ledcAttachPin(pwmPin, pwmChannel);
}
void loop() {
// Increase LED brightness gradually
for (int dutyCycle = 0; dutyCycle <= 255; dutyCycle++) {
ledcWrite(pwmChannel, dutyCycle);
delay(10);
}
// Decrease LED brightness gradually
for (int dutyCycle = 255; dutyCycle >= 0; dutyCycle–) {
ledcWrite(pwmChannel, dutyCycle);
delay(10);
}
}
This code will smoothly fade the LED on and off by incrementally changing the duty cycle.
Advanced Applications of ESP32 PWM
The utility of PWM extends far beyond dimming lights:
-
Servo Motor Control: Servos use PWM pulses of a specific duration (typically 1-2ms) within a 20ms period to determine their angle. The ESP32’s high resolution allows for very precise servo positioning.
-
DC Motor Speed Control: Coupled with an H-Bridge motor driver IC (like the L298N), PWM is the standard method for controlling the speed and direction of DC motors.
-
Audio Generation: By generating PWM signals at audio frequencies (20Hz – 20kHz) and filtering the output with a low-pass filter, the ESP32 can synthesize simple tones and sounds.
-
Power Regulation: PWM is the cornerstone of modern switched-mode power supplies (SMPS) and voltage regulators, allowing for highly efficient power conversion.
Conclusion
Mastering Pulse Width Modulation is a critical skill for anyone working with the ESP32. Its dedicated hardware, high resolution, and pin flexibility make it superior to many other microcontrollers for generating precise digital control signals. By understanding the ledcSetup(), ledcAttachPin(), and ledcWrite() functions, you can unlock a world of possibilities, from creating simple lighting effects to building complex robotic systems. Integrate these techniques into your next ESP32 project to achieve professional-grade control over analog devices.