Skip to content

feat(teensy4/spi): massive parallel SPI driver via FlexIO and/or ObjectFLED (APA102 / SK9822 / HD108 / WS2801) #3428

Closed

Description

@zackees

Channel-driver Capabilities contract (must include in implementation)

Both new engines (ChannelEngineFlexIOSPI for Path A, ChannelEngineObjectFLEDSPI for Path B) must return supportsSpi = true from their getCapabilities() override so the channel manager's dispatch + affinity layer treats them as SPI-capable drivers.

The IChannelDriver::Capabilities struct (see src/fl/channels/driver.h:154-164) already carries the two flags this needs:

struct Capabilities {
    bool supportsClockless;
    bool supportsSpi;
};

Existing reference for both Teensy 4.x engines today:

// src/platforms/arm/teensy/teensy4_common/drivers/flexio/channel_engine_flexio.h:72-73
Capabilities getCapabilities() const FL_NO_EXCEPT override {
    return Capabilities(true, false);   // clockless ONLY
}

For the parallel-SPI variants in this meta, the override should be:

// New ChannelEngineFlexIOSPI / ChannelEngineObjectFLEDSPI
Capabilities getCapabilities() const FL_NO_EXCEPT override {
    return Capabilities(false, true);   // SPI ONLY -- separate from the
                                         // clockless WS2812 path that
                                         // shares the FlexIO/ObjectFLED
                                         // peripheral. Channel manager
                                         // dispatches by capability +
                                         // pin compatibility.
}

If the implementer chooses to unify clockless and SPI into a single engine (one ChannelEngineFlexIO that does both WS2812 and APA102), the return must be Capabilities(true, true) and canHandle() must inspect the channel's chipset to route between the clockless and SPI internal paths. The two-engine option (above) is simpler and recommended because the DMA shifter/timer configuration differs significantly between clockless wave8 and clocked SPI.

Acceptance criterion (gates every PR in this meta):

  • getCapabilities() of the new engine returns Capabilities(_, true) so the channel manager routes SPI-clocked chipsets (APA102, SK9822, HD108, WS2801, LPD8806, APA101) to it.
  • canHandle() accepts fl::ChannelData::isSpi() true and rejects clockless requests if the engine is SPI-only (or accepts both and routes internally if unified).
  • getDriverCapabilities() (the richer Phase-2 capability descriptor, also in driver.h) synthesizes correctly from the Capabilities legacy struct.
  • Host unit test in tests/fl/channels/ asserts the new engine's Capabilities::supportsSpi == true.
  • bash autoresearch teensy40 --lcd-spi --driver FLEX_IO_SPI (Path A) / --driver OBJECT_FLED_SPI (Path B) successfully resolves to the new engine via the channel manager's dispatch.

Default-dispatch policy: single-strip SPI should prefer FlexIO/ObjectFLED, NOT LPSPI

Update to the head-to-head comparison's "best use case" row below — even for a single strip, the channel manager should NOT default to native LPSPI when a FlexIO-SPI or ObjectFLED-SPI engine is available on a free pad. Rationale:

  • LPSPI peripherals on Teensy 4.x (LPSPI1-4) are commonly claimed by other libraries: SD card readers, OLED/TFT displays, IMUs, SPI flash, audio codecs, ICM-20948-style sensors. The user's sketch may need LPSPI for those non-LED peripherals.
  • FlexIO2 and the GPIO6_DR fast-bank pins used by ObjectFLED are far less likely to be allocated by non-LED code — they're niche peripherals that exist specifically for high-bandwidth IO.
  • Defaulting to LPSPI silently steals a scarce resource. Defaulting to FlexIO-SPI leaves the LPSPI block free for the user to use elsewhere.

Dispatch priority for SPI-clocked chipsets (high → low):

  1. Bus::FLEX_IO_SPI (this meta, Path A) — preferred default. Uses FlexIO2 shifters + 1 timer; doesn't compete with general-purpose peripherals.
  2. Bus::OBJECT_FLED_SPI (this meta, Path B) — preferred when ≥8 lanes needed; uses GPIO6 fast bank + DMA, also doesn't compete with LPSPI.
  3. Bus::LCD_SPI (already shipped, uses LCDIF/I80 bus on T4) — third choice.
  4. Bus::SPI (native LPSPI) — fallback only, when none of the above can claim the requested pad. Explicit user opt-in via Bus::SPI selector keeps working for sketches that want the LPSPI block (e.g. when sharing it with other devices is desired).

