Skip to content

fix(teensy4): vendor the LPSPI bring-up so SPI drivers stop needing Arduino <SPI.h> (#3777) - #3802

Merged
zackees merged 1 commit into
masterfrom
feat/3777-teensy4-lpspi-fork
Aug 1, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3777-teensy4-lpspi-fork

Conversation

@zackees

@zackees zackees commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Fixes #3777. Removes the last red check on master (#3775).

The problem

teensy41 has been red since 2026-07-30: every symbol fl::SpiHw2MXRT1062 / SpiHw4MXRT1062 needs from the Arduino SPI library came up undefined at link. fbuild will not let a local library's headers select a framework library, so <SPI.h> never entered the link, and #3777 established that every documented way to declare the dependency fails.

Declaring it isn't what we want anyway: the framework defines three global SPIClass objects, each ~600 bytes of .bss, and the linker can never drop one once anything names it.

The binding site #3777 doesn't mention: spi_output_template.h:15 named the global SPI as a template argument, and that header is reached from chipsets.h — i.e. from essentially every sketch. No amount of work inside the drivers would have removed the global while that line stood. SPI_INDEX already existed alongside it, so the reference was redundant; it's now a plain bus index.

The fork

Per the audio/pjrc_* and sdfat/ precedent the issue title names — vendored, not rewritten, so the register values stay the battle-tested ones:

src/platforms/arm/teensy/teensy4_common/lpspi/
  lpspi_hardware.h   LpspiHardware + three per-bus pin/mux tables, VERBATIM
  lpspi_bus.h        begin/end/setSCK/setMOSI/setMISO/beginTransaction/
                     endTransaction/transfer, each with its upstream
                     SPI.{h,cpp}:<lines> reference
  README.md          provenance, deviations, validation status

Two deliberate deviations, both documented: the DMA triple is dropped (keeping _spi_dma_rxISR* would anchor upstream's DMA/EventResponder into the link), and the NVIC mask save/restore is dropped from beginTransaction/endTransaction — it's gated on interruptMasksUsed, which only usingInterrupt() sets and FastLED never calls.

The shape is load-bearing — I got it wrong twice before measuring

The issue asks for no flash growth on Blink, as the check that the backend is still strippable. That check earned its keep:

attempt Blink .text
implementation in a .cpp.hpp (unity build) 106,816
tables as namespace-scope inline const 106,816
template accessors + function-local statics 58,688 — byte-identical to master

The first two emitted LpspiBus::get() / the tables unconditionally, dragging all three tables into every Teensy sketch — a 48 KB regression on clockless-only builds. The template form is instantiated only when a bus is actually used, and it also satisfies StaticInHeaderChecker, which exempts statics inside template functions.

I would not have caught either without building Blink and comparing sizes.

Bonus fix

spi_hw_2_mxrt1062.cpp.hpp hardcoded the T4.1 LPSPI1 pins {2,45,43,42} unconditionally — a latent T4.0 bug. Going through the table picks up the T4.0 set (34/35/37).

Validation (local, per the issue's own criteria)

check result
bash compile teensy41 --examples Apa102 links — 0 undefined refs (was 64)
bash compile teensy41 --examples Blink byte-identical to master
bash lint no blocking violations; SingletonElision unchanged at 33
bash test --cpp 274 unit + 83 examples pass

Not yet validated on hardware — please read

Compiling proves the symbols resolve. It does not prove the pads are muxed correctly, and #3777 is explicit that a wrong mux links fine and silently drives nothing.

That risk is why this vendors the proven register code rather than reimplementing it: the pin numbers, mux values and select-input registers are byte-for-byte upstream, so the failure mode would have to be in the wiring-up, not the values.

Driving an APA102/SK9822 strip from a Teensy 4.x is still outstanding. The README records that status next to the code.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a standalone SPI hardware implementation for Teensy 4.x boards.
    • Improved support for selecting and operating multiple SPI buses.
  • Bug Fixes

    • Replaced framework SPI handling with board-specific bus management for more consistent initialization, transactions, and data transfers.
  • Documentation

    • Added documentation covering supported bus mappings, implementation details, and validation status.

…ng Arduino <SPI.h> (#3777)

teensy41 has been red on master since 2026-07-30: every symbol
fl::SpiHw2MXRT1062 / SpiHw4MXRT1062 needs from the Arduino SPI library came
up undefined at link (#3775). fbuild will not let a local library's headers
select a framework library, so <SPI.h> never entered the link, and #3777
established that every documented way to declare the dependency fails.

Declaring it is also not what we want. The framework defines three global
SPIClass objects; each carries ~600 bytes of .bss and the linker can never
drop one once anything names it. FastLED named `SPI` as a template argument
in spi_output_template.h -- reached from chipsets.h, i.e. from essentially
every sketch. That was the real binding site and #3777 does not mention it.

So: fork the IMXRT LPSPI bring-up locally, per the audio/pjrc_* and sdfat/
precedent named in the issue title.

  src/platforms/arm/teensy/teensy4_common/lpspi/
    lpspi_hardware.h  LpspiHardware + the three per-bus pin/mux tables,
                      copied VERBATIM from Teensyduino 1.60 SPI.cpp
    lpspi_bus.h       LpspiBus: begin/end/setSCK/setMOSI/setMISO/
                      beginTransaction/endTransaction/transfer, each body
                      carrying its upstream SPI.{h,cpp}:<lines> reference
    README.md         provenance, deviations, validation status

The template parameter `SPIClass& SPIObject` becomes a plain bus index across
spi_device_proxy.h, both fastspi_arm_mxrt1062.h copies and
spi_output_template.h. `SPI_INDEX` already existed alongside it, so the
global reference was redundant.

Deliberate deviations, all documented in README.md: the DMA triple is dropped
from the hardware struct (keeping the _spi_dma_rxISR* pointers would anchor
upstream's DMA/EventResponder machinery into the link), and the NVIC mask
save/restore is dropped from beginTransaction/endTransaction (it is gated on
interruptMasksUsed, which only usingInterrupt() sets and FastLED never calls).

Header-only, with the hardware tables behind TEMPLATE accessors holding
function-local statics. That shape is load-bearing, and I got it wrong twice
before measuring:
  - implementation in a .cpp.hpp in the unity build -> LpspiBus::get() emitted
    unconditionally, dragging all three tables in
  - tables as namespace-scope `inline const` -> emitted and kept
Both grew Teensy 4.1 Blink from 58,688 to 106,816 bytes of .text. The template
form is instantiated only when a bus is used, and also satisfies
StaticInHeaderChecker, which exempts statics in template functions.

Also fixes a latent T4.0 bug: spi_hw_2_mxrt1062.cpp.hpp hardcoded the T4.1
LPSPI1 pins {2,45,43,42} unconditionally; going through the table picks up the
T4.0 set (34/35/37).

Validated locally, per the issue's own acceptance criteria:
  bash compile teensy41 --examples Apa102 -> links (0 undefined refs, was 64)
  bash compile teensy41 --examples Blink  -> byte-identical to master
                                             (text 58688 data 14016 bss 67968)
  bash lint -> no blocking violations; SingletonElision unchanged at 33
  bash test --cpp -> 274 unit + 83 examples pass

NOT yet validated on hardware. Compiling proves the symbols resolve, not that
the pads are muxed correctly -- and the register values are copied rather than
rewritten precisely to keep that risk low. Driving an APA102/SK9822 strip from
a Teensy 4.x is still outstanding; see #3777.

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Teensy 4.x SPI code now uses a local LPSPI implementation. The change adds bus hardware tables and transaction support, removes SPIClass template parameters, and routes SPI output and hardware adapters through indexed LpspiBus instances.

Changes

Teensy LPSPI backend

Layer / File(s) Summary
LPSPI hardware tables
src/platforms/arm/teensy/teensy4_common/lpspi/lpspi_hardware.h
Adds board-specific configurations for LPSPI buses 4, 3, and 1.
Standalone LPSPI bus implementation
src/platforms/arm/teensy/teensy4_common/lpspi/lpspi_bus.h, src/platforms/arm/teensy/teensy4_common/lpspi/README.md
Adds LpspiSettings, LpspiBus, singleton-backed bus storage, pin setup, peripheral lifecycle, transaction setup, and fork documentation.
Hardware SPI output routing
src/platforms/arm/mxrt1062/fastspi_arm_mxrt1062.h, src/platforms/arm/mxrt1062/spi_device_proxy.h, src/platforms/arm/teensy/teensy4_common/fastspi_arm_mxrt1062.h, src/platforms/arm/teensy/teensy4_common/spi_output_template.h
Removes SPIClass template parameters and routes SPI output operations through the selected LpspiBus.
SPI hardware adapter migration
src/platforms/arm/teensy/teensy4_common/spi_hw_2_mxrt1062.cpp.hpp, src/platforms/arm/teensy/teensy4_common/spi_hw_4_mxrt1062.cpp.hpp
Replaces Arduino SPI objects and SPISettings with LpspiBus and LpspiSettings.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SPIOutput
  participant SPIDeviceProxy
  participant LpspiBus
  participant LpspiSettings
  SPIOutput->>SPIDeviceProxy: create SPI backend
  SPIDeviceProxy->>LpspiBus: get(_SPI_INDEX)
  SPIOutput->>LpspiBus: begin()
  SPIOutput->>LpspiSettings: create transaction settings
  SPIOutput->>LpspiBus: beginTransaction(settings)
  SPIOutput->>LpspiBus: transfer(data)
  SPIOutput->>LpspiBus: endTransaction()
Loading

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#3727 — Replaces framework SPIClass dependencies with local SPI backends on another platform.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the primary change: vendoring LPSPI to remove the Arduino SPI dependency from Teensy 4.x drivers.
Linked Issues check ✅ Passed The changes satisfy issue #3777 by replacing Arduino SPI dependencies with local LPSPI bus and hardware implementations and updating affected drivers.
Out of Scope Changes check ✅ Passed All changed files support the local Teensy 4.x LPSPI implementation, dependency removal, API updates, or related documentation.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/3777-teensy4-lpspi-fork

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Aug 1, 2026
@zackees
zackees merged commit 2841fe8 into master Aug 1, 2026
8 of 10 checks passed
@zackees
zackees deleted the feat/3777-teensy4-lpspi-fork branch August 1, 2026 05:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/platforms/arm/teensy/teensy4_common/lpspi/lpspi_bus.h (1)

145-158: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use mCamelCase for LpspiBusStorage members.

LpspiBusStorage has an ensure() method that performs lazy peripheral-table initialization. This is behavior beyond a simple data aggregate, so its members buses and initialized should follow the mCamelCase convention used elsewhere in this file (mPort, mHw, mClock), not the plain lowercase style reserved for simple aggregates.

As per coding guidelines, "Use mVariableName format for member variables in complex classes, lowercase snake_case for simple structs." Based on learnings, "reserve the mCamelCase convention for non-aggregate class members that represent behavior (state/logic beyond a simple data aggregate)."

♻️ Proposed rename
 struct LpspiBusStorage {
-    LpspiBus buses[3];
-    bool initialized = false;
+    LpspiBus mBuses[3];
+    bool mInitialized = false;
 
     void ensure() {
-        if (initialized) {
+        if (mInitialized) {
             return;
         }
-        initialized = true;
-        buses[0].configure(&IMXRT_LPSPI4_S, &lpspi_hardware<4>());
-        buses[1].configure(&IMXRT_LPSPI3_S, &lpspi_hardware<3>());
-        buses[2].configure(&IMXRT_LPSPI1_S, &lpspi_hardware<1>());
+        mInitialized = true;
+        mBuses[0].configure(&IMXRT_LPSPI4_S, &lpspi_hardware<4>());
+        mBuses[1].configure(&IMXRT_LPSPI3_S, &lpspi_hardware<3>());
+        mBuses[2].configure(&IMXRT_LPSPI1_S, &lpspi_hardware<1>());
     }
 };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/platforms/arm/teensy/teensy4_common/lpspi/lpspi_bus.h` around lines 145 -
158, Rename the LpspiBusStorage member variables buses and initialized to mBuses
and mInitialized, and update all references within ensure() accordingly while
preserving the lazy initialization behavior.

Sources: Coding guidelines, Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/platforms/arm/teensy/teensy4_common/lpspi/lpspi_bus.h`:
- Around line 145-158: Rename the LpspiBusStorage member variables buses and
initialized to mBuses and mInitialized, and update all references within
ensure() accordingly while preserving the lazy initialization behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9db1ecf4-c660-4805-ac91-e94086cdd793

📥 Commits

Reviewing files that changed from the base of the PR and between 02d3e4c and 3a1f4d5.

📒 Files selected for processing (9)
  • src/platforms/arm/mxrt1062/fastspi_arm_mxrt1062.h
  • src/platforms/arm/mxrt1062/spi_device_proxy.h
  • src/platforms/arm/teensy/teensy4_common/fastspi_arm_mxrt1062.h
  • src/platforms/arm/teensy/teensy4_common/lpspi/README.md
  • src/platforms/arm/teensy/teensy4_common/lpspi/lpspi_bus.h
  • src/platforms/arm/teensy/teensy4_common/lpspi/lpspi_hardware.h
  • src/platforms/arm/teensy/teensy4_common/spi_hw_2_mxrt1062.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/spi_hw_4_mxrt1062.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/spi_output_template.h

@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Aug 1, 2026
zackees added a commit that referenced this pull request Aug 22, 2026
SdFat's `SdSpiArduinoDriver` held a `SPIClass*`, so `Fx/FxSdCard` pulled in
Teensyduino's SPI library by header only. That library is compiled solely when
the library finder selects it from an unconditional sketch-level
`#include <SPI.h>`, which FastLED cannot add -- it breaks the host example
build, and the stub platform has no SPI.h. So `SPIClass::*` and the global
`SPI` resolved at compile time and went undefined at link. Vendoring the
library is not an option either: it is GPLv2/LGPLv2.1 and FastLED is MIT.

`LpspiBus` (#3802) already owns the LPSPI registers, so on Teensy 4 the port
type is retargeted at it. Added the two members SdFat actually needs --
`setTransferWriteFill()` and a blocking `transfer(tx, rx, count)` -- and gated
selection behind the `FL_SDFAT_HAS_LPSPI_BUS` capability macro.

Two defects found in review and fixed here:

- `beginTransaction` never flushed the FIFOs. The LED driver takes the same
  `LpspiBus::get(0)` object, writes `TDR` in a loop and never reads `RDR`,
  while `CFGR1` leaves RX capture on -- so a strip write left up to 16 stale
  bytes queued and the next SD `transfer()` returned them instead of the
  card's reply. Silent corruption on an APA102-plus-SD sketch. Now resets
  both FIFOs with `RRF | RTF`, which hardens the LED path too.
- `fs_sdfat_teensy.h` still included `<SPI.h>` unconditionally, keeping the
  GPL header and its declarations in the translation unit; it linked only
  because nothing referenced them. Now guarded on `!FL_IS_TEENSY_4X`.

Teensy 3.x is deliberately untouched and still takes the `SPIClass` path --
that is #3972.

Verified: teensy41 links (flash 120832 B), teensy40 links (flash 118784 B),
teensy35 unchanged with the same six pre-existing undefined symbols,
`bash test --cpp --clean` 283/283 unit + 83/83 examples, `bash lint` clean.
No hardware run -- compile and link only.

Closes #3971
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

teensy4: drop the Arduino SPI library dependency from SpiHw2/4MXRT1062 (local fork, like PJRC audio + SdFat) — real fix for #3775

1 participant