# PWM frequency and duty cycle

**URL:** <https://forum.amebaiot.com/t/pwm-frequency-and-duty-cycle/3105>\
**Category:** Peripherals\
**Tags:** rtl8735b\
**Created:** [July 12, 2024, 5:53pm UTC](https://forum.amebaiot.com/t/pwm-frequency-and-duty-cycle/3105 "2024-07-12T17:53:52Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![nsmith1024](https://avatars.discourse-cdn.com/v4/letter/n/bc79bd/32.png) [@nsmith1024](https://forum.amebaiot.com/u/nsmith1024)\
**Post date:** [July 12, 2024, 5:53pm UTC](https://forum.amebaiot.com/t/pwm-frequency-and-duty-cycle/3105/1 "2024-07-12T17:53:52Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Kelvin\_Huang](https://sea2.discourse-cdn.com/flex016/user_avatar/forum.amebaiot.com/kelvin_huang/32/2130_2.png) [@Kelvin\_Huang](https://forum.amebaiot.com/u/Kelvin_Huang)\
**Post date:** [July 13, 2024, 12:15pm UTC](https://forum.amebaiot.com/t/pwm-frequency-and-duty-cycle/3105/2 "2024-07-13T12:15:05Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![nsmith1024](https://avatars.discourse-cdn.com/v4/letter/n/bc79bd/32.png) [@nsmith1024](https://forum.amebaiot.com/u/nsmith1024)\
**Post date:** [August 19, 2025, 10:45am UTC](https://forum.amebaiot.com/t/pwm-frequency-and-duty-cycle/3105/3 "2025-08-19T10:45:25Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![M-ichae-l](https://sea2.discourse-cdn.com/flex016/user_avatar/forum.amebaiot.com/m-ichae-l/32/33_2.png) [@M-ichae-l](https://forum.amebaiot.com/u/M-ichae-l)\
**Post date:** [September 1, 2025, 7:23am UTC](https://forum.amebaiot.com/t/pwm-frequency-and-duty-cycle/3105/4 "2025-09-01T07:23:28Z")

</div>

You may want to refer to this source code [link](https://github.com/Ameba-AIoT/ameba-arduino-pro2/blob/18f4f5f8e737983ce4b54d54fdcf48edffc78bcb/Arduino_package/hardware/cores/ambpro2/wiring_analog.c#L259C6-L259C11)
