PWM
This article explores the use of Pulse Width Modulation (PWM) to adjust LED brightness, providing a step-by-step guide and sample code for creating dynamic lighting effects on the Edge101 board using an ESP32 IoT Programmable Controller.
Example: Adjusting LED Brightness with PWM
Create a breathing light effect on the user LED of the Edge101 board by adjusting its brightness using PWM with a frequency of 5000Hz.
Hardware Preparation:
- ESP32 IoT Programmable Controller (SKU: DFR0886)×1
Sample Code:
// PWM channel configuration
#define PWM_CH 0 // Use PWM channel 0
#define PWM_FREQ 5000 // Set PWM frequency to 5kHz
#define PWM_RES 13 // 13-bit resolution (range 0-8191)
#define LED_PIN 15 // LED connection pin
// Breathing light control parameters
int brightness = 0; // Current brightness value (0-255)
int fadeAmount = 5; // Brightness change step
/**
* Custom PWM output function
* @param ch PWM channel
* @param val Brightness value (0-255)
* @param maxVal Maximum input value (default is 8-bit)
*/
void ledcAnalogWrite(uint8_t ch, uint32_t val, uint32_t maxVal = 255) {
// Convert 8-bit brightness value to 13-bit duty cycle
ledcWrite(ch, (8191 / maxVal) * min(val, maxVal));
}
void setup() {
// Initialize PWM configuration
ledcSetup(PWM_CH, PWM_FREQ, PWM_RES); // Set PWM parameters
ledcAttachPin(LED_PIN, PWM_CH); // Bind pin to PWM channel
}
void loop() {
// Output the current brightness value
ledcAnalogWrite(PWM_CH, brightness);
// Update brightness value (linear gradient)
brightness += fadeAmount;
// Reverse gradient direction when reaching brightness limits
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(30); // Control breathing light speed
}
Was this article helpful?
