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);
 }
}
ocrdu
1,7953 gold badges12 silver badges24 bronze badges
asked Jun 4, 2019 at 20:42
4
  • const int freq = 5000; - this is the frequency Commented Jun 4, 2019 at 20:51
  • Hm. Right, sorry Commented Jun 4, 2019 at 20:52
  • Use ledcWriteTone ? 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. 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.

answered Jun 5, 2019 at 18:05
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. Commented Jun 14, 2019 at 11:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.