changing pwm frequency during void loop()

I'm currently using PWM library ( from and I'm able to change the pwm frequency in the setup .

But is it possible to change the frequency during the void loop() (i.e change the frequency at every execution) ?


Sure, why not?

the void loop()

It is called the loop function. void is not part of its name just the sort of variable it returns.

Why do you want to do this? It is an unusual thing to want to do.

Sounds like a X-Y Problem

I'd like to bring this topic up again as I am having the same question. Wonder if someone can confirm.

Traditionally, we set frequency during setup then change duty cycle in lop function.

There are also cases when we need to alter frequency while within loop function. There are things out there driven by altering frequency.

Is it possible?

Yes. Frequency is based on register settings, yes? Just write to the same registers within loop() when some condition is met. Example:

if ( (digitalRead(buttonX) == LOW ) && (priorButtonState == HIGH) ){
priorButtonState = LOW; // button press occurred, change state from High to Low
//change PWM frequency register(s)
if ( (digitalRead(buttonX) == LOW ) && (priorButtonState == LOW) ){
priorButtonState = HIGH; // button press occurred, change state from Low to  High
// change PWM frequency register(s) back to original settings
This way, you are not rewriting the registers all the time, only when the button is Pressed, or Released, and the held state does not matter.

Thank CrossRoads. Very detailed answer.

I have just done a test with the Mega and an oscilloscope too. Positive :)