Skip to content

meta(rp2040): RX-first channel-driver bring-up — PIO capture, UART/PIO/SPI TX, and SPI LEDs #3647

Closed
1 of 1 issue completed

Description

@zackees

Context

Parent hardware bring-up: #3626
Expands the previously broad pin/LED follow-up: #3631

The attached Pico 1 now has usable loopback wiring, so the next bring-up must cover the complete receive/transmit path for LED drivers. RX is the critical first dependency: establish a trustworthy, datasheet-conformant receive oracle before accepting UART, PIO, or SPI TX behavior.

This work must use the modern channel APIs and the repository's mock-peripheral pattern:

  • RX: RxChannel -> RxDevice (the existing receive-side channel contract).
  • TX: IChannelDriver with enqueue() -> show() -> poll().
  • Hardware operations behind injectable virtual peripheral interfaces.
  • Singleton mocks backed by fl::Singleton<...> and test-local shared_ptr wrappers which delegate to Mock::instance().
  • Host unit tests before attached-board acceptance.
  • Board builds, deploys, serial transport, and JSON-RPC through fbuild only. Do not use PlatformIO, direct flash tools, or raw pyserial.

Datasheet findings

The local FastLED/datasheets material was reviewed for RP2040, WS2812/WS2812B, APA102/APA102C, and SK9822.

RP2040 provides:

  • 12 DMA channels.
  • Distinct DREQs for every PIO state-machine TX/RX FIFO, UART0/1 TX/RX, and SPI0/1 TX/RX.
  • Two PIO blocks, four state machines per block, and 32 shared instructions per block.
  • Per-SM 4-word TX/RX FIFOs, joinable as an 8-word FIFO in one direction.
  • Two PL011 UARTs with 32-byte TX FIFOs and DMA.
  • Two PL022 SPI controllers with 8-entry TX/RX FIFOs and DMA.

The WS2812-family RX oracle must cover at least:

  • WS2812: zero = 350 ns HIGH + 800 ns LOW; one = 700 ns HIGH + 600 ns LOW; reset LOW >= 50 us.
  • WS2812B: zero = 400 ns HIGH + 850 ns LOW; one = 800 ns HIGH + 450 ns LOW; reset LOW >= 50 us.

A concrete existing conformance defect was found: the SK9822 Rev. 01 datasheet specifies a 32-bit all-ones end frame, while src/fl/chipsets/encoders/sk9822.h and tests/fl/chipsets/encoders/sk9822.hpp currently encode and assert an all-zero end frame. This must be corrected before SPI LED closeout.

Existing implementation gaps

  1. RxBackend and RxDeviceType have no PIO backend, so RP2040 PLATFORM_DEFAULT falls through to a dummy receiver and AutoResearch reports RxChannelCreationFailed.
  2. The existing reusable UART waveform encoder is ESP-scoped. The channel driver does not implement the required isInUse lifecycle, and its factory currently returns null.
  3. RP initialization registers SpiHw2/4/8, but SpiChannelEngineAdapter rejects every controller with more than one lane (Multi-lane init not yet implemented). The registered RP SPI path cannot initialize its own controllers.
  4. At least the dual-PIO SPI implementation allocates an internal mDMABuffer but returns a separately constructed DMABuffer, does not remove its uploaded PIO program during cleanup, and treats DMA completion as transfer completion without proving the final word left the PIO pin.
  5. RX, clockless PIO TX, and PIO-based parallel SPI have no common resource owner for PIO instruction memory, state machines, DMA channels, and pins.

Architecture

Do not force RX through IChannelDriver; that interface is transmit-only. Add these platform bindings:

Function FastLED API RP2040 resource
Edge capture RX RxBackend::PIO, RxDeviceType::PIO PIO SM + RX FIFO + DMA
Clockless UART TX Bus::UART, 0/1 UART0/UART1 + TX DMA
Clockless PIO TX Bus::FLEX_IO, 0/1 PIO0/PIO1 + TX DMA
True SPI LEDs Bus::SPI, 0/1 SPI0/SPI1 + TX/RX-drain DMA

Bus::FLEX_IO, 0/1 names the two physical PIO engines; state machines remain internal workers. PIO RX and TX must share one RP resource allocator.