This priority must be reflected in:

  • The Bus enum priority table at src/fl/channels/bus_priorities.h — default_bus_priority(Bus::FLEX_IO_SPI) > default_bus_priority(Bus::SPI).
  • The channel manager's selectDriverForChannel() (src/fl/channels/manager.cpp.hpp:~258) — when an SPI-capable channel is enqueued with Bus::AUTO, it picks the highest-priority registered SPI engine that can claim the requested pad.
  • The autoresearch --lcd-spi flag should be the canonical default for SPI chipsets on Teensy 4.x rigs; --spi (native LPSPI) becomes the explicit-opt-in path.

Explicit selectability is a first-class requirement, separate from AUTO dispatch. Every SPI engine in the stack MUST be explicitly selectable so a sketch can pin its choice:

Selector Engine Use case
Bus::SPI Native LPSPI When the sketch wants the LPSPI block (e.g. sharing it with non-LED devices) and accepts the single-strip limit
Bus::LCD_SPI LCDIF/I80 bus on Teensy 4 (already shipped) When the sketch wants the LCDIF for its specific timing/burst behavior
Bus::FLEX_IO_SPI This meta, Path A Explicit single- or multi-strip FlexIO routing; preferred default for AUTO
Bus::OBJECT_FLED_SPI This meta, Path B Explicit large-fan-out parallel SPI via GPIO6 bank

Bus::AUTO dispatch order (high → low): FLEX_IO_SPI > OBJECT_FLED_SPI > LCD_SPI > SPI. But every entry above is independently selectable by name — none of them are AUTO-only.

Additional acceptance criteria:

  • Explicit selection works for each engine separately. A sketch using FastLED.add({.bus = Bus::FLEX_IO_SPI, ...}) (or the equivalent template form) binds that engine even when other SPI engines are registered. Same for Bus::OBJECT_FLED_SPI, Bus::LCD_SPI, Bus::SPI. Verified by 4 separate host-side unit tests in tests/fl/channels/, one per selector, each asserting the resolved driver name matches the requested bus.
  • AUTO picks FlexIO-SPI first on Teensy 4.x when both FLEX_IO_SPI and SPI engines are registered. Verify via a dispatch test that requests Bus::AUTO + APA102 chipset, asserts the resolved driver is the FlexIO-SPI engine.
  • Existing addLeds<APA102, DATA_PIN, CLOCK_PIN, ...> legacy template path still routes to Bus::SPI because it pre-binds the driver at construction time — no auto-dispatch change (preserves backwards compatibility).
  • Each engine's getName() returns a distinct string ("FLEX_IO_SPI", "OBJECT_FLED_SPI") so ChannelManager::setExclusiveDriverByName() and the autoresearch RPC runSingleTest({driver: "FLEX_IO_SPI"}) path can target them.

Meta scope

Two architectural paths to provide a "massive parallel SPI" driver for Teensy 4.x clocked-LED chipsets (APA102, SK9822, HD108, WS2801, LPD8806, APA101). Both are feasible; pick whichever wins the throughput-per-lane-per-pin tradeoff for the user's setup.

Supersedes / merges the deferred closed scope from #3175 (FlexIO parallel SPI) and #3176 (ObjectFLED SPI). Re-files as a single meta so the FlexIO and ObjectFLED variants can be designed against each other and the user can pick by metric.


Path A — FlexIO parallel SPI

Architecture: 1 FlexIO timer drives a common SCLK pad; each of up to 7 FlexIO shifters drives its own MOSI pad and pulls from its own DMA channel + RAM buffer. All shifters tick on the timer's compare event, so SCLK is shared but data lanes are independent.

Speed bounds (Teensy 4.x, FlexIO2 @ 90 MHz peripheral clock)

