Using this code on an ESP32 allows varying the duty cycle of the PWM with a fixed 5000 Hz frequency; it is working fine.
How do I vary the frequency and keep the duty cycle at a fixed value?
// the number of the LED pin
const int ledPin = 16; // 16 corresponds to GPIO16
// setting PWM properties
const int freq = 5000;
const int ledChannel = 0;
const int resolution = 8;
void setup(){
// configure LED PWM functionalitites
ledcSetup(ledChannel, freq, resolution);
// attach the channel to the GPIO to be controlled
ledcAttachPin(ledPin, ledChannel);
}
void loop(){
// increase the LED brightness
for (int dutyCycle = 0; dutyCycle <= 255; dutyCycle++) {
// changing the LED brightness with PWM
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
// decrease the LED brightness
for (int dutyCycle = 255; dutyCycle >= 0; dutyCycle--) {
// changing the LED brightness with PWM
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
}
1 Answer 1
If you want to change the pwm frequency during runtime there is a function ledc_set_freq()
for this purpose. I'm not sure if your duty cycle will remain valid, but I guess it does as long as the resolution does not change. You will have to try that on your own and eventually implement a compensation.
-
I tried using ledc_set_freq but the issue is that if do it very quickly then is not set it anymore. If I do this on a normal arduino using pwm library i can change pin frequency each 50ms and is fine.lucian_v– lucian_v06/14/2019 11:33:30Commented Jun 14, 2019 at 11:33
ledcWriteTone
?