Repository navigation
fix(teensy4): vendor the LPSPI bring-up so SPI drivers stop needing Arduino <SPI.h> (#3777) - #3802
Conversation
…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]>
📝 WalkthroughWalkthroughTeensy 4.x SPI code now uses a local LPSPI implementation. The change adds bus hardware tables and transaction support, removes ChangesTeensy LPSPI backend
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()
Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/platforms/arm/teensy/teensy4_common/lpspi/lpspi_bus.h (1)
145-158: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
mCamelCaseforLpspiBusStoragemembers.
LpspiBusStoragehas anensure()method that performs lazy peripheral-table initialization. This is behavior beyond a simple data aggregate, so its membersbusesandinitializedshould follow themCamelCaseconvention 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
mCamelCaseconvention 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
📒 Files selected for processing (9)
src/platforms/arm/mxrt1062/fastspi_arm_mxrt1062.hsrc/platforms/arm/mxrt1062/spi_device_proxy.hsrc/platforms/arm/teensy/teensy4_common/fastspi_arm_mxrt1062.hsrc/platforms/arm/teensy/teensy4_common/lpspi/README.mdsrc/platforms/arm/teensy/teensy4_common/lpspi/lpspi_bus.hsrc/platforms/arm/teensy/teensy4_common/lpspi/lpspi_hardware.hsrc/platforms/arm/teensy/teensy4_common/spi_hw_2_mxrt1062.cpp.hppsrc/platforms/arm/teensy/teensy4_common/spi_hw_4_mxrt1062.cpp.hppsrc/platforms/arm/teensy/teensy4_common/spi_output_template.h
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
Fixes #3777. Removes the last red check on master (#3775).
The problem
teensy41has been red since 2026-07-30: every symbolfl::SpiHw2MXRT1062/SpiHw4MXRT1062needs 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
SPIClassobjects, 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:15named the globalSPIas a template argument, and that header is reached fromchipsets.h— i.e. from essentially every sketch. No amount of work inside the drivers would have removed the global while that line stood.SPI_INDEXalready existed alongside it, so the reference was redundant; it's now a plain bus index.The fork
Per the
audio/pjrc_*andsdfat/precedent the issue title names — vendored, not rewritten, so the register values stay the battle-tested ones: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 frombeginTransaction/endTransaction— it's gated oninterruptMasksUsed, which onlyusingInterrupt()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:.text.cpp.hpp(unity build)inline constThe 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 satisfiesStaticInHeaderChecker, which exempts statics inside template functions.I would not have caught either without building
Blinkand comparing sizes.Bonus fix
spi_hw_2_mxrt1062.cpp.hpphardcoded 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)
bash compile teensy41 --examples Apa102bash compile teensy41 --examples Blinkbash lintbash test --cppNot 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
Bug Fixes
Documentation