Bound Per-lane SCLK Aggregate (7 lanes)
Theoretical max (FlexIO_clk / 2) 45 MHz 315 Mbps
Practical max with HD108 (chipset spec) 50 MHz (overclocked FlexIO ok per data sheet) 350 Mbps
Practical max with APA102/SK9822 (chipset spec) 25 MHz 175 Mbps
Min useful (WS2801) 1 MHz 7 Mbps
Min functional (timer divider range) < 1 kHz trivially low

HD108 chips are rated up to 50 MHz; FlexIO can match this. APA102 nominal is 25-30 MHz; some lots tolerate more with good wiring.

LEDs/sec achievable (APA102 = 32 bits/LED)

Config LEDs/sec
FlexIO 7-lane @ 25 MHz 5.47 M LEDs/sec
FlexIO 7-lane @ 50 MHz (HD108) 10.94 M LEDs/sec
FlexIO 1-lane @ 25 MHz (for comparison) 781 K LEDs/sec
Native LPSPI 1-lane @ 30 MHz (current FastLED baseline) 937 K LEDs/sec

Speedup vs native LPSPI: ~5.8x at the conservative APA102-25 MHz config; ~11.7x at HD108-50 MHz.

Pin allocation (Teensy 4.x)

Uses the existing FlexIO2 pin table from src/platforms/arm/teensy/teensy4_common/drivers/flexio/flexio_driver.cpp.hpp:

  • Available FlexIO2 pins: {6, 7, 8, 9, 10, 11, 12, 13, 32} (9 pins)
  • 1 reserved for SCLK, up to 8 for data lanes (but only 7 shifters usable on FlexIO2, so 7 lanes max)