Add platform seams along these lines:

  • IRpPioPeripheral / RpPioPeripheralMock::instance()
  • IRpUartPeripheral / RpUartPeripheralMock::instance()
  • IRpSpiPeripheral / RpSpiPeripheralMock::instance()
  • Shared RP DMA/PIO resource-pool implementation and mock

Production code must use Pico SDK headers and APIs (hardware/pio.h, hardware/dma.h, hardware/uart.h, hardware/spi.h) instead of hand-written register maps.

Phased implementation

Each phase must become a sub-issue before implementation. Do not close this meta until every phase and attached-board gate is complete.

Phase 0 - Resource contracts and mock peripherals

  • Implement shared PIO/DMA ownership covering two PIOs x four SMs, 32 shared instructions per PIO, and 12 DMA channels.
  • Add singleton PIO/UART/SPI peripheral mocks with configuration history, deterministic completion, and failure injection.
  • Verify cleanup after success, partial initialization, exhaustion, timeout, and abort.
  • Use fl::atomic or critical sections for IRQ/shared state; RP2040 is dual-core.
  • Add host tests for every resource/DREQ mapping used by later phases.

Phase 1 - PIO RX instantiation

  • Add PIO to RxBackend and RxDeviceType.
  • Dispatch RP2040 PLATFORM_DEFAULT to RpPioRxDevice.
  • Implement begin, finished, wait, decode, getRawEdgeTimes, and injectEdges.
  • Validate GPIO, buffer, timing range, and backend configuration.
  • Make wait() yield through fl::task::run().
  • Expose backend name, PIO index, SM, DMA channel, resolution, and lifecycle state through JSON-RPC diagnostics.

Hardware gate: creation succeeds and JSON-RPC reports a real PIO_RX instance instead of RxChannelCreationFailed; repeated begin/stop/rebegin leaks no resources.

Phase 2 - PIO RX edge detection

Capture duration counts directly rather than oversampling GPIO into a bitmap:

  • Run the PIO program from clk_sys to avoid fractional-divider jitter.
  • Keep the input synchronizer enabled for asynchronous LED signals.
  • Push one 32-bit duration for each completed HIGH/LOW segment.
  • Infer level from start_low plus alternating transitions.
  • Account for instruction-path bias when converting counts to nanoseconds.
  • Implement signal_range_min_ns, signal_range_max_ns, skip_signals, incomplete-tail handling, and truthful empty-capture behavior.
  • Unit-test polarity, asymmetric pulses, glitches, timeout, capacity, overflow, counter wrap, and saturated EdgeTime.

Hardware gate: JSON-RPC validates GPIO/PWM square waves at 1, 10, and 100 kHz with correct level, mean, min, and max durations. The watchdog remains enabled.

Phase 3 - Production PIO RX with DMA

  • Join the RX FIFO to eight words.
  • Configure 32-bit DMA from the fixed PIO RX FIFO to incrementing RAM using pio_get_dreq(pio, sm, false).
  • Bound transfer count by edge_capacity and report overflow distinctly.
  • Keep decoding outside IRQ context.
  • Handle RP2040-E13 correctly when aborting DMA: disable completion IRQ, abort, then clear any spurious completion IRQ.
  • Unit-test the exact DMA configuration and simulated DREQ/FIFO activity.

Hardware gate: sustain WS2812-rate capture (up to 1.6 million HIGH/LOW segments per second), capture long random streams without FIFO loss, and preserve valid partial frames on timeout.

Phase 4 - UART clockless TX and first full RX byte match

  • Move/generalize the existing wave10/wave4 UART encoder into platform-shared code rather than duplicating it.
  • Implement ChannelEngineRpUart and an injectable RP UART peripheral.
  • Bind UART0/UART1 to Bus::UART, 0/1; USB CDC does not consume these hardware UARTs.
  • Validate each selected TX pin belongs to its UART instance.
  • Configure 6- or 8-bit framing according to the selected waveform geometry.
  • Feed the 32-byte UART FIFO through the correct TX DMA DREQ.
  • Treat DMA completion as FIFO-fed only; READY requires UART BUSY to clear.
  • Implement the full two-queue READY/BUSY/DRAINING/ERROR and ChannelData::isInUse lifecycle, including all error paths.
  • Unit-test all 256 byte values, baud quantization, both UART instances, concurrency, failure injection, and driver lifecycle.

