Skip to content

Hoist solveI2sClockDivider() to shared location; apply to other drivers #3562

Closed

Description

@zackees

Context

Follow-up from #3526 Phase 2e. The modern I2S engine's peripheral impl (src/platforms/esp/32/drivers/i2s/i2s_peripheral_esp32dev_esp.cpp.hpp) now contains a solveI2sClockDivider(target_hz, &N, &A, &B) helper — adapted from Yves's i2s_define_bit_patterns — that solves the 80 MHz APB / (N + B/A) fractional divider for any target frequency.

The generalisation

The same fractional-divider math applies to other classic-ESP32 peripherals that derive their clock from the APB reference via a clkm_conf.clkm_div_{num,a,b} triple. Candidates:

  • SPI0/1/2/3: spi_dev_t::clock divider (different register layout but same math)
  • RMT4 (classic ESP32): rmt_dev_t::conf1.div_cnt_ch{n} — 8-bit-only divider, but for finer control the fractional path applies
  • I2S0 on classic ESP32 (currently unused by any modern driver but the arithmetic is identical to I2S1)
  • Anything on ESP32-S2/S3 / P4 / C-series — different peripheral families but the pattern generalises

Proposal

Hoist solveI2sClockDivider() to a shared src/platforms/esp/32/ location (e.g., platforms/esp/32/core/clock_divider.h) with a generic signature:

```cpp
namespace fl::platforms::esp32 {
struct ClkDividerNAB { int N; int A; int B; };
ClkDividerNAB solveFractionalDivider(u32 base_hz, u32 target_hz,
u8 max_A = 63, u8 min_N = 2) FL_NO_EXCEPT;
}
```

Then:

  • I2S peripheral consumes it (replace inline impl).
  • SPI peripherals that currently open-code their divider math consume it.
  • Future drivers pick it up "for free".

Acceptance

  • Investigate: audit src/platforms/esp/32/ for callers currently open-coding N/A/B math.
  • If ≥ 2 open-coders found: hoist the helper to shared location.
  • Update I2S impl to consume the shared helper.
  • Update other identified callers.
  • Regression test: verify the hoisted helper produces byte-identical output to Yves's original i2s_define_bit_patterns for the canonical WS2811 / WS2812 / WS2812B timings.

Reference

Current impl: src/platforms/esp/32/drivers/i2s/i2s_peripheral_esp32dev_esp.cpp.hpp — search for solveI2sClockDivider.

Origin: Yves Bazin's i2s_esp32dev.cpp.hpp:pgcd() + i2s_define_bit_patterns() divider search loop (deleted at #3526 Phase 2e; algorithm preserved in the hoisted helper).

Related: #3561 (PARLIO variable-timing — will likely consume the same helper).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions