Skip to content

BIT_BANG driver cannot drive WS2812: constant ~2-3us per-writeByte overhead stretches every bit (RP2350W + ESP32-C6) #4203

Closed

Description

@zackees

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.

Activity

  1. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    Correcting my own root-cause attribution above. The measurements stand; the explanation I attached to them does not.

    I blamed applyNibble's per-pin fl::digitalWrite() loop. That doesn't hold up: on both RP paths (pin_rp.hpp and pin_rp_native.hpp) fl::digitalWrite bottoms out in gpio_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:

    return ((u64)ns * (u64)hz + 999999999UL) / 1000000000UL;   // runtime u64 divide

    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:

    u32 hz = esp_clk_cpu_freq_impl();   // -> ::esp_clk_cpu_freq(), an ESP-IDF 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 of writeByte() — 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 reworking DigitalMultiWrite8. The allSamePort() fast-path observation is still worth doing, but it may not be what is costing the time here.

  2. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    Measured it. Root cause is the delay call — both of my earlier guesses were wrong.

    Added a perfProbeBitBangCost RPC 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:

    nop_us_per_iter:         0.058     <- loop floor
    delay_us_per_iter:       3.023     <- delayNanoseconds(400)
    delay_hz_us_per_iter:    3.007     <- same, clock frequency hoisted
    write_byte_us_per_iter:  0.511     <- DigitalMultiWrite8::writeByte()
    clock_query_us:          0.016
    predicted_bit_overhead:  10.257
    cpu_hz:                  125000000
    

    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:

    quantity predicted from probe measured on wire error
    T0H ~3.5us 3.45us +2%
    T1H ~6.6us 7.05us -6%
    period ~11.5us 11.9us -3%

    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.
    • The clock query is 0.016us on this board. My correction floated 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: 125000000 from FL_CPU_FREQUENCY() on a part clocked at 150MHz.

    Revised fix direction. The DigitalMultiWrite8 port-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 runtime u64 divide in cycles_from_ns_*, or inside busy_wait_at_least_cycles(). That is one more probe variant (time delay_cycles_pico(N) directly against the full delayNanoseconds path), 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 per show() and spin on a cheap cycle counter in the loop.

  3. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    ESP32-C6 numbers, completing the cross-platform picture. Same probe, 20000 iterations, ns=400:

    nop_us_per_iter:         0.038
    delay_us_per_iter:       1.603
    delay_hz_us_per_iter:    1.379
    write_byte_us_per_iter:  0.460
    clock_query_us:          0.224
    predicted_bit_overhead:  5.964
    cpu_hz:                  160000000
    

    Side by side:

    RP2350W ESP32-C6
    loop floor 0.058us 0.038us
    delayNanoseconds(400) 3.023us 1.603us
    same, clock hoisted 3.007us 1.379us
    writeByte() 0.511us 0.460us
    clock query 0.016us 0.224us

    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 u64 divide in cycles_from_ns_* or the busy_wait_at_least_cycles / delay_cycles_mcycle implementations. 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 per show() and spin on a cheap counter inside the loop. I withdraw the DigitalMultiWrite8 port-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.

  4. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    Root cause pinned: the runtime u64 divide in cycles_from_ns_*().

    Extended the probe with a compile-time-NS variant. delayNanoseconds<400>() folds cycles_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:

    delay_us_per_iter:        3.020    <- fl::delayNanoseconds(400)      runtime ns
    delay_hz_us_per_iter:     3.002    <- same, clock frequency hoisted
    delay_ct_us_per_iter:     0.469    <- fl::delayNanoseconds<400>()    compile-time NS
    delay_cycles_us_per_iter: 0.697    <- delaycycles<50>() + delaycycles<10>()
    write_byte_us_per_iter:   0.514
    ns_conversion_us:         2.533
    nop_us_per_iter:          0.059
    

    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:

    return ((u64)ns * (u64)hz + 999999999UL) / 1000000000UL;

    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 whose cycles_from_ns_* has the same shape (checked: arm/rp/rp2040/delay.h and esp/32/core/delay_riscv.h are identical in this respect).

    Fix. Two independent changes, both narrow:

    1. Make cycles_from_ns_*() avoid the 64-bit divide. ns * (hz / 1000000) / 1000 in u32 gives exact results for MHz-integral clocks (400 * 150 / 1000 = 60 cycles) and lets the compiler turn /1000 into a multiply-shift. Fixes every runtime caller at once.
    2. Have the clockless bit loop convert once per 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_us to 100% byte corruption is closed.

    Retracting once more, for the record: the DigitalMultiWrite8 port-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.

  5. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    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:

    before after
    delayNanoseconds(400) 3.020us 0.655us
    ns conversion 2.533us 0.293us
    predicted per-bit overhead 10.247us 3.146us
    delayNanoseconds<400>() (control) 0.469us 0.469us
    writeByte() (control) 0.511us 0.511us

    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() — so writeByte is now ~44% of what is left, where it was ~14% before. That makes the DigitalMultiWrite8 port-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:

    1. perf(delay): drop the 64-bit divide from delayNanoseconds, with the probe that found it (#4203) #4204 (this) — removes the dominant term, benefits every runtime delayNanoseconds() caller on every affected platform, not just bit-bang.
    2. DigitalMultiWrite8 same-port fast path using the existing unused allSamePort() — targets the now-comparable writeByte cost.
    3. Re-capture on both boards. Close this only if it decodes.

    Also worth separating out: platforms/arm/rp/rp2040/delay.h still hardcodes hz = 125000000 and RP2350 runs at 150MHz, so every RP2350 nanosecond delay is ~20% short. The probe reports it directly as cpu_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 reports Ok: 0 Fail: 0 with no reason, because ci/meson/test_execution.py only echoes lines matching FAILED/ERROR and swallows the traceback. This is the recurring #4168 symptom; it is not stale state from any particular merge.

  6. zackees commented on Sep 7, 2026

    @zackees
    MemberAuthor

    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:

    TEST BIT_BANG lanes=1 leds=100 FAIL 4733ms class=decode_mismatch
    Raw sample: H2100 L5450 H2125 L5450 H4325 L3225 H4325 L3200 ...
    Byte corruption: 300/300 bytes (100.0%)
    
    before after WS2812
    T0H 2650ns 2100ns 400ns
    T1H 5375ns 4325ns 800ns
    bit period ~9150ns ~7550ns 1250ns

    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 DigitalMultiWrite8 port-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.

    scenario per-bit overhead
    now, post-#4204 ~6300ns
    if writeByte() were entirely free ~1790ns
    if every delay used the compile-time form ~1230ns + writeByte
    budget ~150ns

    Even a perfect writeByte leaves ~12x the budget. Even delayNanoseconds<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 x writeByte, 3 x delayNanoseconds) with runtime timing values. No amount of optimizing those callees gets under 22 cycles per phase. Meeting clockless timing requires what ClocklessBlockingGeneric already 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:

    1. perf(delay): drop the 64-bit divide from delayNanoseconds, with the probe that found it (#4203) #4204 stands on its own merits — it fixes a genuine ~2.5us-per-call bug affecting every runtime fl::delayNanoseconds() caller on six platforms, not just bit-bang. Worth merging regardless of what happens here.
    2. The DigitalMultiWrite8 fast path is worth doing but will not make BIT_BANG usable. I was wrong to frame it as the closing step.
    3. Making BIT_BANG actually drive WS2812 is a rewrite of its bit loop, not a set of optimizations. That is a design decision for a maintainer, not something I should pick unilaterally.
    4. Until then, Bus::BIT_BANG is 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.

  7. zackees commented on Sep 10, 2026

    @zackees
    MemberAuthor

    any expensive clock related calculations should be done once before entering into repeated inner loops

  8. zackees commented on Sep 10, 2026

    @zackees
    MemberAuthor

    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 is esp_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 uses delayNanoseconds(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:

    #define DELAY_NS (1000 / (SPI_SPEED/1000000))
    #define CLOCK_HI_DELAY do { delayNanoseconds((DELAY_NS/4)); } while(0);
    #define CLOCK_LO_DELAY do { delayNanoseconds((DELAY_NS/4)); } while(0);

    DELAY_NS derives from the SPI_SPEED template 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.h hardcodes hz = 125000000 while RP2350 runs at 150MHz, so every RP2350 nanosecond delay is ~20% short. fl::cpuFrequencyHz() inherits that on RP — it returns FL_CPU_FREQUENCY() there — so hoisting does not fix it and does not make it worse.

  9. moved this from Triage to Done in FastLED Trackeron Sep 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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