Skip to content

raspberrypi: round the rp2pio clock divider up when the division is not exact - #11933

Merged
dhalbert merged 1 commit into
adafruit:mainfrom
emincan2000:rp2pio-clkdiv-round-up
Nov 20, 2026
Merged

dhalbert merged 1 commit into
adafruit:mainfrom
emincan2000:rp2pio-clkdiv-round-up

Conversation

@emincan2000

Copy link
Copy Markdown

rp2pio computes the PIO clock divider as div256 = frequency256 / frequency, then rounds it up to keep the actual frequency at or below the requested one, as the frequency docs promise. The rounding check uses frequency256 % div256 > 0. It should check the remainder from the division that produced div256, frequency256 % frequency. If div256 divides frequency256 evenly, the divider stays rounded down even when the original division wasn't exact, so the state machine runs slightly fast. At 125 MHz, requesting 399999 Hz gives 400000 Hz, and 312499 Hz gives 312500 Hz.

This changes the check to frequency256 % frequency in both rp2pio_statemachine_construct() and common_hal_rp2pio_statemachine_set_frequency().

I compiled both versions of the calculation on Linux and tested every frequency from 1908 Hz up to the system clock at 125, 150 and 200 MHz. The old check produced a frequency above the requested one for 1614450, 3451310 and 2583194 of them, respectively. The new check did so for none. The difference was small, a few Hz at most in the cases I looked at. I haven't run it on a board.

…ot exact

The check used frequency256 % div256 instead of the remainder of the
division that produced div256, so some frequencies kept the rounded down
divider and ran faster than requested.

@dhalbert dhalbert left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@dhalbert
dhalbert merged commit 580dc20 into adafruit:main Nov 20, 2026
171 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants