PWM frequency and duty cycle

Hello,

I need to control both frequency and duty cycle for multiple PWM channels.

Rignt now im using this code to control the duty cycle

pinMode(PWM_A, OUTPUT);
analogWrite(PWM_A,duty);

How can i control the frequency of the PWM as well as the duty cycle?

Thanks

Hi @nsmith1024,

You can use void analogWritePeriod(int us) to set the duty cycle. Do a loop for the analogWrite API for the frequency.

Thank you.

Thanks for your answer.

I need to generate a melody using a series of tones, but i cant use the tone() function because tone() cant be called from inside an interrupt that is needed to maintain the proper timing for the melody, so i need to use the PWM directly.

Can you show an example code of how i can change the PWM frequency?

My code cannot sit in a loop as you suggest because it has other things to do, and it cant be in a loop inside the interrupt.

Is there a way to just set the frequency without having loops from inside an interrupt?

Thanks

You may want to refer to this source code link