Hardware gate: UART TX -> PIO RX byte-matches 00, FF, AA, 55, walking bits, random bytes, and multi-LED WS2812 frames. This is the first acceptance proof for production RX.

Phase 5 - PIO clockless TX

  • Implement ChannelEngineRpPio behind Bus::FLEX_IO, 0/1 using ChipsetTimingConfig, not hard-coded WS2812 constants.
  • Start with single-lane output, then extend to compatible 2/4/8-lane consecutive-pin batches.
  • Allocate programs, SMs, DMA, and pins through the shared owner.
  • Use a PIO terminal marker/IRQ or equivalent proof that the final bit left the pin; DMA completion alone is insufficient.
  • Generate/enforce the chipset reset/latch interval.
  • Batch channels only when their timing is compatible; serialize incompatible timing groups.
  • Implement and test the complete channel-driver queue and isInUse lifecycle.

Hardware gate: PIO TX -> PIO RX exact byte comparison for WS2812, WS2812B, and another representable timing, followed by repeated and concurrent PIO0/PIO1 transfers.

Coordinate the parallel-output portion with #3620; do not create a second incompatible resource manager or parallel PIO architecture.

Phase 6 - Fixed-function SPI0/SPI1 channel driver

  • Implement a true-SPI IChannelDriver over RP2040 SPI0/SPI1, separate from PIO-based parallel SPI.
  • Use spi_init, spi_set_format, and spi_get_dreq with declarative pin groups matching the RP2040 mux table.
  • Use TX DMA plus RX-drain DMA/sink so the PL022 receive FIFO cannot overflow during TX-only LED traffic.
  • Support and test clock selection, mode 0, pin pairing, both SPI instances, timeout, and failure paths.
  • Require DMA completion and spi_is_busy() == false before clearing isInUse.
  • Clamp requested speed to both silicon capability and the selected LED chipset's documented limits.

Hardware gate: SPI0 and SPI1 loopback byte-match at multiple clock rates through JSON-RPC before an LED strip is attached.

Phase 7 - SPI LED protocol conformance and public API

  • Correct SK9822 end framing to the vendor-specified all-ones end frame and replace the currently incorrect golden tests.
  • Audit APA102/APA102C start frame, 111 + 5-bit brightness, BGR order, and end clocks against the datasheets.
  • Preserve extended APA102 end clocks for long chains while guaranteeing the datasheet's minimum 32 ones.
  • Reuse SpiEncoder; the hardware driver transmits already encoded bytes and does not duplicate chipset framing.
  • Golden-test 0, 1, 31, 32, 33, and long LED counts plus brightness boundaries and exact transmitted bytes.
  • Validate through public FastLED.addLeds(...)/show() and explicit Bus::SPI selection, not only raw SPI helpers.

Hardware gate: APA102 and SK9822 tests cover black, RGB primaries, white, brightness sweep, walking pixel, repeat frames, and long-chain end-frame behavior.

Phase 8 - Combined soak and closeout

  • Run RX and each TX engine under repeated transfers with the watchdog enabled.
  • Exercise resource exhaustion and recovery without rebooting.
  • Prove PIO RX alongside UART TX, PIO TX, and SPI TX in supported combinations.
  • Run targeted host tests, full bash test, lint, and RP2040 fbuild compile.
  • Run attached-board acceptance exclusively through bash autoresearch/JSON-RPC and fbuild serial transport.
  • Record board identity, wiring, exact commands, merge SHA, selected resources, decisive JSON-RPC output, and pass/fail measurements.

How every phase must be conducted - lessons from ESP32-WROOM

The classic ESP32/WROOM bring-up evolved through failures that are directly applicable here:

Mandatory sub-issue execution template

