1

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);
  }
}
4
  • const int freq = 5000; - this is the frequency
    – lucian_v
    Commented Jun 4, 2019 at 20:51
  • Hm. Right, sorry
    – Eugene Sh.
    Commented Jun 4, 2019 at 20:52
  • Use ledcWriteTone ?
    – Eugene Sh.
    Commented Jun 4, 2019 at 20:57
  • Why remove points on the question? changing the frequency will be helpful if you are working with a stepper motor for example.
    – Tono Nam
    Commented Sep 13, 2021 at 2:22

1 Answer 1

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.

1
  • 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
    Commented Jun 14, 2019 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.