Skip to content

feat(objectfled): unified clockless+SPI engine scaffolding (#3428) - #3432

Merged
zackees merged 14 commits into
masterfrom
feat/objectfled-spi-driver
Jun 28, 2026
Merged

zackees merged 14 commits into
masterfrom
feat/objectfled-spi-driver

Conversation

@zackees

@zackees zackees commented Jun 27, 2026 •

Copy link
Copy Markdown
Member

Summary

🎉 HARDWARE-VERIFIED DMA TRANSMIT on Teensy 4.1. The ObjectFLED-SPI driver now actually fires DMA cycles end-to-end through a QTimer3 + XBAR1 + DMA + GPIO1-aliased pads pipeline. Three-iteration bench debug arc found and fixed:

  1. FlexPWM2 + VALDE — wrong DMA-trigger primitive (VALDE = VAL FIFO reload, not generic tick).
  2. QTimer3 + XBAR + GPIO6_DR — architecturally correct trigger, but DMA bus-faulted on destination: GPIO6-9 are M7-private TCM bus, eDMA can't reach them. Confirmed via DMA_ES = 0x80000401 (DBE).
  3. QTimer3 + XBAR + GPIO1 remap (CURRENT) — clear IOMUXC_GPR_GPR26 bits to alias the pads to GPIO1 (system-bus, eDMA-reachable). DMA fires. ✓

Hardware-verified on Teensy 4.1 (COM20)

uv run python ci/autoresearch/test_objectfled_spi_smoke.py — 3/3 pass:

Case MOSI SCLK GPIO6 bits Clock Bytes wait_ms before wait_ms after DMA_ES
1 14 15 18/19 1 MHz 4 55 (timeout) 5 (drain only) 0
2 14 15 18/19 6 MHz 16 55 (timeout) 5 (drain only) 0
3 16 17 23/22 12 MHz 64 55 (timeout) 5 (drain only) 0

wait_ms=5 = just the unconditional 5ms drain wait. DMA major-loop fires, ISR clears the INT bit, sSpiDmaComplete=true, the outer wait loop exits early.

What changes

Component Status
Unified-engine pattern (Capabilities(true,true), BusSupports, canHandle) ✓ shipped
FlexPWM2/VALDE first attempt ✗ wrong primitive — replaced
QTimer3 + XBAR1 + DMA_CH_MUX_REQ95 ✓ shipped
IOMUXC_GPR_GPR26 remap to GPIO1 alias for eDMA reach ✓ shipped
DMA destination = &GPIO1_DR (was &GPIO6_DR) ✓ shipped
ObjectFLEDDmaManager::acquire() bypass (dma3-spin bug) ✓ shipped
ObjectFLEDSPIDiagnostics struct + RPC dump ✓ shipped (DMA ERQ/INT/ERR/ES/CITER/BITER + TMR3 regs + XBARA1 CTRL1)
objectfledSpiSelfTest RPC smoke test ✓ shipped
ci/autoresearch/test_objectfled_spi_smoke.py host driver ✓ shipped
Full DMA transmit verified end-to-end on Teensy 4.1 ✓ verified
Byte-level MOSI scope verification ✗ pending physical scope
APA102/SK9822 strip end-to-end test ✗ pending physical strip

Why the safety gate is still OFF by default

FL_OBJECTFLED_SPI_HARDWARE_ENABLE stays OFF until the scope verification of the actual MOSI bit pattern lands. The DMA cycle is proven, but if there's still an off-by-half-bit timing or LSB/MSB inversion bug, the user-visible symptom would be "strip lights up wrong" rather than "firmware crashes" — better to keep the gate-off default conservative than ship a transmit path that flickers user strips.

Flipping FL_OBJECTFLED_SPI_HARDWARE_ENABLE=1 enables the working DMA path for anyone with a scope or strip to bench-verify.

Test plan

  • bash test --cpp — 338/338 host tests pass
  • bash lint --cpp clean
  • bash compile teensy40/teensy41 --examples AutoResearch succeeds
  • objectfledSpiSelfTest RPC: 3/3 configurations transmit (wait_ms=5, DMA_ES=0)
  • CI green
  • Scope-verify MOSI bit pattern (0xA5 = 1010 0101 MSB-first)
  • APA102 strip end-to-end test

Refs #3428, #3430. Companion to #3431 (FlexIO-SPI is also hardware-verified at API level).

🤖 Generated with Claude Code

Lands the unified-engine architectural pattern for ObjectFLED per the
rule in PR #3430 ("Parallel-IO peripherals -- one engine for both
clockless and SPI modes"). Same shape as the FlexIO scaffolding in
PR #3431 -- one ChannelEngine, one Bus enum slot, both modes handled
inside the same class. The DMA-bit-banged SPI hardware programming is
a follow-up; this PR puts the capability, BusSupports, and canHandle
SPI branch in place so the type system says the OBJECT_FLED bus can
accept SPI chipsets at compile time.

What changes
- ChannelEngineObjectFLED::getCapabilities() now returns Capabilities(true, true).
- canHandle() accepts both ClocklessChipset and SpiChipsetConfig
  channels. The SPI branch is gated by objectfled_spi_lookup_pins()
  which currently stub-returns false, so SPI channels still fall
  through today via priority dispatch.
- BusSupports<Bus::OBJECT_FLED, SpiChipsetConfig> specialization: lets
  users write FastLED.add<Bus::OBJECT_FLED, SpiChipsetConfig>(cfg) and
  have it type-check at compile time.
- objectfled_spi_mode.{h,cpp.hpp}: new TU declaring the SPI-mode
  hardware shim API (objectfled_spi_lookup_pins / init / show / wait /
  deinit) with stub implementations that all return false. Real impl
  lands in a follow-up PR: DMA-bit-banged SPI via FlexPWM-clocked DMA
  writes to GPIO6_DR (two writes per SCLK cycle, MOSI and SCLK on the
  same GPIO bank).

What does NOT change
- Existing clockless behavior is untouched. canHandle()'s clockless
  branch is byte-equivalent to the previous code (the same pixel-format
  + timing-range check). show() is not modified -- with canHandle()
  rejecting SPI today, show() never sees SPI channels.

Test updates
- `ObjectFLED engine - capabilities are clockless only` flipped to
  `... are unified clockless + SPI (#3428)` and asserts both bits true.
- 338/338 host tests pass; lint clean.

Refs #3428, #3430. Mirror of #3431 (same architectural pattern, FlexIO).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 27, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds Teensy 4.x ObjectFLED SPI-mode support end to end: public SPI helpers, hardware pin lookup and DMA/FlexPWM control, engine dispatch and RPC wiring, plus updated capability and smoke-test coverage.

Changes

ObjectFLED SPI-mode implementation

Layer / File(s) Summary
SPI-mode contract and capability surface
src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_spi_mode.h, src/platforms/arm/teensy/teensy4_common/drivers/objectfled/_build.cpp.hpp, src/platforms/arm/teensy/teensy4_common/drivers/objectfled/bus_traits.h, src/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.h
Defines the SPI pin-routing type and helper declarations, includes the SPI compilation unit, marks Bus::OBJECT_FLED as supporting SpiChipsetConfig, and updates ObjectFLED capability documentation and return values to include SPI.
SPI hardware setup and transmit path
src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_spi_mode.cpp.hpp
Implements GPIO6 pin lookup, FlexPWM2 setup, SPI initialization, byte encoding, frame transmission, bounded waiting, and deinitialization for the Teensy 4.x SPI engine.
Engine dispatch and SPI self-test RPC
src/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp.hpp, examples/AutoResearch/AutoResearchRemoteDriverMethods.cpp
Updates channel handling to recognize valid SPI configurations and registers the Teensy 4.x objectfledSpiSelfTest RPC that runs lookup, init, show, wait, and deinit in sequence.
Capabilities and smoke-test validation
tests/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp, ci/autoresearch/test_objectfled_spi_smoke.py
Updates the ObjectFLED capabilities test to expect SPI support and adds a serial smoke test that exercises the new RPC across multiple SPI pin and clock cases.

Sequence Diagram(s)

sequenceDiagram
  participant AutoResearchRemoteControl
  participant ChannelEngineObjectFLED
  participant objectfled_spi_mode
  participant Teensy4Hardware

  AutoResearchRemoteControl->>ChannelEngineObjectFLED: objectfledSpiSelfTest request
  ChannelEngineObjectFLED->>objectfled_spi_mode: objectfled_spi_lookup_pins()
  objectfled_spi_mode-->>ChannelEngineObjectFLED: pin info
  ChannelEngineObjectFLED->>objectfled_spi_mode: objectfled_spi_init()
  objectfled_spi_mode->>Teensy4Hardware: configure FlexPWM2, GPIO6, DMA
  ChannelEngineObjectFLED->>objectfled_spi_mode: objectfled_spi_show()
  objectfled_spi_mode->>Teensy4Hardware: DMA-driven GPIO6 output
  ChannelEngineObjectFLED->>objectfled_spi_mode: objectfled_spi_wait()
  ChannelEngineObjectFLED->>objectfled_spi_mode: objectfled_spi_deinit()
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#2461: The new BusSupports<Bus::OBJECT_FLED, SpiChipsetConfig> specialization depends on the typed-bus dispatch model introduced there.
  • FastLED/FastLED#3191: The new objectfledSpiSelfTest RPC is added in the same remote-driver binding path that this PR refactored.

Poem

🐇 I hopped through GPIO with a grin,
FlexPWM hummed as the bytes rolled in.
SPI now scurries with DMA in tow,
Then waits, deinit, and off it can go.
A little rabbit cheer for the shiny new lane,
Clockless and SPI now dance in the same frame.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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
Title check ✅ Passed The title clearly matches the main change: unifying ObjectFLED clockless and SPI engine support.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/objectfled-spi-driver

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.

@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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
tests/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp (1)

463-473: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add one runtime SPI-gating test next to this capability check.

This only verifies the advertised capability bit. The new SPI branch in src/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp.hpp still has no test proving that canHandle() rejects SPI channels while objectfled_spi_lookup_pins() is stubbed, so that contract can drift silently. As per coding guidelines, tests/**: keep tests simple, avoiding mocks where possible.

🤖 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
`@tests/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp`
around lines 463 - 473, Add a small runtime SPI-gating test alongside the
existing capability check in ChannelEngineObjectFLED, focusing on the new SPI
path in canHandle() rather than only getCapabilities(). The test should verify
that when objectfled_spi_lookup_pins() is still stubbed, SPI channels are
rejected by canHandle() while clockless behavior remains unchanged, and should
keep the setup simple with minimal mocking in line with the tests/** guidance.

Source: Coding guidelines

🤖 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.

Inline comments:
In
`@src/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp.hpp`:
- Around line 111-117: The pin validation in the ObjectFLED SPI path only
rejects negative values before narrowing to u8, so out-of-range pins can wrap
and hit the wrong lookup. Update the guard in the channel engine logic around
SpiChipsetConfig handling to also reject values above 255 before calling
objectfled_spi_lookup_pins(), keeping the existing early-return behavior and the
same dataPin/clockPin checks.

In
`@src/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.h`:
- Around line 95-96: Move the ChannelEngineObjectFLED::getCapabilities()
implementation out of this header so the header remains declaration-only. Keep
only the method declaration in channel_engine_objectfled.h and place the body in
channel_engine_objectfled.cpp.hpp, preserving the same signature and
override/FL_NO_EXCEPT qualifiers.

In
`@src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_spi_mode.h`:
- Around line 51-55: Update the new SPI transmit API in objectfled_spi_show to
take a single fl::span<const u8> buffer parameter instead of the separate const
u8* buffer and u32 num_bytes arguments. Adjust the declaration in
objectfled_spi_mode.h and any corresponding callers or implementation references
to use the span’s size/data internally, keeping the same validation and DMA
behavior.

---

Nitpick comments:
In
`@tests/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp`:
- Around line 463-473: Add a small runtime SPI-gating test alongside the
existing capability check in ChannelEngineObjectFLED, focusing on the new SPI
path in canHandle() rather than only getCapabilities(). The test should verify
that when objectfled_spi_lookup_pins() is still stubbed, SPI channels are
rejected by canHandle() while clockless behavior remains unchanged, and should
keep the setup simple with minimal mocking in line with the tests/** guidance.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: cc9e693e-ee4f-4d45-b188-8de94e91f967

📥 Commits

Reviewing files that changed from the base of the PR and between cab1619 and b8a74cc.

📒 Files selected for processing (7)
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/_build.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/bus_traits.h
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.h
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_spi_mode.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_spi_mode.h
  • tests/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp

#3428)

Replaces the scaffolding stub with the full DMA-bit-banged SPI design:
FlexPWM2_SM0 drives eDMA writes to GPIO6_DR at 2*SCLK rate, each input
byte expanded to 16 32-bit words alternating MOSI/SCLK phases. MOSI and
SCLK must both be on GPIO6 (the same bank ObjectFLED clockless mode uses);
runtime serialization through ObjectFLEDDmaManager::acquire()/release()
prevents the two modes from racing on the shared peripheral.

Hardware bring-up status
- Pin lookup VERIFIED on real Teensy 4.1 (COM20): pin 14->bit 18,
  pin 15->bit 19, pin 16->bit 23, pin 17->bit 22 (matches digitalPinToBit
  and the GPIO6 pad routing).
- FlexPWM2 register sequence NOT yet hardware-verified -- the first
  show() call hard-faults the Teensy. Initial CCM gate bug (bits 22-23
  vs the correct 18-19) is fixed; a remaining issue still triggers the
  fault. Likely candidates for scope-debug:
    * FlexPWM2 SM0CTRL2 INIT_SEL / CLK_SEL values (RM 30 cross-check).
    * eDMA channel allocation conflict during early boot.
    * GPIO6_DR direct write while clockless mode's GPR26 remap is in
      an unexpected partial state from a prior test boot.

Safety latch
- objectfled_spi_init() returns false unless FL_OBJECTFLED_SPI_HARDWARE_ENABLE
  is defined. Default (undefined) means SPI channels fall through to the
  next bus (FlexIO-SPI from PR #3431) via canHandle returning false.
  Flipping the flag re-enables the full path for bench debug.
- channel_engine_objectfled.cpp.hpp gates its canHandle SPI branch on
  the same macro so a user can't accidentally route SPI to a driver
  whose hardware path is known to crash.

Architectural scaffolding (unchanged from prior commit; ships ready)
- Capabilities(true, true), BusSupports<Bus::OBJECT_FLED, SpiChipsetConfig>,
  canHandle SPI branch, ObjectFLEDSPIPinInfo struct, full lookup/init/
  show/wait/deinit API.

Test infrastructure (new)
- examples/AutoResearch/AutoResearchRemoteDriverMethods.cpp: new RPC
  binding `objectfledSpiSelfTest` (mirrors `flexioSpiSelfTest` from
  PR #3431). Exercises the full lookup -> init -> show -> wait -> deinit
  path with a known byte pattern.
- ci/autoresearch/test_objectfled_spi_smoke.py: host-side driver.
  Currently passes the LOOKUP stage on all 3 test configurations
  (1/6/12 MHz, multiple pin pairs) but reports init_ok=false as expected
  while the hardware gate is off. Ready to validate full path once the
  FL_OBJECTFLED_SPI_HARDWARE_ENABLE flag is flipped after bench debug.

What this PR delivers
- Compiles on teensy40 + teensy41.
- 338/338 host tests pass.
- Lint clean.
- Firmware boots and runs cleanly with the new ObjectFLED-SPI code
  linked in (no crash unless the hardware-enable flag is set).
- Pin lookup hardware-verified on Teensy 4.1.

What this PR does NOT yet deliver
- End-to-end SPI transmission on hardware (gated until FlexPWM2
  register sequence is scope-debugged).
- APA102/SK9822 strip lighting up.

Refs #3428, #3430, #3431.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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.

Actionable comments posted: 7

🧹 Nitpick comments (1)
ci/autoresearch/test_objectfled_spi_smoke.py (1)

101-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Return a dataclass result instead of a tuple.

evaluate() returns multiple values as a tuple; use a small named dataclass result. As per coding guidelines, "Return dataclass structs instead of tuples or dicts for functions with multiple return values."

🤖 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 `@ci/autoresearch/test_objectfled_spi_smoke.py` around lines 101 - 125, The
evaluate() helper currently returns a tuple of (bool, str), but it should return
a small named dataclass result instead to match the coding guideline. Update the
result shape in test_objectfled_spi_smoke.py by introducing a dataclass for the
evaluation outcome and have evaluate() return that type for both failure and
pass cases, keeping the existing success flag and message content while
replacing the tuple-based return.

Source: Coding guidelines

🤖 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.

Inline comments:
In `@ci/autoresearch/test_objectfled_spi_smoke.py`:
- Around line 36-40: The optional pyserial import currently exits during module
import, which can abort test discovery for this test_objectfled_spi_smoke
module. Move the try/except ImportError handling into main(), keep the import of
serial there, and have main() return 1 after printing the missing-dependency
message instead of calling sys.exit(1) at import time.
- Around line 107-112: The smoke test logic in test_objectfled_spi_smoke.py
currently treats objectfled_spi_init() returning false as a hard failure, but
this call is intentionally gated by FL_OBJECTFLED_SPI_HARDWARE_ENABLE. Update
the result handling around the lookup/init/show checks so objectfled_spi_init is
recognized as a skipped or hardware-disabled state instead of failing the test,
while still failing only on real init errors; use the existing result keys like
lookup_ok, init_ok, and show_ok to locate the branch.

In `@examples/AutoResearch/AutoResearchRemoteDriverMethods.cpp`:
- Around line 699-727: The SPI setup path in the remote driver is narrowing
inputs too early, so invalid values can wrap before validation. In the method
that performs the pin lookup and init, validate mosi_pin, sclk_pin, and clock_hz
against their allowed ranges before calling objectfled_spi_lookup_pins and
objectfled_spi_init, and reject out-of-range values with an InvalidArgs response
instead of casting them to fl::u8/fl::u32 first.

In
`@src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_spi_mode.cpp.hpp`:
- Around line 286-317: Rollback the hardware programming in the ObjectFLED SPI
init path when DMA setup fails: in objectfled_spi_mode.cpp.hpp inside the
initialization flow that saves mux state, programs the pads/GPIO6_GDIR, and
calls objectfled_spi_program_flexpwm, make the DMAChannel allocation/TCD failure
branches restore the saved pin mux/pad registers and undo the GPIO/FlexPWM
changes before returning false. Use the existing saved state variables and the
objectfled_spi_deinit cleanup pattern so the failure path leaves the hardware in
its original state even though sSpiInitialized remains false.
- Around line 367-370: The objectfled SPI flow is skipping cleanup when
`sSpiDmaComplete` is already set before `objectfled_spi_wait()` runs. Update the
`objectfled_spi_mode` path around `objectfled_spi_wait`,
`ObjectFLEDDmaManager::getInstance()`, and `mgr.acquire(...)` to track whether
DMA has actually been acquired/started separately from completion state, so the
wait path still stops FlexPWM, clears pins, and releases the DMA manager even if
completion was pre-signaled. Also ensure the next frame only acquires after the
previous one has fully cleaned up.
- Around line 361-365: Reject oversized SPI frames in the objectfled SPI path
instead of truncating them. In the frame validation logic inside the
ObjectFLED_SPI send/parse flow, change the branch that checks num_bytes against
kSpiMaxInputBytes so it returns false immediately and logs the invalid argument,
rather than clamping num_bytes and continuing. Keep the behavior consistent with
the existing invalid-argument contract in the same method so callers of
ObjectFLED_SPI can detect the failure.
- Around line 487-495: The deinit path in
objectfled_spi_init/objectfled_spi_deinit is restoring the SPI pins with a
hardcoded ALT5 value instead of the mux values saved earlier. Update the cleanup
logic for the MOSI and SCLK mux registers to write back sSpiSavedMosiMux and
sSpiSavedSclkMux, using the saved values from initialization rather than forcing
5u. Ensure the changes are made in the deinit section that handles
sSpiCurrentPins.mosi_mux_reg and sSpiCurrentPins.sclk_mux_reg.

---

Nitpick comments:
In `@ci/autoresearch/test_objectfled_spi_smoke.py`:
- Around line 101-125: The evaluate() helper currently returns a tuple of (bool,
str), but it should return a small named dataclass result instead to match the
coding guideline. Update the result shape in test_objectfled_spi_smoke.py by
introducing a dataclass for the evaluation outcome and have evaluate() return
that type for both failure and pass cases, keeping the existing success flag and
message content while replacing the tuple-based return.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d278f472-c695-4588-8640-2221b2f3ca39

📥 Commits

Reviewing files that changed from the base of the PR and between b8a74cc and 15f6a89.

📒 Files selected for processing (5)
  • ci/autoresearch/test_objectfled_spi_smoke.py
  • examples/AutoResearch/AutoResearchRemoteDriverMethods.cpp
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_spi_mode.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_spi_mode.h
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/channel_engine_objectfled.cpp.hpp

zackees and others added 2 commits June 27, 2026 15:43
…cipline, pin validation, test-discovery safety)

Four fixes from CodeRabbit's review of #3432:

1. Move getCapabilities() body out of the header (MAJOR header discipline).
   Per `src/**/*.h` rule: declarations only, no inline definitions. Body
   moved to channel_engine_objectfled.cpp.hpp.

2. Validate SPI pin ranges in canHandle BEFORE narrowing to u8 (MINOR
   functional correctness). spi->dataPin=270 wraps to pin 14 in
   static_cast<u8>() and silently routes to the wrong hardware pin. Now
   reject [-, -1] U [256, ∞) explicitly.

3. Validate pin / clock_hz in objectfledSpiSelfTest RPC binding before
   narrowing casts (MAJOR validation). Same wrap-to-wrong-pin issue as
   #2 but on the host-driven RPC path. Added explicit InvalidArgs for
   out-of-range mosi_pin, sclk_pin, clock_hz.

4. Defer pyserial import to main() in test_objectfled_spi_smoke.py (MAJOR
   stability). The file is named `test_*.py` so pytest-style collectors
   will try to import it; the prior `sys.exit(1)` at module-load would
   abort the whole collection when pyserial is absent. Now the import +
   error live inside main() so the module imports cleanly.

Verified:
  - bash test --cpp -> 338/338 pass
  - bash lint --cpp -> clean
  - bash compile teensy41 --examples AutoResearch -> succeeds

Refs #3428, #3432.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Bench-debug update for #3428: the hard fault that crashed the Teensy 4.1
on the first SPI show() call has been root-caused to
`ObjectFLEDDmaManager::acquire()`, which calls `waitForCompletion()`
that spins on `dma3.complete()`. When clockless mode has NEVER run,
dma3's major-loop INT flag is unset and `complete()` returns false
forever -- the spin either hangs or crashes the firmware (we observed
crash + USB-serial disconnect on Teensy 4.1).

Bisect timeline (via Serial.flush() checkpoints between each register
write, with FL_OBJECTFLED_SPI_HARDWARE_ENABLE forced on locally):
  init_entry -> init_pre_ccm -> init_post_ccm -> init_pre_gpio ->
  init_post_gpio -> pwm_pre_outen -> ... -> pwm_done ->
  init_post_program_flexpwm -> dma_pre_new -> dma_post_new ->
  dma_pre_trigger -> dma_post_trigger -> dma_post_attach ->
  show_pre_mgr_acquire -> *** CRASH ***

The FlexPWM2 register sequence + GPIO6 setup + DMA channel allocation
all complete cleanly. The crash is entirely in the manager's
acquire/waitForCompletion path.

Fix: bypass the manager from SPI mode. The "race" between clockless and
SPI on the same GPIO6 bank is theoretical -- FastLED's single-threaded
engine serializes show() calls per channel, so a clockless show()
completes before a SPI show() can start. Proper coordination (if needed
later) requires either a manager-side fix to initialize dma3's INT flag
in the constructor, or a separate per-bank primitive that doesn't rely
on dma3.

Hardware verified on Teensy 4.1 (COM20) with the gate enabled:
  - Full init + show + wait + deinit path runs without crashing.
  - wait_ms=50 = bounded recovery timeout -- the DMA isn't yet
    completing within budget. This is a separate issue (FlexPWM2 -> DMA
    trigger wiring) that needs scope-on-wire to debug.

Safety gate FL_OBJECTFLED_SPI_HARDWARE_ENABLE stays OFF by default --
even though the crash is fixed, the driver still doesn't actually
transmit bytes (DMA timeout). Flipping the gate enables the no-crash
path for bench debug.

Refs #3428, #3432.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@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/drivers/objectfled/objectfled_spi_mode.cpp.hpp (1)

246-255: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Update the stale bring-up note above this status block.

These new lines say init+show now completes cleanly, but Line 239 still says the first show() hard-faults. Please collapse this into one current failure mode so bench-debug notes do not point at the wrong symptom.

Proposed comment cleanup
-    // a remaining issue still hard-faults the Teensy on the first show()
-    // call. Likely culprits to investigate on first scope-on-MOSI debug:
+    // first-time show() hard-fault is fixed by bypassing
+    // ObjectFLEDDmaManager::acquire() in SPI mode, but the transfer still
+    // times out waiting for DMA completion. Likely culprits to investigate
+    // on first scope-on-MOSI debug:
🤖 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/drivers/objectfled/objectfled_spi_mode.cpp.hpp`
around lines 246 - 255, The bring-up note in the ObjectFLED SPI status block is
stale and conflicts with the current behavior described nearby. Update the
comment around the ObjectFLEDDmaManager acquire/show path so it reflects one
current failure mode only, removing the mention that the first show()
hard-faults if that is no longer true. Keep the bench-debug note aligned with
the actual Teensy 4.1 state and preserve the guidance about
FL_OBJECTFLED_SPI_HARDWARE_ENABLE being off by default.
🤖 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/drivers/objectfled/objectfled_spi_mode.cpp.hpp`:
- Around line 246-255: The bring-up note in the ObjectFLED SPI status block is
stale and conflicts with the current behavior described nearby. Update the
comment around the ObjectFLEDDmaManager acquire/show path so it reflects one
current failure mode only, removing the mention that the first show()
hard-faults if that is no longer true. Keep the bench-debug note aligned with
the actual Teensy 4.1 state and preserve the guidance about
FL_OBJECTFLED_SPI_HARDWARE_ENABLE being off by default.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: cae62a98-fe2c-4249-be3d-aa1e4961697f

📥 Commits

Reviewing files that changed from the base of the PR and between f511abb and f536882.

📒 Files selected for processing (1)
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_spi_mode.cpp.hpp

zackees and others added 3 commits June 27, 2026 16:28
…trigger

Second hardware-debug pass on #3428: the FlexPWM2_SM0DMAEN write was
using `(1u << 4)`, which is the `CA0DE` field (Capture A 0 DMA Enable)
-- a capture-mode DMA trigger that never fires in PWM-output mode. The
correct field for "DMA on VAL register reload" is `FLEXPWM_SMDMAEN_VALDE`
= bit 9 (per imxrt.h:5079).

Cross-verified against Teensyduino's `libraries/Audio/output_pwm.cpp:310`
which uses `FLEXPWM_SMDMAEN_VALDE` for the same PWM-update-driven DMA
pattern.

Status with this fix + the prior dma3-bypass fix:
  - Init + show + wait + deinit no longer crashes the firmware. ✓
  - All three smoke-test configurations report success / lookup_ok /
    init_ok / show_ok. ✓
  - DMA major-loop completion is STILL not signaled within the 50 ms
    timeout. The VALDE bit is now correctly set, but something else
    in the FlexPWM2 -> DMAMUX -> eDMA chain isn't wiring through.
    Likely candidates (per the TODO marker, still to debug on bench):
      * FlexPWM RUN timing -- maybe RUN must precede LDOK, not follow.
      * DMAMUX source 100 may not be the actual FlexPWM2_WRITE0 line
        on every RT1062 stepping.
      * eDMA ERQ might need explicit set after triggerAtHardwareEvent.

Safety gate FL_OBJECTFLED_SPI_HARDWARE_ENABLE stays OFF by default --
even though no crash, the driver still doesn't transmit. Bench debug
with scope-on-wire required to root-cause the missing trigger.

Refs #3428, #3432.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Update the safety-gate comment with the architectural finding from this
debug session: VALDE is the wrong DMA trigger primitive for our use case.

VALDE (FlexPWM SMDMAEN bit 9) is documented as "VAL FIFO needs more
data" -- it fires when a PWM VAL register is about to be reloaded from
its FIFO. Teensy's Audio library uses it that way (output_pwm.cpp:310)
to feed new duty-cycle values to the PWM. It is NOT a generic "PWM
compare event happened" trigger.

Our design wants the second semantic: fire DMA on each PWM tick so we
can write a new pattern word to GPIO6_DR. The two correct paths for
that are:

  (a) Use QTimer1/2/3 with DMAMUX_SOURCE_QTIMER{1,2,3}_WRITE0_CMPLD1.
      QTimer compare events have generic DMA-request hookup. QTimer4 is
      taken by ObjectFLED clockless mode but 1/2/3 are free.

  (b) XBAR-route a FlexPWM compare event to a generic DMA request line.
      More flexible but more setup overhead.

Either is a non-trivial redesign vs the current "set VALDE and hope"
approach, so the safety gate FL_OBJECTFLED_SPI_HARDWARE_ENABLE stays
OFF by default until the next bench session picks (a) or (b) and
verifies on scope.

Refs #3428, #3432.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Python with `-OO` strips docstrings, so `__doc__` can be `None`. The
prior `__doc__.splitlines()[0]` triggers an unresolved-attribute error
under ty (type checker). Guard with `or ""` before calling .splitlines().

Caught by the stop-hook lint run after the previous commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 27, 2026
Mirror of the same fix on PR #3432's test_objectfled_spi_smoke.py:
`__doc__` can be `None` if Python runs with `-OO`, so guard before
calling `.splitlines()`.

Caught by the same stop-hook lint pass (`ty` type checker).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees and others added 5 commits June 27, 2026 16:40
Update the safety-gate design comment with the precise QTimer1+XBAR
implementation path, cross-referenced against the working clockless
setup at OjectFLED.cpp.hpp:305-335. Key corrections vs the previous
comment:

- The bare DMAMUX_SOURCE_QTIMER1_WRITE0_CMPLD1 (= 52) is NOT a viable
  alternative -- that source fires on CPU/DMA writes to CMPLD1, not on
  periodic compare events. Removed the misleading reference.

- Added the exact XBAR mapping to use: XBARA1_IN_QTIMER1_TIMER0 ->
  XBARA1_OUT_DMA_CH_MUX_REQ95 (30/31/94 are taken by clockless mode).

- Spelled out the 5-step adaptation from clockless QTimer4 to SPI
  QTimer1, with file:line references to the reference code.

No behavior change -- safety gate FL_OBJECTFLED_SPI_HARDWARE_ENABLE
stays OFF by default. Next bench-debug session implements the path.

Refs #3428, #3432.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…nding bench debug)

Replaces the FlexPWM2/VALDE DMA-trigger design with the architecturally
correct QTimer3 + XBAR1 + DMA_CH_MUX_REQ95 path, mirroring the working
clockless QTimer4 setup at OjectFLED.cpp.hpp:305-335.

What changed
- objectfled_spi_program_qtimer() replaces objectfled_spi_program_flexpwm().
  Configures QTimer3 channel 0 in periodic count-and-compare mode at
  2*sclk_hz, with TCF1EN compare-flag-1 IRQ enable (drives XBAR edge).
- xbar_connect(XBARA1_IN_QTIMER3_TIMER0, XBARA1_OUT_DMA_CH_MUX_REQ95) +
  XBARA1_CTRL1 slot-1 edge-detect DMA enable (OR'd, doesn't disturb
  slot 0 which clockless mode may have configured for req94).
- DMA trigger source: DMAMUX_SOURCE_XBAR1_3 (= 95) instead of
  DMAMUX_SOURCE_FLEXPWM2_WRITE0.
- show()/wait()/deinit() use TMR3_ENBL bit toggles instead of FLEXPWM
  RUN bit toggles.
- Forward-decl `extern "C" void xbar_connect(...)` since Teensyduino
  doesn't expose it via header.

Why both attempts (VALDE and QTimer3+XBAR)
- VALDE is "VAL FIFO needs more data" -- only fires when DMA destination
  is a PWM VAL register. Wrong primitive for our GPIO6_DR target.
- QTimer3 compare events routed through XBAR are the canonical "periodic
  tick triggers DMA" primitive on i.MX RT1062, used by clockless mode.

Hardware bench status (Teensy 4.1, COM20):
- Init + show + wait + deinit no longer crash (was: hard fault on first
  show; fix landed in earlier commit f536882).
- wait_ms = 55 ms = bounded DMA-timeout(50) + drain-wait(5).
  The DMA STILL doesn't actually complete -- both attempted designs
  fail to fire the DMA, with the same symptom.

Remaining suspects (in-code TODO comment lists them):
  (a) QTimer3 channel 0 not actually counting.
  (b) XBAR edge-detect not latching.
  (c) DMA channel ERQ bit not set.
  (d) DMAMUX mis-configured.

All four require scope-on-bench to diagnose -- the next bench session
should add a DMA-state dump (DMA_ERQ, DMA_INT, TCD.CITER, etc.) to the
smoke test RPC response so host-side test can see which suspect is the
root cause.

Safety gate FL_OBJECTFLED_SPI_HARDWARE_ENABLE stays OFF by default.

Refs #3428, #3432.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…A reach

Root cause of the DMA-not-completing puzzle root-caused and FIXED via the
diagnostic-register dump shipped earlier this iteration: DMA_ES showed
0x80000401 = DBE (Destination Bus Error) on channel 4. The eDMA cannot
write to &GPIO6_DR directly because GPIO6-9 are "fast GPIO" on the
Cortex-M7 private TCM bus, inaccessible from the system-bus eDMA.

Fix: mirror the clockless ObjectFLED pattern (OjectFLED.cpp.hpp:264) --
clear the matching IOMUXC_GPR_GPR26 bits in init() to remap the MOSI/SCLK
pads from GPIO6 (M7-only) to GPIO1 (system-bus = eDMA-reachable). Bit
positions in GPIO1_DR are identical to GPIO6_DR. Then DMA destination
becomes &GPIO1_DR and all reads/writes touch the alias.

Hardware-verified on Teensy 4.1 (COM20). Three smoke-test configurations:
  | Case                  | wait_ms before | wait_ms after | DMA_ES |
  |-----------------------|----------------|---------------|--------|
  | 1 MHz @ 14/15 (4B)    | 55 (timeout)   | 5 (drain only)| 0      |
  | 6 MHz @ 14/15 (16B)   | 55 (timeout)   | 5 (drain only)| 0      |
  | 12 MHz @ 16/17 (64B)  | 55 (timeout)   | 5 (drain only)| 0      |

DMA fires, ISR clears the INT bit, the full lookup -> init -> show ->
wait -> deinit chain transmits end-to-end.

Also adds (for the diagnostic):
- ObjectFLEDSPIDiagnostics struct + objectfled_spi_read_diagnostics()
  exposing DMA ERQ/INT/ERR/ES/CITER/BITER + TMR3 CNTR0/CSCTRL0/SCTRL0/
  CTRL0/ENBL + XBARA1 CTRL1. Captured BEFORE wait()-timeout cleanup.
- objectfledSpiSelfTest RPC now reports all of the above so the host
  smoke test can diagnose any future regression without scope-on-wire.

Safety gate FL_OBJECTFLED_SPI_HARDWARE_ENABLE stays OFF by default --
the DMA transmit cycle is proven on hardware, but byte-level scope
verification of the actual MOSI bit pattern + APA102/SK9822 strip test
are still pending. Flipping the gate enables the working path.

Refs #3428, #3432.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Per CodeRabbit review on PR #3432:

- objectfled_spi_show() now returns false when num_bytes exceeds
  kSpiMaxInputBytes instead of silently truncating. Silent truncation
  would emit a partial APA102/SK9822 frame with no caller visibility,
  corrupting strip output.
- objectfled_spi_deinit() now restores the pre-init pad ALT mux values
  (sSpiSavedMosiMux / sSpiSavedSclkMux) instead of forcing ALT5 (GPIO).
  Forcing ALT5 silently mutated the pin mux for users who had the pad
  on another ALT (e.g. ALT3 FlexCAN) before init.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…SPI_HARDWARE_ENABLE=1)

Flip the gate to ENABLED-by-default per user directive. The DMA transmit
cycle is hardware-verified on Teensy 4.1 (3/3 smoke tests at 1/6/12 MHz
with wait_ms=5 = drain-only, DMA_ES=0 = no errors).

What changes:
  - objectfled_spi_mode.cpp.hpp: `FL_OBJECTFLED_SPI_HARDWARE_ENABLE` now
    auto-defines to 1 unless `FL_OBJECTFLED_SPI_HARDWARE_DISABLE` is
    explicitly defined by the user (opt-out, not opt-in).
  - channel_engine_objectfled.cpp.hpp: canHandle SPI branch gated on
    `!defined(FL_OBJECTFLED_SPI_HARDWARE_DISABLE)` instead of the
    opt-in `defined(FL_OBJECTFLED_SPI_HARDWARE_ENABLE)`.

Re-verified on Teensy 4.1 (COM20) -- 3/3 smoke test pass remains:
  1 MHz @ 14/15 (4B)   -> wait_ms=5
  6 MHz @ 14/15 (16B)  -> wait_ms=5
  12 MHz @ 16/17 (64B) -> wait_ms=5

The opt-out flag `FL_OBJECTFLED_SPI_HARDWARE_DISABLE` is provided for
users who prefer the prior "SPI falls through to next bus" behavior --
e.g. if they want SPI channels to land on FlexIO-SPI (from #3431) instead.

Refs #3428, #3432.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 28, 2026
* feat(flexio): unified clockless + SPI engine scaffolding (#3428)

Lands the unified-engine architectural pattern for FlexIO2 per the rule
in PR #3430 ("Parallel-IO peripherals -- one engine for both clockless
and SPI modes"). The hardware SPI programming itself is a follow-up;
this PR puts the engine, capabilities, BusSupports specialization, and
mode-routing in place so the type-system and dispatch story is in code.

What changes
- ChannelEngineFlexIO::getCapabilities() now returns Capabilities(true, true).
- canHandle() accepts both ClocklessChipset and SpiChipsetConfig channels
  (the SPI branch is gated by flexio_spi_lookup_pins() which currently
  stub-returns false, so SPI channels still fall through today).
- show() routes per-channel between the existing clockless path and a
  new SPI path. The peripheral is deinit'd and reinit'd on mode change
  -- one peripheral, two modes, never both at once.
- New `Mode` enum + per-mode tracking fields (current pin/timing for
  clockless, current MOSI/SCLK/clock_hz for SPI) detect when the
  hardware can be reused vs needs reprogramming.
- BusSupports<Bus::FLEX_IO, SpiChipsetConfig> specialization: lets users
  write FastLED.add<Bus::FLEX_IO, SpiChipsetConfig>(cfg) and have it
  type-check at compile time.
- flexio_spi_mode.{h,cpp.hpp}: new TU declaring the SPI-mode hardware
  shim API (flexio_spi_lookup_pins / init / show / wait / deinit) with
  stub implementations that all return false. Real FlexIO2 SPI master
  mode register programming (shifter 0 = MOSI, timer 0 = SCLK baud)
  lands in a follow-up PR.

What does NOT change
- Existing clockless behavior is untouched -- canHandle()'s clockless
  branch is byte-equivalent to the previous code; show()'s clockless
  reinit path is the same logic guarded by mCurrentMode != Clockless.
- DefaultBus<SpiChipsetConfig> for Teensy 4.x stays intentionally
  unspecified (per user directive: "single strip should not default
  LPSPI"; flip to Bus::FLEX_IO once the SPI hardware is verified
  working on device).

Test updates
- `FlexIO engine - capabilities are clockless only` flipped to
  `... are unified clockless + SPI (#3428)` and asserts both bits true.
- 338/338 host tests pass; lint clean.

Refs #3428, #3430.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(flexio-spi): implement FlexIO2 SPI master hardware programming (#3428)

Replaces the stubbed flexio_spi_* helpers from the scaffolding commit
with the real i.MX RT1062 FlexIO2 SPI master mode register programming.
With this commit, ChannelEngineFlexIO can actually serve APA102 /
SK9822-class SPI channels in addition to its existing clockless WS2812
mode -- one peripheral, one engine, two modes (unified-engine rule per
PR #3430).

Hardware programming
- Shifter 0: transmit mode (SMOD=2), TIMSEL=0, TIMPOL=1 (shift on
  falling edge for Mode 0 stable-at-rising-edge), PINCFG=3 (drives
  MOSI), PINSEL=MOSI flexio pin index.
- Timer 0: dual 8-bit baud mode (TIMOD=1), trigger from shifter 0
  status flag (TRIGGER_ACTIVE_LOW so timer runs while shifter has
  data), PINCFG=3 (drives SCLK), TIMOUT=1 (SCLK idle LOW for Mode 0
  CPOL=0 -- note: TIMOUT encoding is inverted from intuition; TIMOUT(1)
  = LOW per imxrt.h:4146-4147).
- TIMCMP = (15 << 8) | baud_div_field. 15 = (8 bits * 2 transitions) -
  1. baud_div = (120 MHz / (2 * clock_hz)) - 1, clamped to [0, 255].
  Effective SCLK range: ~234 kHz to ~12 MHz at baud_div=4 (12 MHz =
  120 / 10).
- Pin mux: ALT4 + SION on both MOSI and SCLK pads; SION is critical
  for routing the pin to the FlexIO peripheral (same SION investigation
  that fixed the clockless mode in #3416 FX-CRIT-1).
- DMA TCD: 1-byte beats from user buffer to SHIFTBUFBBS[0] (byte+bit-
  swap alias) -- streams bytes out MSB-first as required by APA102 /
  Mode 0 SPI. DMAMUX_SOURCE_FLEXIO2_REQUEST0 triggers per shifter-empty.
- Cache coherence: arm_dcache_flush() on the user buffer when it lives
  in cached memory (>= 0x20200000).
- DSB barrier before kicking DMA.
- Bounded 50 ms DMA wait + bounded 5 ms shifter-drain wait, both with
  force-recovery on timeout (same pattern as flexio_wait FX-MED-4).

Architectural notes
- flexio_internal.h: new shared header exposing the FlexIOPinEntry
  struct + flexio_lookup_pin_entry() + flexio_ensure_clock(). Both
  the clockless mode (flexio_driver.cpp.hpp) and the SPI mode share
  the same pin table and the same CCM clock-gate sequence -- no
  forking.
- Mutually exclusive at runtime: each mode's _init() asserts the
  peripheral is in its expected state, and each mode's _deinit() is
  called by the unified engine before switching modes.
- Same FASTACC=OFF + SION mux + #undef FLEXIO2_* dance as the
  clockless side.
- Clamps clock to [100 kHz, 25 MHz]; APA102 spec is 30 MHz max but
  we keep margin for cable + chipset variance.

Reference
- NXP i.MX RT1060 Reference Manual rev 2, chapter 50 (FlexIO).
- Teensyduino libraries/FlexIO_t4/src/FlexIOSPI.cpp (canonical
  NXP-blessed reference cross-checked for all field encodings).

Build / test
- bash test --cpp: 338/338 host tests pass.
- bash compile teensy40 --examples AutoResearch: succeeds (flash 18.6%).
- bash compile teensy41 --examples AutoResearch: succeeds.
- bash lint --cpp: clean.
- Hardware loopback validation pending -- TODO comments in the file
  mark the two register fields (TIMPOL polarity, SHIFTBUFBBS vs
  SHIFTBUFBIS) to scope-verify on first bring-up.

Refs #3428, #3430. Builds on the scaffolding from this branch's prior
commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(flexio-spi): add hardware bring-up smoke test (#3428)

Adds the `flexioSpiSelfTest` AutoResearch RPC binding plus a Python
host-side driver script `ci/autoresearch/test_flexio_spi_smoke.py` that
exercises the full FlexIO2 SPI master-mode hardware path -- pin lookup,
init, DMA-driven show, wait, deinit -- without needing a logic analyzer
or APA102 strip wired up.

Hardware-verified on a real Teensy 4.1 (COM20). Three test cases pass:
  - 1 MHz @ pins 10/12 (flex 0/1), 4 bytes
  - 6 MHz @ pins 10/12, 16 bytes
  - 12 MHz @ pins 11/13 (flex 2/3), 64 bytes

This rules out the worst-case failures (firmware crash on SPI init, DMA
hang past the 50 ms timeout, wrong pin routing) and confirms that:
  - flexio_spi_lookup_pins correctly maps (MOSI, SCLK) pin pairs against
    the shared kFlexIOPins table.
  - flexio_spi_init successfully programs shifter 0 + timer 0 at multiple
    clock rates (1, 6, 12 MHz).
  - flexio_spi_show + flexio_spi_wait round-trip cleanly for buffers
    from 4 to 64 bytes (all complete in <1 ms vs the 50 ms budget).
  - The clockless mode is unaffected -- the AutoResearch firmware still
    boots with the new SPI hardware code linked in.

What this does NOT verify (still TODO per the in-code markers in
flexio_spi_mode.cpp.hpp):
  - Byte-level MOSI bit pattern (need a scope to confirm 0xA5 streams
    out as 1010 0101 MSB-first).
  - SCLK polarity / TIMPOL / SHIFTBUFBBS vs SHIFTBUFBIS questions --
    these need scope-on-the-wire verification on first APA102 strip
    bring-up. The test pattern (0xA5 0x5A 0xFF 0x00) was chosen for
    easy scope visual inspection.

Implementation note: the RPC binding parses args from `args.is_object()`
(the framework strips the outer params array and passes params[0]
directly). Several existing bindings in this file use the wrong
`args.is_array()` check and silently use their defaults -- pre-existing
bug, fix tracked separately so this PR stays focused on the SPI work.

Refs #3428.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(flexio-spi): address coderabbitai PR #3431 review (ceiling div, state reset, header discipline, arg validation)

Four fixes from CodeRabbit's review of #3431, all hardware-verified to
keep the 3/3 smoke-test pass on Teensy 4.1:

1. Ceiling division for SPI baud divider (MAJOR correctness).
   The floor calc had `120 MHz / (2 * 25 MHz) = 2` → div_field=1 → actual
   SCLK = 120/(2*2) = 30 MHz, exceeding the 25 MHz upper clamp. Switch to
   `(num + denom - 1) / denom` so actual SCLK never exceeds the requested
   rate. (flexio_spi_mode.cpp.hpp:241)

2. Reset cached engine state immediately after deinit (MAJOR stability).
   Both clockless and SPI reinit paths in show() called deinit() then ran
   validation/init that could `continue` on failure, leaving
   mHwInitialized/mCurrentMode advertising a torn-down config. A later
   channel could then skip reinit and transmit through deinitialized
   hardware. Now reset state right after each deinit().
   (channel_engine_flexio.cpp.hpp:163 + :221)

3. Move getCapabilities() body out of the header (MAJOR header discipline).
   Per the project's `src/**/*.h` rule: declarations only, no inline
   definitions. Body moved to channel_engine_flexio.cpp.hpp.
   (channel_engine_flexio.h:91 → channel_engine_flexio.cpp.hpp)

4. Validate pin / clock_hz ranges before narrowing casts (MAJOR validation).
   `flexioSpiSelfTest` RPC narrowed user-supplied `mosi_pin` /  `sclk_pin`
   directly to u8 and `clock_hz` to u32; out-of-range inputs (e.g.
   mosi_pin=270 wraps to pin 14) would silently route to wrong hardware.
   Now reject [-, -1] U [256, ∞) for pins and [-, 0] for clock_hz with
   InvalidArgs before the cast.
   (AutoResearchRemoteDriverMethods.cpp:flexioSpiSelfTest)

Verified:
  - bash test --cpp -> 338/338 pass
  - bash lint --cpp -> clean
  - bash compile teensy41 --examples AutoResearch -> succeeds
  - flexioSpiSelfTest on real Teensy 4.1 -> 3/3 pass at 1/6/12 MHz

Refs #3428, #3431.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(ci): guard against __doc__ being None in test_flexio_spi_smoke

Mirror of the same fix on PR #3432's test_objectfled_spi_smoke.py:
`__doc__` can be `None` if Python runs with `-OO`, so guard before
calling `.splitlines()`.

Caught by the same stop-hook lint pass (`ty` type checker).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(channels): set DefaultBus<SpiChipsetConfig> = Bus::FLEX_IO on Teensy 4.x

Per user directive #3428 ("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").

With FlexIO-SPI hardware-verified (this PR's smoke test passes 3/3 on
Teensy 4.1 at 1/6/12 MHz), the parallel-IO peripheral is the right
default for SPI chipsets (APA102 / SK9822 / HD108 / etc) on Teensy 4.x.

Why FlexIO over ObjectFLED for the SpiChipsetConfig default:
- FlexIO is a true hardware SPI master engine (shifter + timer),
  ObjectFLED-SPI is DMA-bit-banged (slower, more memory).
- FlexIO2's dedicated pin pool {6, 7, 8, 9, 10, 11, 12, 13, 32} rarely
  collides with user GPIO use. ObjectFLED-SPI uses the GPIO6 bank,
  which overlaps with many common Teensy pins.
- LPSPI is the prior "implicit default" and is often already claimed by
  user peripherals (per the user's reason cited above).

Users who explicitly want LPSPI, BIT_BANG, or ObjectFLED-SPI can still
pick those via `FastLED.add<Bus::LPSPI, SpiChipsetConfig>(cfg)` etc.

Refs #3428, #3431.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(flexio-spi): address coderabbitai second-pass review (PR #3431)

Five fixes from CodeRabbit's follow-up review:

1. Restore pin muxes on DMA allocation failure (MAJOR stability).
   flexio_spi_init() saves MOSI/SCLK mux state at entry, then switches
   both pads to ALT4|SION. If the subsequent DMAChannel allocation
   fails, restore the saved muxes (and clear SPI_FLEXIO2_CTRL) before
   returning false so the pins are not left stolen by a failed init.
   (flexio_spi_mode.cpp.hpp:343)

2. Strict wait_ms validation in smoke test (MINOR correctness).
   `int(result.get("wait_ms", 0))` silently defaulted a missing/
   non-integer wait_ms to 0, which could let a malformed firmware
   response pass the smoke test. Now require an actual int (reject
   bool, None, str, etc.) and fail with a clear message otherwise.
   (ci/autoresearch/test_flexio_spi_smoke.py:111)

3. Align flexioSpiSelfTest RPC comment with actual payload (MINOR docs).
   The doc-comment claimed the handler returned a "snapshot of the
   FlexIO2 peripheral registers", but the response only contains
   stage-success flags and resolved pin indices. Updated to match.
   (AutoResearchRemoteDriverMethods.cpp:646)

4. Use %d/%u format specifiers for integer log args (MINOR style).
   Several FL_LOG_FLEXIO_F() call sites passed `(int)pin` / `(int)hz`
   with `%s` specifiers. `fl::printf` is type-safe so this is not UB,
   but the specifiers should match the argument type. Switched pin
   args to `%d` and clock_hz/timeout_ms args to `%u` across
   channel_engine_flexio.cpp.hpp, flexio_driver.cpp.hpp, and
   flexio_spi_mode.cpp.hpp.

5. Guard flexio_spi_show() return value before wait (MINOR robustness).
   ChannelEngineFlexIO::show() previously called flexio_spi_wait()
   unconditionally even if flexio_spi_show() returned false (e.g.
   peripheral not initialized, null buffer). wait() short-circuits in
   that case but the new guard makes the dependency explicit and
   prevents the loop from advancing as if DMA had been armed.
   (channel_engine_flexio.cpp.hpp:264)

Verified:
  - bash test --cpp -> all pass
  - bash lint -> clean
  - bash compile teensy41 --examples AutoResearch -> succeeds
    (only pre-existing -Wunused-variable warnings on SHIFTBUF / SHIFTBUFBIS)

Refs #3428, #3431.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(flexio-spi): update bus_traits comment to reflect working SPI runtime

CodeRabbit (#3431) noted the comment claimed the FlexIO SPI helpers
were stubbed, which would have made the BusSupports<FLEX_IO,
SpiChipsetConfig> specialization an empty promise. The helpers are
no longer stubbed -- flexioSpiSelfTest passes 3/3 at 1/6/12 MHz on
real Teensy 4.1 hardware (see PR #3431, commit f13dc0e). Update the
comment to point at the smoke test instead of claiming a stub.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees and others added 2 commits June 27, 2026 18:45
…-driver

# Conflicts:
#	examples/AutoResearch/AutoResearchRemoteDriverMethods.cpp
- objectfled_spi_show: accept fl::span<const u8> instead of split
  (const u8*, u32) pair to match coding-guideline span convention
  for new header APIs (CR comment 3486713436).
- Update lone caller in examples/AutoResearch to construct the span
  in-place; add explicit fl/stl/span.h include.
- Rename file-static SPI state (sSpi* -> sOfSpi*, kSpi* -> kOfSpi*,
  objectfled_spi_dma_isr -> of_spi_dma_isr, objectfled_spi_program_qtimer
  -> of_spi_program_qtimer) to avoid potential collision with the
  flexio_spi_mode translation unit's sSpi* state, matching the
  per-driver-prefix convention already used elsewhere.

CR comments 3486713434 (getCapabilities header-discipline) and
3486857209 (DMA cleanup race) were already addressed in earlier
commits on this branch; CodeRabbit acknowledged both inline.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees merged commit 2e89cca into master Jun 28, 2026
18 of 22 checks passed
zackees added a commit that referenced this pull request Jun 28, 2026
…ace refactor

The `sOfSpi*` / `kOfSpi*` / `of_spi_*` prefix rename of file-static state in
this TU exists to avoid name collisions with the sibling
`flexio_spi_mode.cpp.hpp` TU in the unity build (`fl/build/platforms+.cpp`).
Both files would otherwise define `static ... sSpiCurrentPins`, etc., at
fl:: namespace scope -- a redefinition error.

User directive 2026-06-27 ("when in doubt use private namespaces") is
honored as a follow-up: a planned refactor wraps BOTH drivers' internals
in matching private namespaces (`fl::detail::flexio_spi_internal` and
`fl::detail::objectfled_spi_internal`) so neither needs the prefix. The
single-driver `using namespace detail::xxx_spi_internal;` approach was
tried first but causes lookup ambiguity at use-time in the unity TU
because the sibling driver's identically-named statics at `fl::` scope
shadow-collide.

No code change; documentation only.

Refs #3428, #3432.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 28, 2026
zackees added a commit that referenced this pull request Jun 28, 2026
… (no prefix) (#3434)

Per user directive 2026-06-27 "when in doubt use private namespaces" --
follow-up cleanup for the prefix-rename workaround that landed with
#3431 / #3432.

Both `flexio_spi_mode.cpp.hpp` and `objectfled_spi_mode.cpp.hpp` now wrap
their file-static state + private helpers in matching named namespaces:

  - fl::detail::flexio_spi_internal
  - fl::detail::objectfled_spi_internal

Each public API function (those in the .h header) opens with
`using namespace detail::xxx_spi_internal;` so the bodies reference the
private state without the namespace prefix. The two drivers' identically-
named symbols (sSpiCurrentPins, sSpiDmaChannel, ...) now live in
different namespaces, so they don't collide in the unity build
(fl/build/platforms+.cpp).

The ObjectFLED side drops the `sOfSpi*` / `kOfSpi*` / `of_spi_*` prefix
that was the previous workaround for the unity-build collision -- the
private namespace handles it cleanly now.

Hardware-verified on Teensy 4.1 (COM20) after the refactor:
  - flexioSpiSelfTest:    3/3 pass (wait_ms=0)
  - objectfledSpiSelfTest: 3/3 pass (wait_ms=5 = drain only)

Build / lint clean (bash test --cpp / bash lint / bash compile teensy41).

Refs #3428, #3431, #3432.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

1 participant