From df34590d3d2f6ea84a7d0a8115807d35595add47 Mon Sep 17 00:00:00 2001 From: EminY <57416756+emincan2000@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:02:12 +0300 Subject: [PATCH] raspberrypi: pick the closer pacing timer fraction in audiopwmio limit_denominator() returned the farther of its two bounds, the opposite of the Python code it is based on. For rates between half and all of system_clock / 65535 that bound has a zero numerator, which stops the DMA pacing timer. Also return the reduced fraction when its denominator equals max_denominator instead of running the loop into a division by zero. --- ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c index 3ab8eb814a1..c86e8fe1ed4 100644 --- a/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +++ b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c @@ -46,7 +46,7 @@ static uint32_t limit_denominator(uint32_t max_denominator, uint32_t num_in, uin uint32_t g = gcd(n, d); d /= g; n /= g; - if (d < max_denominator) { + if (d <= max_denominator) { *den_out = d; return n; } @@ -71,8 +71,11 @@ static uint32_t limit_denominator(uint32_t max_denominator, uint32_t num_in, uin uint32_t bound1_num = p0 + k * p1, bound1_den = q0 + k * q1; uint32_t bound2_num = p1, bound2_den = q1; - if (fabsf((float)bound1_num / bound1_den - (float)num_in / den_in) <= - fabsf((float)bound2_num / bound2_den - (float)num_in / den_in)) { + // Pick the closer bound like Python does, but never a zero numerator because the pacing + // timer would never fire. Rates below den_in / max_denominator get the slowest rate instead. + if (bound2_num != 0 && + fabsf((float)bound2_num / bound2_den - (float)num_in / den_in) <= + fabsf((float)bound1_num / bound1_den - (float)num_in / den_in)) { *den_out = bound2_den; return bound2_num; }