Implementation cost

  • New file src/platforms/arm/teensy/teensy4_common/drivers/flexio_spi/flexio_spi_driver.cpp.hpp (~150 LOC)
  • New ChannelEngineFlexIOSPI mirroring ChannelEngineFlexIO (~80 LOC)
  • New Bus::FLEX_IO_SPI + bus_traits + registration (~20 LOC)
  • Pixel-data transpose (strip-major to lane-major) — can reuse fl::simd DSP-ext widen/narrow ops landed in PR feat(simd/arm-dsp): wire scale/blend/mullo DSP ops (closes #3425 yellow) #3427
  • Estimate: ~300 LOC, 1-2 days focused work

Per-op verification checklist

  • Stage 1: single-lane FlexIO SPI — bring up 1 strip via 1 FlexIO shifter + 1 timer. Verify SCLK and MOSI on scope/FlexPWM RX. Compare against native LPSPI output byte-for-byte on a small APA102 strip.
  • Stage 2: 2-lane parallel — add a second shifter sharing the same timer. Independent pixel buffers per lane. Verify both lanes light correct colors.
  • Stage 3: 7-lane parallel — scale up to maximum lane count. DMA contention benchmark.
  • Stage 4: AutoResearch wiring — bash autoresearch teensy40 --flex-io-spi --tx-pin 6 --rx-pin 22 runs an APA102 frame and captures via existing SPI decoder.
  • Stage 5: Throughput benchmark — measure actual MB/s and us/frame vs LPSPI 7x-sequential and ObjectFLED parallel SPI.

Path B — ObjectFLED-style parallel SPI

Architecture: PIT timer → FlexPWM gate → eDMA writes 32-bit words to GPIO6_DR. Bit 0 of each word toggles SCLK (0,1,0,1,... on consecutive DMA words); bits 1-N drive MOSI lanes in lockstep.

Speed bounds (Teensy 4.x, eDMA-to-GPIO6_DR sustained throughput)

Bound Per-lane SCLK Aggregate (15 lanes)
Theoretical max (eDMA peak burst) ~7.5 MHz 112 Mbps
Practical sustained (per OctoWS2811 / ObjectFLED measurements) 2-4 MHz 30-60 Mbps
Practical min (any chipset) < 1 kHz trivially low

The bottleneck is DMA->GPIO6_DR write bandwidth, not FlexIO peripheral speed. Each SCLK cycle needs 2 GPIO writes (HIGH then LOW), so per-lane SCLK = (DMA write rate) / 2.

LEDs/sec achievable (APA102)

Config LEDs/sec
ObjectFLED 15-lane @ 4 MHz 1.87 M LEDs/sec
ObjectFLED 15-lane @ 2 MHz (conservative) 937 K LEDs/sec
Native LPSPI 1-lane @ 30 MHz 937 K LEDs/sec

Speedup vs native LPSPI: ~1-2x aggregate, but 15x more physical strips.

Pin allocation (Teensy 4.x)

GPIO6_DR (FlexGPIO6) covers the Teensy 4 fast-GPIO bank — pins {0, 1, 6-9, 14-19, 22-27} (~16 pins). 1 reserved for SCLK, 15 for data lanes.

Pin 0/1 conflict with USB Serial (Serial1 on T4.0/4.1). Real usable count: ~13-15 data lanes.

Implementation cost

  • New file src/platforms/arm/teensy/teensy4_common/drivers/objectfled_spi/objectfled_spi_driver.cpp.hpp (~200 LOC)
  • Adapter: the bit-encoding loop differs from WS2812 (SCLK toggles unconditionally; data bits sampled on rising edge instead of variable-pulse-width)
  • Cannot reuse much of vendored ObjectFLED code; this is essentially a new GPIO-bit-banged-via-DMA driver
  • Estimate: ~400-500 LOC, 2-3 days focused work

Per-op verification checklist

  • Stage 1: 1-lane ObjectFLED SPI — single MOSI + SCLK via the 32-bit DMA-GPIO mechanism. Verify timing on scope.
  • Stage 2: 4-lane parallel — 4 data lanes + 1 SCLK on GPIO6 bank pins. Verify independent strip data.
  • Stage 3: 15-lane parallel — maximum lane count test. Measure sustained DMA write rate.
  • Stage 4: AutoResearch wiring — bash autoresearch teensy40 --object-fled-spi --tx-pin 7 --rx-pin 22.
  • Stage 5: Throughput benchmark — compare aggregate Mbps vs native LPSPI and FlexIO parallel SPI.

Head-to-head comparison

Metric FlexIO parallel SPI ObjectFLED parallel SPI Native LPSPI (baseline)
Max lanes 7 15 1
Per-lane SCLK (practical) 25 MHz 2-4 MHz 30 MHz
Aggregate Mbps (practical) 175 Mbps 30-60 Mbps 30 Mbps
LEDs/sec (APA102, practical) 5.47 M 1.87 M 937 K
LEDs/sec (APA102, max-theoretical) 10.94 M 3.51 M 937 K
Pin pressure 8 pins from FlexIO2 set 16 pins from GPIO6 bank 2 pins (any LPSPI-capable)
Driver complexity Medium (~300 LOC) High (~500 LOC) Already shipped
Best use case High-fps, <=7 strips, throughput-bound Massive walls, >=8 strips, lane-count-bound Single moderate-size strip

Recommendation order

  1. Path A first (FlexIO parallel SPI) — clearer architectural fit, ~5-12x throughput vs LPSPI, lower implementation cost, and the FlexIO scaffolding from fix(flexio): pin mux offsets + timing bugs -- TX now alive on Teensy 4.x #3415 + PR feat(simd/arm-dsp): wire scale/blend/mullo DSP ops (closes #3425 yellow) #3427 (DSP-ext SIMD for transpose) is already on master to lean on.
  2. Path B as a follow-up — only worth building if a user appears with a documented use case for >=8 simultaneous APA102 strips. Otherwise the throughput-per-lane disadvantage makes it a wash with LPSPI + FlexIO mixed-driver fan-out.

Risks (both paths)

  • DMA contention — Path A needs 7 simultaneous channels; Path B needs 1 high-rate channel. eDMA on RT1062 has 32 channels with priority arbitration — feasible but should benchmark under load.
  • Pixel-data transpose — Both paths need strip-major to lane-major buffer reorganization per frame. fl::simd's DSP-ext widen/narrow/UXTB16 ops (PR feat(simd/arm-dsp): wire scale/blend/mullo DSP ops (closes #3425 yellow) #3427) accelerate this.
  • Pin claim coordination — Both compete with existing FastLED drivers (FlexIO TX, ObjectFLED, LPSPI, LPUART) for pads. A central pin-allocation table (similar to kLPUARTTxPins from PR feat(lpuart): WS2812 driver via LPUART4 inverted-TX + eDMA for Teensy 4.x #3421) is needed.
  • Per-strip independent reset/latch — APA102 needs an end-frame of 32+ ones; per-strip lengths may differ, so the longest strip drives total transfer time and shorter strips need padding or early stop. Easy to handle in the encoder.

Cross-references

Generated with Claude Code

Activity

  1. added 18 commits that reference this issue on Jun 27, 2026
  2. zackees commented on Jun 28, 2026

    @zackees
    MemberAuthor

    Closing — both unified clockless+SPI engines are now merged and hardware-verified on Teensy 4.1 (COM20).

    Merged

    DefaultBus

    DefaultBus<SpiChipsetConfig> for Teensy 4.x is now Bus::FLEX_IO per directive ("single strip should not default LPSPI because that can be allocated already for peripherals where the parallel io drivers are more likely to be free and can be purposed for spi usage").

    Smoke tests

    • bash autoresearch teensy41 + uv run python ci/autoresearch/test_flexio_spi_smoke.py — 3/3 pass (wait_ms=0)
    • bash autoresearch teensy41 + uv run python ci/autoresearch/test_objectfled_spi_smoke.py — 3/3 pass (wait_ms=5 = drain wait only)

    Both expose register-state diagnostics so future regressions can be triaged without scope-on-wire.

    Follow-ups (separately tracked)

    • FlexIO SPI: track active transfer state for accurate wire-drain timeout #3433 — FlexIO-SPI wire-drain rework (replace fixed 50ms timeout with shifter-drain proxy).
    • Refactor both drivers' file-static state into matching private namespaces (fl::detail::flexio_spi_internal / fl::detail::objectfled_spi_internal) to drop the current sOfSpi* prefix-rename.
    • Byte-level MOSI scope verification + APA102/SK9822 strip end-to-end test (needs physical scope + strip).
  3. moved this from Triage to Done in FastLED Trackeron Jun 28, 2026
  4. chrismiller commented on Oct 11, 2026

    @chrismiller

    I have a use case for the multi-lane FlexIO "Path A" approach described here. I'm looking to build a Teensy powered LED jacket, and I'm planning to have 6 SK9822 LED strips that are all on separate channels, mainly to give more resiliency. If the whole jacket was driven by a single channel, any breakage in the LED strip would on average knock out half the jacket's LEDs. With 6 channels, any break would have a much smaller impact, with an average of just 1/12 of the LEDs going offline.

    With FastLED currently, the FlexIO SPI mode is single-lane (shifter 0 + timer 0), and ChannelEngineFlexIO updates SPI channels sequentially. I haven't tested this yet, but believe it will limit the frame rates I can achieve given the CPU heavy pattern generation code I'll be using. Is there any chance of having Path A implemented, as it seems like a much better solution? I believe it would need these two things:

    1. Multi-lane FlexIO2 SPI. Up to 8 channels (all sharing a clock pin) would be batched into one transfer, one for each of FlexIO2's 8 shifters, with one controller registered per data pin (I think the same as the ESP32 I2S-SPI driver does).

    2. Teensy 4.1 FlexIO2 pins. kFlexIOPins only lists the nine pins a Teensy 4.0 exposes. The Teensy 4.1 has four more:

      Teensy 4.1 pin Pad FlexIO2 line
      36 GPIO_B1_02 18
      37 GPIO_B1_03 19
      35 GPIO_B1_12 28
      34 GPIO_B1_13 29

      The flexio_pin <= 17 static assert would need raising to 31 for these. The existing comment about pad routing topping out at line 17 only applies to the Teensy 4.0.

    One note on the original Path A design: it assumes a DMA channel per shifter, but FlexIO2 only has two distinct DMA request sources (DMAMUX_SOURCE_FLEXIO2_REQUEST0/1 are both 1, REQUEST2/3 are both 65), and shifters 4–7 have none. Having a single DMA request from shifter 0 that writes all the SHIFTBUF registers in one loop would avoid that limit, since every shifter empties on the same timer. Also, FlexIO2 has 8 shifters, so I believe 8 lanes should be possible, not 7, since the clock doesn't need a shifter?

    Apologies if I've made any mistakes in the above, I'm still trying to learn/understand what is and isn't possible with FlexIO, but from what I understand it should be possible to drive 8 SPI channels very efficiently via the FlexIO2 pins.

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