0

Using this code on an esp32 allow to vary duty cycle of the PWM with a fixed 5000Hz frequency and is working fine.

My question is how to vary frequency and keep duty cycle on 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);
  }
}

Thanks

4
  • const int freq = 5000; - this is the frequency
    – lucian_v
    Jun 4, 2019 at 20:51
  • Hm. Right, sorry
    – Eugene Sh.
    Jun 4, 2019 at 20:52
  • Use ledcWriteTone ?
    – Eugene Sh.
    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
    Sep 13, 2021 at 2:22

1 Answer 1

0

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

Your Answer

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

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