Every phase sub-issue must contain and execute these gates.

  1. Entry state and provenance

    • Record issue/PR dependencies, current merge SHA, board/USB identity, exact jumper wiring, pins, and expected resources.
    • Run fbuild port scan, deploy, and invoke unchanged AutoResearch JSON-RPC smoke through fbuild only. PlatformIO, direct flash tools, and raw pyserial are prohibited.
    • Record reset reason, watchdog state, heap/stack high-water data where supported, and the PIO/SM/DMA ledger before testing.
    • If RPC is silent, diagnose discovery/reset/reacquisition, request ingestion, scheduler progress, output truncation, and console-peripheral ownership before debugging LED drivers.
  2. RED host proof before production code

    • Add a focused failing test for the absent behavior or reproduced defect.
    • Reset singleton mock state per test; capture configuration/transaction history; inject failures at allocate, configure, start, poll/wait, timeout, abort, and cleanup.
    • Cover READY/BUSY/DRAINING/ERROR, both queues, ChannelData::isInUse, enqueue-while-busy isolation, repeated frames, partial initialization, destruction, exhaustion, and recovery.
    • Assert actual clock/timing, DREQ, FIFO direction/width, capacity, descriptor chaining, IRQ order, and ownership release. Compilation is not acceptance evidence.
  3. Instrumented fbuild deployment

    • Use the documented bash autoresearch rp2040 .../fbuild command and redeploy current main after every major merge.
    • JSON-RPC must report the concrete backend, begin/configure result, actual clock/timing, pins, PIO/SM/DMA, requested/effective capacity, lifecycle, timeout/overflow state, and resources before/after cleanup.
    • Keep the watchdog enabled. A timeout must return an explicit error and the next RPC must work without replugging.
  4. Physical GPIO baseline

    • Prove the stated TX-to-RX jumper with the AutoResearch GPIO RPC using both levels and repeated transitions; reverse direction when both pins permit it.
    • Repeat on every board, wiring, or pin change. If this fails, stop: zero captured edges are not peripheral evidence.
  5. Independently qualify the RX oracle

    • Feed RX from a simpler controlled generator and verify begin/armed, completion, nonzero edges, polarity, counts, duration statistics, timeout, capacity, and overflow.
    • Phase 2 uses GPIO/PWM. Later phases use the last known-good TX on the exact same pins/wire/timing immediately before the target.
    • Never use rawEdges == 0 against TX unless RX proved it armed and captured the same-session control. Report distinct capture_not_armed, capture_timeout, zero_edges, timing_mismatch, and decoded_data_mismatch outcomes.
  6. Target hardware proof ladder

    • Run the same-session control, then target, without moving the jumper.
    • Test 00, FF, AA, 55, walking one/zero, and seeded pseudo-random data at 1 byte/LED, 10 LEDs, FIFO/DMA/descriptor boundaries, and long frames.
    • Require start success, nonzero raw evidence, measured datasheet-valid timing with useful symbol separation, exact wire bytes, correct latch/idle, repeated passes, and cleanup. The default 10-LED gate is 4/4 exact passes per pattern/configuration.
    • Driver name, enqueue success, DMA completion, ISR activity, clean wait(), or visible LED color are supporting telemetry only. Prove peripheral and wire idle after DMA completes.
  7. Memory and resource accounting

    • Derive limits from hardware/RAM; report requested/effective sizes and clamp or reject impossible requests. Check every allocation before use.
    • Record heap/stack high-water data around control and target runs; repeated runs must not trend downward.
    • Snapshot resource ownership before begin, while active, and after success/failure/timeout/abort. No leaks or double ownership.
  8. Exit and default-switch discipline

    • Attach exact commands and decisive JSON-RPC evidence, separately reporting host tests, deploy/RPC, GPIO, RX control, target timing/bytes, memory/resources, and soak.
    • Land seams/mocks first and hardware behind explicit selection. Preserve proven paths until the replacement passes the entire wire ladder; do not delete or switch defaults on mock/build/boot/RPC evidence.
    • After milestone merges, redeploy current main with fbuild and repeat. Unresolved evidence gets a linked follow-up rather than a caveat hidden in closeout.

Serial/JSON-RPC print-pipe budget (mandatory in every phase)

