Repository navigation
Description
Summary
BitBangChannelDriver (Bus::BIT_BANG) cannot drive a WS2812 strip. Every bit is
stretched by a constant ~2.3-3.1us because DigitalMultiWrite8::writeByte() costs
far more than the 400ns timing budget it is supposed to hit. Confirmed on two
different architectures with wire captures.
This matters because BIT_BANG is registered at priority 0 as AUTO's last-resort
fallback on ESP32. When the hardware engines are exhausted, AUTO degrades to a
driver that emits undecodable output rather than to a working one.
Evidence
Wire captures via bash autoresearch <board> --bitbang (flag added in #4202),
100 LEDs, WS2812B-V5 timing. Both boards: 300/300 bytes corrupt (100%).
RP2350W (Cortex-M33 @150MHz) — after locally registering Bus::BIT_BANG, see below:
Raw sample: H3450 L8450 H3450 L8400 H7050 L4850 H7050 L4800 ...
Capture status: RX produced no decodable bytes
ESP32-C6 (RISC-V @160MHz) — registers BIT_BANG today:
TEST BIT_BANG lanes=1 leds=100 FAIL 4843ms class=decode_mismatch
Raw sample: H2650 L6500 H5375 L3725 H5375 L3750 ...
The encoding is well-formed — a clean 1:2 ratio between "0" and "1" high times —
just far too slow. Nominal WS2812 is T0H400ns, T1H800ns, period ~1250ns.
Root cause
Not the delay math. A constant-overhead-per-writeByte() model fits both boards:
| board | implied C per writeByte | T1H predicted | T1H measured | error |
|---|---|---|---|---|
| RP2350W | 3050ns | 6900ns | 7050ns | -2.1% |
| ESP32-C6 | 2250ns | 5300ns | 5375ns | -1.4% |
Predicted bit period is off by an identical -12.6% on both boards, i.e. one further
constant per-bit cost in the byte/bit loop. Two unrelated architectures showing the
same structure points squarely at shared code:
src/fl/system/pins.cpp.hpp — applyNibble() is a per-pin loop of out-of-line calls:
void DigitalMultiWrite8::applyNibble(const PinList &set, const PinList &clr) {
for (u8 i = 0; i < set.count; ++i) fl::digitalWrite(set.pins[i], PinValue::High);
for (u8 i = 0; i < clr.count; ++i) fl::digitalWrite(clr.pins[i], PinValue::Low);
}writeByte() calls it twice (low nibble, high nibble), and transmitClocklessBit()
calls writeByte() three times per bit — so up to 6 applyNibble invocations and
many individual digitalWrite() calls per bit, against a 400ns budget.
Note DigitalMultiWrite8::allSamePort() already exists in the header but nothing
calls it. That looks like the intended port-masked fast path, never wired up.
Suggested fix
Give applyNibble a same-port fast path: precompute per-nibble 32-bit set/clear masks
and issue one masked port write (on RP, sio_hw->gpio_set / gpio_clr; ESP32 has the
equivalent w1ts/w1tc registers), falling back to the current per-pin loop only for
pins spanning multiple ports. allSamePort() is presumably there for exactly this.
Bit-bang also needs interrupts disabled around the bit loop to hold timing; worth
confirming separately once the write path is fast enough to matter.
Second, smaller bug found alongside
src/platforms/arm/rp/rp2040/delay.h hardcodes the CPU clock:
constexpr u32 hz = 125000000UL; // "RP2040 clock is fixed at 125 MHz"RP2350 selects this same header (arduino-pico defines ARDUINO_ARCH_RP2040 for both)
but runs at 150MHz, so every fl::delayNanoseconds() on RP2350 is ~20% short. Dwarfed
by the issue above, but it affects any RP2350 nanosecond-delay path, not just bit-bang.
Related
RP2040/RP2350 does not register Bus::BIT_BANG at all (initChannelDrivers() in
init_channel_driver_rp.cpp.hpp registers PIO/SPI/UART only), so RP's AUTO chain has
no software fallback -- relevant to #1471, where TinyUSB holds every PIO state machine.
I have a one-line patch that registers it and verified it slots correctly at priority 0,
but I am deliberately not proposing it until this bug is fixed: it would turn the
loud "no free PIO state machine" warning (#4163) into silently wrong LED output.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
zackees commentedon Sep 7, 2026
Correcting my own root-cause attribution above. The measurements stand; the explanation I attached to them does not.
I blamed
applyNibble's per-pinfl::digitalWrite()loop. That doesn't hold up: on both RP paths (pin_rp.hppandpin_rp_native.hpp)fl::digitalWritebottoms out ingpio_put()— two register writes. Even with an out-of-line call per pin, that is tens of nanoseconds, not the ~2.3-3.1us the arithmetic requires. I asserted it without checking what the call actually compiled to.What still stands: the constant-cost-per-bit structure. The model predicts measured T1H within 1-2% on both boards, with an identical -12.6% residual on period across two unrelated architectures. Something fixed-cost runs a small number of times per bit. That part is solid and is what makes the driver unusable.
Better candidate, not yet verified. The cost may be in the delay call rather than the pin write. Every
fl::delayNanoseconds(ns)runs, per invocation:a 64-bit divide by 1e9 with no hardware 64-bit divide on either Cortex-M33 or RV32, so it lowers to a software routine. On ESP32 the one-argument form additionally queries the clock on every call:
Three delay calls per bit. Both costs are independent of the requested
ns, which is exactly the constant-offset signature the captures show.Caveat against over-reading this: RP measures a larger constant (3050ns) than the C6 (2250ns) despite doing no clock query, so the clock query cannot be the whole story and the two platforms may have different dominant terms.
I am not going to publish a third guess. Next step is to measure it directly on both boards — time N iterations of
delayNanoseconds(400)against N iterations ofwriteByte()— and attribute the cost from data. Will update with numbers.If the delay path is confirmed, the fix is much narrower and cheaper than the port-masked-write refactor I proposed above: hoist the ns->cycles conversion and the clock query out of the per-bit hot loop (compute once per
show()), rather than reworkingDigitalMultiWrite8. TheallSamePort()fast-path observation is still worth doing, but it may not be what is costing the time here.zackees commentedon Sep 7, 2026
Measured it. Root cause is the delay call — both of my earlier guesses were wrong.
Added a
perfProbeBitBangCostRPC to the AutoResearch harness (PR to follow) that times the candidates against a common loop floor instead of reasoning from source. RP2350W, 20000 iterations,ns=400:fl::delayNanoseconds()costs 3.023us to deliver a requested 0.4us — a ~2.97us constant on top, independent of the value asked for.This reconstructs the wire captures. A bit is 3 delays + 3
writeBytes:Both attributions I posted earlier were wrong, and the probe says so directly:
writeByte()is 0.511us. Real, but it is not what makes the driver unusable. My first comment blamed it.esp_clk_cpu_freq()as the better candidate; on RP that path is not even taken, and the hoisted-vs-unhoisted gap here is noise. The C6 measurement will test that hypothesis on the platform that does make the call — but on RP it is settled, and the constant is in the delay itself.The 125MHz bug is confirmed live, not inferred: the probe reports
cpu_hz: 125000000fromFL_CPU_FREQUENCY()on a part clocked at 150MHz.Revised fix direction. The
DigitalMultiWrite8port-masked-write refactor I proposed in the original report is not the fix — it targets 0.45us of a 3.5us problem. The delay path is where the time goes. Worth establishing next, before any patch: whether the ~2.97us is the runtimeu64divide incycles_from_ns_*, or insidebusy_wait_at_least_cycles(). That is one more probe variant (timedelay_cycles_pico(N)directly against the fulldelayNanosecondspath), and I would rather measure it than guess a third time.Either way the shape of the fix is the same: a clockless bit loop must not call a general-purpose
delayNanoseconds()per phase. Convert ns to cycles once pershow()and spin on a cheap cycle counter in the loop.zackees commentedon Sep 7, 2026
ESP32-C6 numbers, completing the cross-platform picture. Same probe, 20000 iterations,
ns=400:Side by side:
delayNanoseconds(400)writeByte()Conclusion, now measured on two architectures:
fl::delayNanoseconds()carries ~1.0-3.0us of constant overhead to deliver a requested 0.4us. That is the bug.writeByte()is ~0.5us on both — real, worth fixing eventually, but not what makes the driver unusable.On the clock query specifically: it is measurable on the C6 (0.224us, ~14% of that board's delay cost) and effectively zero on RP (0.016us), which matches RP hardcoding its frequency instead of querying. So the hypothesis in my correction was directionally right for ESP32 and wrong as an explanation — even with the query hoisted out, the C6 still pays 1.379us to deliver 0.4us. Removing the query alone would not fix this.
What remains unmeasured: whether the residual (~2.97us RP / ~0.98us C6, after hoisting the clock) is the runtime
u64divide incycles_from_ns_*or thebusy_wait_at_least_cycles/delay_cycles_mcycleimplementations. One more probe variant settles it. I am not going to assert which without measuring, given the two wrong calls already in this thread.The fix direction does not depend on that answer: a clockless bit loop must not call a general-purpose
delayNanoseconds()three times per bit. Convert ns to cycles once pershow()and spin on a cheap counter inside the loop. I withdraw theDigitalMultiWrite8port-masked-write refactor as the fix — it addresses ~0.5us of a ~3.5us problem — though it is still a reasonable follow-up once the delay path is sorted.Probe available in #4204 so anyone can reproduce these numbers on their own board.
zackees commentedon Sep 7, 2026
Root cause pinned: the runtime
u64divide incycles_from_ns_*().Extended the probe with a compile-time-
NSvariant.delayNanoseconds<400>()foldscycles_from_ns_pico()to a constant, so the runtime divide disappears while the platform busy-wait still runs — the two are separable. RP2350W, 20000 iterations:2.533us of the 3.020us — 84% — is the runtime ns->cycles conversion. Same call, same busy-wait, same requested 400ns; the only difference is whether this line runs at runtime or folds at compile time:
A 64-bit divide by 1e9, and neither Cortex-M33 nor RV32 has a hardware 64-bit divide, so it lowers to a software routine.
delayNanoseconds()is called three times per clockless bit, so a bit pays ~7.6us of pure division.With the conversion folded, the delay call costs 0.469us to deliver 400ns — essentially correct.
Scope beyond bit-bang. This is not a BIT_BANG bug. Any code calling
fl::delayNanoseconds(ns)with a runtime value pays this, on every platform whosecycles_from_ns_*has the same shape (checked:arm/rp/rp2040/delay.handesp/32/core/delay_riscv.hare identical in this respect).Fix. Two independent changes, both narrow:
cycles_from_ns_*()avoid the 64-bit divide.ns * (hz / 1000000) / 1000inu32gives exact results for MHz-integral clocks (400 * 150 / 1000 = 60 cycles) and lets the compiler turn/1000into a multiply-shift. Fixes every runtime caller at once.show()instead of three times per bit. Correct regardless of (1), and the right shape for a hot loop.I will put up (1) with before/after probe numbers and a bit-bang wire capture, since the capture is the end-to-end check that matters: if the driver decodes after the change, the chain from
ns_conversion_usto 100% byte corruption is closed.Retracting once more, for the record: the
DigitalMultiWrite8port-masked-write refactor from my original report is not the fix.writeByte()is 0.514us of a ~3.5us bit. Still a reasonable follow-up, but it was never the cause.Probe is in #4204 if anyone wants to reproduce these on another board.
perf(delay): drop the 64-bit divide from delayNanoseconds (#4203)
zackees commentedon Sep 7, 2026
Fix for the dominant term is up in #4204, measured before/after on hardware.
Replaced the per-call 64-bit divide in
cycles_from_ns_*()with 32-bit arithmetic. RP2350W, 20000 iterations,ns=400, loop floor 0.059us:delayNanoseconds(400)delayNanoseconds<400>()(control)writeByte()(control)The two controls not moving is the part that matters: the compile-time delay path and the pin-write path were untouched, so the improvement is attributable to the conversion and not to some incidental build difference.
This does not close the issue. A WS2812 bit still costs ~4.4us against a 1.25us budget — roughly 3.5x too slow — so BIT_BANG will still not decode. I am not going to claim otherwise on the strength of a microbenchmark; the wire capture is the test that counts and I have not run it post-fix yet.
What has changed is the balance. Remaining per-bit overhead is 3 x 0.655us of delay against 3 x 0.511us of
writeByte()— sowriteByteis now ~44% of what is left, where it was ~14% before. That makes theDigitalMultiWrite8port-masked-write refactor the necessary second half, after I twice said it was not the fix. It was wrong as a root cause and right as a follow-up; both of those can be true and I got the ordering backwards.Suggested sequencing:
delayNanoseconds()caller on every affected platform, not just bit-bang.DigitalMultiWrite8same-port fast path using the existing unusedallSamePort()— targets the now-comparablewriteBytecost.Also worth separating out:
platforms/arm/rp/rp2040/delay.hstill hardcodeshz = 125000000and RP2350 runs at 150MHz, so every RP2350 nanosecond delay is ~20% short. The probe reports it directly ascpu_hz: 125000000. Independent of this fix and of bit-bang; it wants its own change.Unrelated build-environment bug found while verifying, worth its own issue: the link wrapper emits plain executables without the exec bit on every relink (shared objects are unaffected, umask is a normal 0022). The test driver then fails with
Permission denied (os error 13)on all 383 tests and reportsOk: 0 Fail: 0with no reason, becauseci/meson/test_execution.pyonly echoes lines matching FAILED/ERROR and swallows the traceback. This is the recurring #4168 symptom; it is not stale state from any particular merge.zackees commentedon Sep 7, 2026
Post-fix wire capture: still 100% corruption. Ran it rather than inferring from the microbenchmark, and it changes the conclusion.
ESP32-C6,
bash autoresearch esp32c6 --bitbang, 100 LEDs, with #4204 applied:The improvement is real and the right size — the period dropped ~1600ns, about 3x the ~550ns saved per phase, matching three delay calls per bit. It is also nowhere near enough: still 6x over budget.
This retracts the plan I posted earlier in this thread. I said the
DigitalMultiWrite8port-masked-write refactor was "the necessary second half" and that the issue could close after it. The arithmetic says otherwise:WS2812 tolerance leaves roughly 150ns of total per-bit overhead. Post-fix overhead is ~6300ns.
writeByte()were entirely freeEven a perfect
writeByteleaves ~12x the budget. EvendelayNanoseconds<400>(), which has no conversion at all, costs 411ns per call — nearly 3x the entire per-bit budget on its own. At 150MHz, 150ns is 22 cycles; a single cross-TU call plus loop setup already exceeds that.So the remaining problem is not two more hot functions — it is the shape of the inner loop.
BitBangChannelDriver::transmitClocklessBit()makes six out-of-line calls per bit (3 xwriteByte, 3 xdelayNanoseconds) with runtime timing values. No amount of optimizing those callees gets under 22 cycles per phase. Meeting clockless timing requires whatClocklessBlockingGenericalready does: compile-time timing constants so the conversion folds, inlined pin writes with no cross-TU call, and interrupts disabled across the bit.Revised view of this issue:
fl::delayNanoseconds()caller on six platforms, not just bit-bang. Worth merging regardless of what happens here.DigitalMultiWrite8fast path is worth doing but will not make BIT_BANG usable. I was wrong to frame it as the closing step.Bus::BIT_BANGis registered on ESP32 at priority 0 as AUTO's last-resort fallback and cannot drive a WS2812 strip. That is the user-facing problem worth deciding on: either fix the loop, or stop advertising it as a clockless fallback. It is also why I am still not proposing the one-line patch that would register it on RP (test(rp2350): complete RP2350(W) loopback driver and subsystem HIL #3899, FastLED and Arduino TinyUSB issues on RP2040 #1471) — that would extend a non-working fallback to another platform.Happy to attempt (3) if a maintainer wants it, but it is a different piece of work from what this issue started as.
fix(autoresearch): make the delay probe's conversion metric always valid
fix(autoresearch): keep an explicit --bitbang when --all is also given
feat(autoresearch): add --bitbang driver flag (#4202)
perf(delay): drop the 64-bit divide from delayNanoseconds, with the p…
zackees commentedon Sep 10, 2026
any expensive clock related calculations should be done once before entering into repeated inner loops
zackees commentedon Sep 10, 2026
Hoisted the clock query out of the bit loop — #4262
Acting on your note. The per-call cost was concrete:
delayNanoseconds(ns)re-derives the CPU frequency every call, and on ESP32 that isesp_clk_cpu_freq_impl(), an ESP-IDF call — three per bit.fl::cpuFrequencyHz()is the accessor for the hoisted form; the driver fetches it once per transmission and usesdelayNanoseconds(ns, hz)in the loop.It does not close this issue and I am not claiming it does. Your arithmetic above puts post-#4204 overhead at ~6300ns against a ~150ns budget, with the conclusion that the remaining problem is the inner loop's shape rather than its callees' cost. This removes one callee's fixed cost on ESP32. The wire capture is the test that counts, and it needs the bench.
Guarded structurally rather than by a benchmark, deliberately: the cost is per-platform and the property is not, so a host microbenchmark would measure a machine that does not have the problem. The test pins that the per-bit path never uses the one-argument form, still performs three delays, and fetches the frequency exactly once.
A second instance of the same shape, reported rather than changed
src/platforms/shared/spi_bitbang/generic_software_spi.h:153-154, Teensy 4.x:DELAY_NSderives from theSPI_SPEEDtemplate parameter, so it is a compile-time constant — but these call the runtime form, paying both the ns→cycles conversion and the clock query on every clock edge of an SPI bit-bang loop.The fix is
delayNanoseconds<(DELAY_NS/4)>(), which removes the cost outright rather than amortising it — strictly better than what #4262 does for the clockless path, because there is nothing to hoist when the value is already constant.I have not made that change. It is
FL_IS_TEENSY_4X-gated, I cannot compile that platform here, and I am not pushing an unbuilt one-line edit into timing-critical code. Flagging it so it is not lost.And the RP2350 clock constant is still wrong
Restating from your earlier comment since it is independent and still open:
platforms/arm/rp/rp2040/delay.hhardcodeshz = 125000000while RP2350 runs at 150MHz, so every RP2350 nanosecond delay is ~20% short.fl::cpuFrequencyHz()inherits that on RP — it returnsFL_CPU_FREQUENCY()there — so hoisting does not fix it and does not make it worse.perf(bitbang): fetch the CPU frequency once, not three times per bit (#…
perf(bitbang): fetch the CPU frequency once, not three times per bit (F…