Tutorials
Set RP2040 PWM to 20 kHz and Know How Many Duty Steps Remain
Published · Updated
Writing 32768 to the compare register does not guarantee 50% duty. The compare value has to fit the counter period that the PWM slice actually uses. A logic probe stuck high is often the first clue that the period changed but the compare value did not.
Count zero as one of the PWM states

In free-running, trailing-edge mode the RP2040 counter runs from zero through TOP inclusive. The frequency is the slice input clock divided by the clock divider and by TOP plus one. Get the current system clock from the running firmware.
Pico projects can change it after startup. Phase-correct mode traverses the counter differently and needs a separate calculation. A and B outputs of the same slice share its divider and TOP, even though their compare values can differ.
Check current at the GPIO load · Test a counter at its boundaries
Build a 50 microsecond period from a 125 MHz clock

With clk_sys measured or configured at 125 MHz and divider 1, a 20 kHz output needs 6,250 counter states. Set TOP to 6,249 and the compare level to 3,125 for a 50% high interval on a non-inverted output. One count changes the high time by 8 ns, about 0.016% of the period.
Measure the period first, then the high time, at a GPIO assigned to the intended slice. A 50 µs period with the wrong high time points to the compare level or polarity.
Can the other channel on the same slice run at 25 kHz?
It inherits the 20 kHz period in this configuration. Choose a different slice for an independent period or coordinate the channels around one frequency.
Read the example one step at a time

- Counter period · TOP = 6,249 · 50 µs
- Half duty · Compare = 3,125 · 25 µs high
- One duty step · 1 / 125 MHz · 8 ns
Review measurement lead placement · Look for missed trigger edges
Separate throughput from transaction latency.
Raspberry Pi RP2040 Datasheet, 4.5 PWM.
Photograph credit and licence
Phiarc, Raspberry Pi Pico top (Wikimedia Commons), CC BY-SA 4.0. WebP adaptation.
Original photograph https://commons.wikimedia.org/wiki/File:Raspberry_Pi_Pico_top.jpg
Licence https://creativecommons.org/licenses/by-sa/4.0/
Back to Tutorials