Serial output is a finite shared transport resource, not free diagnostics. Excessive fl::print, Serial.print/Serial.println, FL_PRINT, FL_WARN, related logging macros, and verbose JSON-RPC chatter can fill device/USB/host buffers, block writers, starve scheduler/RPC work, and make otherwise-correct operations appear to stall or time out.

  • Keep normal bring-up output minimal and structured. Prefer one compact JSON-RPC result per stage over duplicated human-readable text plus JSON.
  • Never print per edge, byte, sample, polling iteration, DMA event, or tight-loop transition. Accumulate counters/summaries in memory and emit one bounded record after the timing-critical operation.
  • Verbose diagnostics must be opt-in, bounded, batched, and rate-limited. Default runs and acceptance evidence use quiet logging.
  • Every RPC silence, timeout, unexpected latency, watchdog event, truncated response, or apparent peripheral stall must include a print-pipe audit before blaming USB, RPC, scheduler, DMA, PIO, UART, SPI, or the LED driver.
  • The audit must inventory all active fl::print, Serial.print*, FL_PRINT, FL_WARN, AR_FL_WARN, and equivalent call sites on the exercised path, including library code invoked indirectly and device-emitted JSON-RPC progress/events.
  • Run a same-binary quiet control (setDebug(false)/testNoSerial or the narrowest equivalent) and compare it with diagnostic logging enabled. Record output bytes/messages, completion latency, timeout result, and whether RPC remains responsive.
  • Do not raise a timeout or add delays until the quiet control has ruled out print saturation. If quiet mode fixes the failure, reduce/collate/gate output and keep the original timing gate unless hardware evidence independently justifies changing it.
  • Logging performed while a capture/transmit deadline is active must not share the critical path. Snapshot diagnostic state and serialize it after the peripheral is idle whenever possible.

A phase cannot close while success depends on disabling an undocumented flood of logs, increasing timeouts to accommodate chatter, or accepting missing/truncated JSON-RPC responses.

Phase-specific conduct and exit evidence

Phase How to conduct it Exit evidence
0 - contracts/mocks Build one shared ownership ledger first. Match WROOM I2S mock coverage: deterministic completion, failure injection, histories, reuse/reallocation, destructor cleanup, enqueue-during-BUSY, multi-frame cycles, and contention between future RX/UART/PIO/SPI claimants. RED-to-GREEN host tests for every lifecycle/resource edge; zero outstanding claims after success and every failure. No hardware-working claim.
1 - RX instantiation Add backend/factory and diagnostics without claiming decode. Test selection, validation, begin/stop/rebegin, unsupported config, exhaustion, and cleanup. RPC-smoke before and after RX to catch #3452-style regressions. Real PIO_RX identity/capabilities/claims in RPC; repeated construction restores the ledger; GPIO baseline passes.
2 - RX detection Use an independent slow square wave, then 1/10/100 kHz, asymmetric periods, polarity, glitches, missing tail, timeout, wrap/saturation, and capacity. Measure PIO instruction-path bias. Armed/completed status, nonzero edges, correct level order/count, bounded min/mean/max durations; empty/overflow are truthful and distinct.
3 - DMA RX Run non-DMA control immediately before DMA on the same signal. Gate features on actual capability; exercise FIFO pressure, hardware capacity, DREQ/width/counts, abort ordering, spurious IRQ clearing, timeout, and partial frames. Control and DMA decode identically; WS2812-rate plus long seeded streams show no unexplained loss; capacity/overflow are reported; abort/retry needs no replug.
4 - UART TX Qualify PIO RX first; ensure UART is not RPC/log transport. Host-test all 256 bytes and symbol-separation margin after baud quantization. Compare requested/actual baud and wire timing. Same-session control passes; UART has nonzero edges and 4/4 byte-exact pattern/frame results; symbols remain separated; READY follows wire idle; UART0/1 clean up.
5 - PIO TX Keep any proven clockless path until wire-green. Start single-lane; prove timing from ChipsetTimingConfig, terminal/wire-idle marker, reset, program removal, and DMA boundaries. Then add compatible lanes and dual-PIO concurrency with #3620. Control and target pass on same RX/wire; exact bytes/timing for WS2812, WS2812B, and another timing; last-bit/reset measured; no program/SM/DMA leaks.
6 - fixed SPI Separate electrical transport from LED framing. MOSI-to-MISO loopback SPI0/1 across pins, clocks, boundaries, timeout, TX plus RX-drain DMA, and peripheral-busy drain. Exact bytes at every clock/instance; no RX overflow; DMA-done precedes measured wire-idle; stable resources/memory.
7 - SPI LED/API RED-test encoder bytes first, including the SK9822 all-ones end-frame defect. Check APA102/SK9822 framing/brightness/BGR/end clocks at 0/1/31/32/33/long counts. Then use qualified Phase 6 and public FastLED.addLeds(...)/show(). Golden frames and MOSI bytes match; raw transport and public API agree; strip observation is secondary evidence.
8 - soak Start only after isolated control/target pairs are green. Run conflict matrices, RPC bursts during transfer, memory pressure, timeout/abort, watchdog recovery, exhaustion/recovery, long seeded frames, and settle-time variation as taught by #3588. No crash, wedge, leak, declining memory margin, resource conflict, or data/timing mismatch across documented soak count; current-main redeploy and all controls rerun.

Failure-classification decision tree

  • No port/RPC: fbuild discovery/reset/reacquisition, USB identity, provenance, ingestion, scheduler, output truncation, console ownership.
  • RPC works; begin fails: capabilities, pin mux, resource ledger, allocation, requested/effective capacity.
  • RX armed; control has zero edges: GPIO/wire, generator, RX FIFO/DREQ/IRQ; reduce to slow square wave. Target remains unjudged.
  • Control passes; target has zero edges: target mux/start, DMA/FIFO feed, terminal/stop conditions, selected bus instance.
  • Edges but wrong timing: actual clock/divider, sample mapping, PIO bias, quantization, descriptors, latch/idle.
  • Valid timing but wrong bytes: polarity, bit/byte order, lane mapping, framing, truncation/overflow, decode thresholds.
  • Crash/reset/wedge: capture reset/trace and memory/resource high-water data, test allocation failure, reduce buffers to hardware limits, and rerun a control before naming ISR/DMA/driver as root cause.

Acceptance criteria

  • Every phase above is represented by a linked sub-issue with objective host and hardware gates.
  • RP2040 RxChannel defaults to a real PIO receiver and successfully decodes datasheet-conformant WS2812/WS2812B captures.
  • UART, PIO, and fixed-function SPI TX are modern IChannelDriver implementations with correct two-queue and isInUse semantics.
  • All hardware paths use Pico SDK APIs; no hand-written RP2040 register maps are introduced.
  • PIO instruction memory, state machines, DMA channels, and pins have one shared owner with tested cleanup and contention behavior.
  • DMA completion is never mistaken for wire-idle completion on UART, PIO, or SPI.
  • RX and TX mocks are singleton peripheral mocks with failure injection and observable configuration/transaction history.
  • SK9822 framing matches the vendor datasheet rather than the current incorrect all-zero end-frame tests.
  • Public FastLED clockless and SPI LED APIs pass attached-board loopback/LED tests.
  • Hardware deployment and JSON-RPC use fbuild only; no PlatformIO, direct flash-tool, or raw pyserial fallback is added.
  • Normal runs keep l::print, Serial.print*, FL_PRINT, FL_WARN, related macros, and JSON-RPC chatter bounded; every stall/timeout includes a documented quiet-control print-pipe audit before timeout changes.
  • The watchdog remains enabled in hardware tests and deliberate failure/timeout cases recover without wedging the board.

Related issues

Sub-issues

Sub-issues

1 of 1 Issues completed
Loading 1 sub-issues

Activity

  1. zackees commented on Jul 16, 2026

    @zackees
    MemberAuthor

    This original RX-first design tracker is superseded by the consolidated #3648 burn-down. Its implementation phases #3653-#3661 and postmortem phases #3649-#3652 are closed with merged PRs and validation evidence. The remaining source-audit findings were resolved as follows:

    Closing this historical tracker keeps #3648 as the single authoritative meta issue.

  2. moved this from Triage to Done in FastLED Trackeron Jul 16, 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