Skip to content

fix(flexio): pin mux offsets + timing bugs -- TX now alive on Teensy 4.x - #3415

Merged
zackees merged 4 commits into
masterfrom
fix/flexio-timcmp-trgpol-round7
Jun 26, 2026
Merged

zackees merged 4 commits into
masterfrom
fix/flexio-timcmp-trgpol-round7

Conversation

@zackees

@zackees zackees commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

Summary

After six rounds of FlexIO bring-up on Teensy 4.x (#3410) producing zero_capture (silent wire) and one Round-6 register-comparison audit, the actual root cause of the silence was finally found: every entry in kFlexIOPins had its IOMUXC mux+pad offsets shifted +0x10 from the real register addresses. Cross-checked against Teensyduino's IOMUXC_SW_MUX_CTL_PAD_GPIO_B*_** macros in imxrt.h. The requested TX pin was never being switched to ALT4 (FlexIO2); the FlexIO shifter and DMA ran correctly the whole time but drove an unrouted internal signal.

Round 7 also fixes four real timing/encoding bugs that would have masked the mux fix even once it was corrected, cross-referenced against Teensyduino's verified-working FlexSerial UART driver:

  • TIMCMP bit-count was 31, should be 63. Per RM 47.4.18, number of bits per word = (CMP[15:8] + 1) / 2. Old value emitted only 16 of the 32 pre-encoded FlexIO bits per word.
  • TIMCTL missing TRGPOL bit 23. Trigger needs to be active-low so it asserts when the shifter-status-flag is LOW (shifter loaded with data).
  • TIMENA was 6 (rising-edge) instead of 2 (level-high). FlexSerial uses level-high; level is the correct fit for our continuous shift loop.
  • CTRL had FASTACC set (bit 2). FASTACC requires FlexIO clock ≥ 2× bus clock; we have 120 MHz FlexIO vs 600 MHz bus, so FASTACC=1 silently corrupts register accesses.

This PR also wires a new flexio_read_diagnostics() snapshot into the autoresearch RPC response so future bring-up can see real FlexIO register state (CTRL, SHIFTSTAT, TIMSTAT, SHIFTSDEN, TCD, IOMUXC mux/pad) without a logic analyzer. This is the diagnostic that surfaced the mux bug after six rounds of guesswork.

State after this PR

  • Wire is alive
  • RX captures 300/300 bytes on every frame (was 0/300 across all 6 prior rounds)
  • Decoder runs to completion with non-empty output
  • Residual byte corruption is now a bit-phase alignment issue at frame start rather than total silence, and is tractable as a follow-up

Test plan

Refs #3410

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added a FlexIO2 register diagnostics section to single-test output for Teensy 4.x.
    • Added a public FlexIO2 diagnostics snapshot (registers, DMA bookkeeping, completion/initialized flags) for bring-up and troubleshooting.
  • Bug Fixes
    • Corrected Teensy 4.x FlexIO2 pin routing/muxing to improve reliable mode entry.
    • Improved WS2812 waveform generation, including byte/bit mapping and frame-start behavior.
    • Refined FlexIO/DMA start sequencing and timing alignment to prevent shifter/DMA phase misbehavior.

Six rounds of FlexIO bring-up against #3410 failed with zero_capture
because of a 0x10 offset error in every entry of kFlexIOPins. The
table values were 16 bytes higher than the real IOMUXC mux/pad
register addresses (cross-checked against Teensyduino's
IOMUXC_SW_MUX_CTL_PAD_GPIO_B*_** macros). The requested TX pin was
never actually switched to ALT4 (FlexIO2); FlexIO shifter and DMA ran
correctly but drove an unrouted internal signal.

Round 7 also fixes four real timing/encoding bugs that would have
masked the mux fix:

1. TIMCMP bit-count was 31 (16 bits per word); per RM 47.4.18 the
   formula is (CMP[15:8]+1)/2, so 32 bits requires 63. The old value
   emitted only half the pre-encoded bits.
2. TIMCTL was missing TRGPOL bit 23 -- trigger needs to be active-low
   so it asserts when SSF is LOW (shifter loaded). Without it the
   timer-enable polarity was inverted.
3. TIMENA was 6 (rising-edge) instead of 2 (level-high), matching the
   verified-working Teensyduino FlexSerial UART driver.
4. CTRL had FASTACC set (bit 2). FASTACC requires FlexIO clock >= 2x
   bus clock; we run FlexIO 120 MHz vs 600 MHz bus, so FASTACC=1
   would corrupt register reads/writes.

Also added flexio_read_diagnostics() and wired it into the
autoresearch RPC harness so future investigation can see real
register state (CTRL, SHIFTSTAT, TIMSTAT, SHIFTSDEN, TCD,
IOMUXC mux/pad) without a logic analyzer -- this is what surfaced
the mux bug.

State after this change: wire is alive, RX captures 300/300 bytes
on every frame, decoder produces non-empty results. Residual byte
corruption (~75%) is now a bit-phase alignment issue at frame start
rather than total silence, and is tractable to follow up.

Refs #3410
@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 29737ec6-9f69-4aec-ba63-b0df48aea979

📥 Commits

Reviewing files that changed from the base of the PR and between b7dfa3f and 2a37f43.

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

📝 Walkthrough

Walkthrough

Teensy 4.x FlexIO2 waveform generation is updated with new pin mapping, timer setup, bit encoding, and enable sequencing. The PR also adds a diagnostics snapshot API and exposes it through the AutoResearch single-test response and diagnostics printer.

Changes

Teensy 4.x FlexIO waveform and diagnostics

Layer / File(s) Summary
Waveform generation and start sequence
src/platforms/arm/teensy/.../flexio_driver.cpp.hpp
The FlexIO2 pin table, pin state retention, pad configuration, Timer 0 setup, WS2812 bit expansion, and FlexIO enable sequence are updated together.
Diagnostics snapshot and reporting
src/platforms/arm/teensy/.../flexio_driver.h, src/platforms/arm/teensy/.../flexio_driver.cpp.hpp, examples/AutoResearch/AutoResearchRemoteRunSingleTest.cpp, ci/autoresearch/context.py
A new FlexIODiagnostics snapshot and reader are added, then serialized in the Teensy 4.x RPC response and printed when flexIoDiagnostics is present.

Sequence Diagram(s)

sequenceDiagram
  participant AutoResearchRemoteRunSingleTest
  participant flexio_read_diagnostics
  participant display_objectfled_diagnostics
  AutoResearchRemoteRunSingleTest->>flexio_read_diagnostics: capture FlexIODiagnostics
  flexio_read_diagnostics-->>AutoResearchRemoteRunSingleTest: populated register snapshot
  AutoResearchRemoteRunSingleTest->>display_objectfled_diagnostics: provide flexIoDiagnostics
  display_objectfled_diagnostics->>display_objectfled_diagnostics: print FlexIO2 register diagnostics
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#3217: Extends the same Teensy 4 single-test response path that now serializes flexIoDiagnostics.
  • FastLED/FastLED#3358: Updates the same RPC response construction flow in AutoResearchRemoteRunSingleTest.cpp.
  • FastLED/FastLED#3405: Modifies the same diagnostics display path that now prints the FlexIO2 register section.

Poem

I hopped through wires at dawn so bright,
FlexIO hummed in tidy light.
I nosed the registers, neat and grand,
Then tapped out diagnostics by paw and hand.
🐇✨ The LEDs danced right back to life.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.46% 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 accurately summarizes the main FlexIO bring-up fixes on Teensy 4.x, especially the pin mux and timing corrections.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/flexio-timcmp-trgpol-round7

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: 1

🤖 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/flexio/flexio_driver.cpp.hpp`:
- Around line 473-500: flexio_read_diagnostics currently snapshots FLEXIO2
registers before checking whether FlexIO is initialized, which can trigger
unsafe peripheral access on uninitialized Teensy 4.x runs. Update
flexio_read_diagnostics in flexio_driver.cpp.hpp to zero-initialize the
FlexIODiagnostics output, record only the always-safe CCM/state fields first,
and gate all FLEXIO2_* register reads plus pin mux/pad access behind the
existing sInitialized/clocked state check so the function returns a safe
snapshot when FlexIO has not been brought up.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: b5adfc72-974d-48b7-9169-290e1d3dedf5

📥 Commits

Reviewing files that changed from the base of the PR and between 9574ac9 and a83b92e.

📒 Files selected for processing (4)
  • ci/autoresearch/context.py
  • examples/AutoResearch/AutoResearchRemoteRunSingleTest.cpp
  • src/platforms/arm/teensy/teensy4_common/drivers/flexio/flexio_driver.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/drivers/flexio/flexio_driver.h

zackees added 3 commits June 26, 2026 00:36
After Round 7's mux + timing fixes, the FlexIO TX wire was alive and
the receiver captured 300/300 bytes per frame, but ~75% of bytes
decoded incorrectly. The pattern was a consistent 1-bit left-shift
across each frame: byte_1 = 0xFE for expected 0xFF, byte_n's bits
shifted into byte_n+1's MSB, etc.

Root cause: between flexio_show() calls the FlexIO peripheral leaves
the line in an indeterminate state -- the receiver consistently
captured a long HIGH (~85 us) before the first valid edge of every
frame. The shared WS2812 edge decoder
(fl::channels::rx::decodeWs2812Edges) treats that long HIGH as an
invalid edge-pair (high_ns way out of T0H/T1H range, low_ns below
reset threshold) and silently advances past it -- consuming the
FIRST WS2812 bit of the new frame in the process. Every subsequent
byte then appears bit-shifted by one position.

Fix: before re-asserting FLEXEN at the top of flexio_show(), switch
the pad mux to ALT5 (GPIO), drive the pin LOW via the Teensyduino
fast-GPIO path, wait 60 us so the receiver settles on a clean LOW
idle, then restore ALT4 | SION. The first FlexIO-driven edge after
that is now an unambiguous rising edge that decodes cleanly as the
first data bit.

Aggregate byte corruption dropped from 77.8% to 0.8% (10/1200 bytes
across 4 patterns). Residual errors are scattered single-bit issues
at random LED positions (LED[0], LED[7], LED[36], LED[51], LED[58]
etc) -- the raw_sample diagnostic shows clear receiver-side capture
glitches like double-H edges with no intervening LOW and ~200 us
mid-frame HIGH gaps. Comparable noise floor to ObjectFLED's residual
~0.5% rate on the same RX path.

Refs #3410
Add FL_FLEXIO_TX_DSE and FL_FLEXIO_TX_SPEED defines so hardware-
specific drive strength tuning can be done without editing the
driver. The default DSE=3 was empirically the best on the bench
loopback rig (Teensy 4.1 pin 8 -> pin 22, short jumper) at 0.8%
residual byte corruption; sweeping DSE=1/3/6 converged to the same
RX-side noise floor (the residual errors are FlexPWM capture
dropout visible as ~200 us mid-frame HIGH gaps in raw_sample, not
edge ringing). The override is still useful on different boards or
longer wires where edge integrity does become the limit.
CodeRabbit flagged that flexio_read_diagnostics() read FLEXIO2_*
registers unconditionally, but the new autoresearch RPC path now
calls it for every Teensy 4.x test -- including runs that never
bring FlexIO up. Without the CCM clock gate on and FLEXEN set at
least once, those reads hit the same IMPRECISERR class fault we
chased during bring-up (#3411, #3412).

Zero-fill the snapshot, populate the always-safe CCM/state fields,
and bail before touching the FLEXIO2_* block when !sInitialized.
@zackees
zackees merged commit ec8eb88 into master Jun 26, 2026
7 of 11 checks passed
@zackees
zackees deleted the fix/flexio-timcmp-trgpol-round7 branch June 26, 2026 15:38
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 26, 2026
zackees added a commit that referenced this pull request Jun 27, 2026
Resolves intermittent ~55s RPC timeout on Teensy 4 clockless tests
(LPUART, FlexIO, ObjectFLED autoresearch) when the test framework's
RPC ASYNC handler wraps execution in `fl::ScopedLogDisable`.

Root cause (marker-narrowed across this session):
`FL_WARN(...)` macro ALWAYS constructs `fl::sstream() << X` regardless
of log level -- `ScopedLogDisable` only suppresses OUTPUT inside
`log_emit`. The cumulative `fl::sstream`/`fl::string` heap alloc/free
cycles across this file's many FL_WARN sites (banner, per-run dump,
per-pattern hex dump, summary, OVERALL pass/fail) leave the Teensy 4
heap in a state where the function-exit destructor of a heap-backed
`fl::string` hangs indefinitely -- traced via Serial.println markers
to the `fl::variant<NotNullStringHolderPtr, ...>` destructor in
fl::sstream::~fl::sstream() at the close of runMultiTest.

Reproduction: ~80% of LPUART/FlexIO/ObjectFLED runs hung at exactly
`mt_pre_inner_close` marker → no `mt_dtors_done` → no
`art_after_multitest` → ~55s host timeout.

Fix: introduce `AR_FL_WARN` / `AR_FL_ERROR` macros that check
`fl::getLogLevel()` before expanding FL_WARN -- when under
ScopedLogDisable (level=NONE), the sstream is never constructed and
the heap stays clean. Sed-swept all 73 FL_WARN sites in
AutoResearchTest.cpp and 8 sites in AutoResearchHelpers.cpp.

Also gates `flexIoDiagnostics` / `flexPwmRxDiagnostics` JSON emit
to OBJECT_FLED only (their original #3343/#3410 purpose). LPUART
and FLEX_IO no longer carry that ~660-byte / 22-field JSON payload
that further compounds the heap pressure post-test.

Results (bench rig, Teensy 4.0, --lpuart --tx-pin 8 --rx-pin 22):
- LPUART:  1/5 baseline → 5/5 success (clean 0.3-2.0% noise floor)
- FlexIO:  0/5 baseline → 1-2/5 success (intermittent residual --
           likely additional heap pressure outside this file; not
           blocking since FlexIO landed via #3415 prior)
- LPUART tests now return reliable byte-corruption reports
  matching FlexIO/ObjectFLED noise floor, confirming the LPUART
  driver itself works correctly when the framework returns.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 27, 2026
… + LPUART polish (#3423)

* feat(lpuart): wave8 encoder + Teensy 4.x real driver + host unit tests

Adds Bus::LPUART workstream A from #3023:

- src/.../drivers/lpuart/lpuart_encoder.h: header-only WS2812 -> UART
  byte encoder. 2 WS2812 bits per UART byte using TXINV semantics.
  Wire pattern per bit at 4 Mbps:
    '0' -> H L L L L  (250 ns + 1000 ns)
    '1' -> H H H L L  (750 ns + 500 ns)
  Pair-to-byte table: (0,0)->0xEF, (0,1)->0x8F, (1,0)->0xEC, (1,1)->0x8C.
- src/.../drivers/lpuart/lpuart_driver.{h,cpp.hpp}: Teensy 4.x real
  driver. Configures LPUARTn for 4 Mbps with TXINV + TDMAE, programs
  the IOMUXC pad to ALT2 + SION, allocates a 4 KB DMAMEM buffer, and
  drives eDMA from the encoded byte stream to LPUARTn_DATA.
- src/.../drivers/lpuart/lpuart_peripheral_real.cpp.hpp: ILPUARTPeripheral
  factory for Teensy 4.x. Wraps the procedural driver in the existing
  ILPUARTInstance interface that the mock in
  src/platforms/shared/mock/arm/teensy4/drivers/lpuart/ already targets.
- tests/.../drivers/lpuart/lpuart_encoder.cpp: 8 host-side unit tests
  covering all-zeros, all-ones, MSB-first ordering, palindromic
  patterns, the pair-byte table, and the wire-format invariant.

Verified:
- bash test ilpuart_peripheral: existing mock interface tests pass
- bash test lpuart_encoder: 8/8 encoder tests pass on host
- bash compile teensy40 --examples Blink: clean build on T4.0 with
  the new driver in the unity build path

Pin map (T4.0): pin 1/8/14/17/20/24/29 map to LPUART6/4/2/3/8/1/7
TX respectively. Bench-rig pin 8 reuses the existing FlexIO/ObjectFLED
loopback jumper to FlexPWM-RX pin 22.

Refs #3023

* feat(lpuart): channel engine + BusTraits registration

Add the high-level ChannelEngineLPUART (mirrors ChannelEngineFlexIO)
plus a BusTraits<Bus::LPUART> specialisation so Bus::LPUART routes
through the real Teensy 4.x driver.

- channel_engine_lpuart.{h,cpp.hpp}: engine creates one ILPUARTInstance
  per (pin, strip-length) combination, encodes raw WS2812 bytes into
  the instance buffer using lpuart_encode_byte(), and calls
  instance->show().
- bus_traits.h: standard registerWithManager() pattern.
- lpuart_driver: add lpuart_show_encoded() for callers (the engine)
  that pre-encode externally; refactor common TCD arming into
  lpuart_arm_dma().
- bus_priorities.h: Bus::LPUART defaults to priority 1 (same as FlexIO
  and ObjectFLED).

Teensy 4.0 AutoResearch builds clean. Hardware test next.

* debug(lpuart): polled-tx diagnostic confirms LPUART4 transmits

Hardware bring-up progress on Teensy 4.0:
- Init sequence runs cleanly: clock gate, BAUD config, FIFO+CTRL,
  pin mux + IOMUXC SELECT_INPUT daisy.
- LPUART4 STAT = 0xC00000 after configure -> TC+TDRE both set,
  transmitter is alive.
- Polled writes successfully push 1200 wave8 UART bytes in 10 ms
  (= ~120 kbps actual due to per-byte STAT-polling overhead, well
  short of the 4 Mbps the BAUD divisor targets but proves the
  hardware path works).
- DMA arming sequence currently never sees the major-loop ISR fire;
  next iteration adds DMA_ES + CITER snapshots to diagnose whether
  TDMAE is being honored.

Also wires --lpuart through the autoresearch driver dispatcher and
enables Bus::LPUART in the Teensy 4.x enableAllChannelDrivers list.

Hardware test reproducible: bash autoresearch teensy40 --lpuart
--tx-pin 8 --rx-pin 22 reaches LPUART firmware and emits bytes on
pin 8 (polled path). Full WS2812-rate DMA path is the remaining
work.

* feat(lpuart): hardware-verified DMA path on Teensy 4.0

Working LPUART driver path bring-up:
- Force CCM_CSCDR1 UART_CLK_SEL=PLL3_80M / UART_CLK_PODF=1 so the
  LPUART clock is 80 MHz regardless of what the Teensyduino boot
  state left CSCDR1 at. Empirical: post-boot the LPUART clock was
  24 MHz, making OSR=4/SBR=4 produce ~1.2 Mbps instead of 4 Mbps.
- Move triggerAtHardwareEvent() + attachInterrupt() out of the
  per-show arm path into lpuart_dma_init() (set once at init).
- Add LPUART transmit-complete (STAT.TC) wait after the DMA major-
  loop ISR fires, so the final byte fully drains through the FIFO
  + shift register before show_encoded() returns.

Hardware verification (bench loopback, Teensy 4.0 pin 8 -> pin 22
via FlexPWM4_SM0_A RX):

  raw_sample: H753 L499 H746 L499 H753 L499 ... H253 L999 H246 L999
  -> exactly matches wave8 4-Mbps encoding:
       '1' bit = ~750 ns HIGH + ~500 ns LOW
       '0' bit = ~250 ns HIGH + ~1000 ns LOW
  -> Byte corruption: 1.4% (17/1200) on the first 4-pattern frame
     -- matches the FlexIO/ObjectFLED noise floor on the same rig.

DMA progression confirmed via CITER snapshots (in earlier diagnostic
revs): CITER decrements smoothly from BITER=1200 to 0 within ~3 ms
at 4 Mbps, then the major-loop ISR fires and resets CITER back to
BITER and sets sLpDmaComplete = true.

Still TODO: the autoresearch RPC sometimes times out after 2 TX
frames before the test framework collects results. The TX driver
itself completes cleanly each time -- the hang is in the test
harness's between-pattern handoff, not in the LPUART path.

* fix(lpuart): refactor engine, ws2812b-v5 reset=150us, add yield()

- Replace function-local static CachedInstance with proper member
  state (mInstance, mCurrentPin, mCurrentRawBytes, mCurrentTiming)
  mirroring ChannelEngineFlexIO's per-engine cache pattern.
- Add yield() after each show() so the USB-CDC RPC stack can flush
  responses; without it the autoresearch test pipeline stalls.
- Per user note: ws2812b-v5 datasheet specifies 150 us reset/latch,
  not the 280 us we had hard-coded. Update TIMING_WS2812B_MINI_V3
  (which TIMING_WS2812B_V5 aliases). The longer 280 us was a
  conservative carry-over from older WS2812 variants.

* fix(lpuart): audit pin map against Teensyduino HardwareSerial sources

Audited every entry in kLpuartPins[] against the matching
UARTn_Hardware struct in Teensyduino's HardwareSerial[1-7].cpp and
the IOMUXC_SW_MUX_CTL_PAD_GPIO_* offsets in imxrt.h. Found 6 of 7
entries had wrong mux_offset/pad_offset/select_input_value -- only
pin 8 was correct, which is why the bench rig works there but other
pins would have silently driven the wrong pad.

Corrected (all entries verified for Teensy 4.0):
  pin  1 -> LPUART6 TX, GPIO_AD_B0_12 (mux 0x0EC),  SELECT_INPUT=1
  pin  8 -> LPUART4 TX, GPIO_B1_00    (mux 0x17C),  SELECT_INPUT=2
  pin 14 -> LPUART2 TX, GPIO_AD_B1_02 (mux 0x104),  SELECT_INPUT=1
  pin 17 -> LPUART3 TX, GPIO_AD_B1_06 (mux 0x114),  SELECT_INPUT=0
  pin 20 -> LPUART8 TX, GPIO_AD_B1_10 (mux 0x124),  SELECT_INPUT=1
  pin 24 -> LPUART1 TX, GPIO_AD_B0_13 (mux 0x0F0),  no SELECT_INPUT
  pin 29 -> LPUART7 TX, GPIO_EMC_31   (mux 0x090),  SELECT_INPUT=1

Also revert WS2812B_V5 RESET back to 280 us per user follow-up.

Strip debug Serial.printf from engine + driver. Engine kept member-
state refactor (mInstance/mCurrentPin/mCurrentRawBytes) + yield()
after show.

Hardware status: bench rig with pin 8 LPUART loopback to pin 22
FlexPWM RX intermittently completes the 4-pattern test at the
~1% byte corruption noise floor matching FlexIO/ObjectFLED. Some
runs RPC-timeout downstream of the engine show() -- the LPUART TX
itself completes cleanly each time per the diagnostic snapshots.

* fix(autoresearch): LPUART takes the UART-decode path

In examples/AutoResearch/AutoResearchTest.cpp `is_uart_driver` was
narrowly checking `driver_name == "UART"`. The LPUART driver
emits a wave8-encoded 4 Mbps signal whose wire shape is functionally
identical to the existing UART path -- T0H=250 ns, T1H=750 ns,
T1L=500 ns -- so it should take the same decode branch (UART-specific
timing thresholds, 500 ms RX wait, gap_tolerance_ns=100us). Expand
the check to also match LPUART.

* fix(lpuart): address CodeRabbit review on PR #3421

5 actionable findings:

- bus_traits.h: move BusTraits<Bus::LPUART>::instancePtr() function-
  local static `gHolder` out of the header into the .cpp.hpp TU
  (per repo's no-static-in-headers rule).
- channel_engine_lpuart.h: move getName() / getCapabilities() bodies
  out of the header into the .cpp.hpp.
- channel_engine_lpuart.cpp.hpp: clear mHwInitialized/mCurrentPin/
  mCurrentRawBytes BEFORE attempting createInstance() so a failed
  create leaves the engine in a clean re-init-required state instead
  of a half-torn-down state that the next channel could inherit.
- lpuart_driver.cpp.hpp: honour reset_us. Record the previous
  frame's end-of-TC micros and stall the next show until reset_us
  has elapsed -- contractual fix per the public docstring.
- ci/autoresearch/args.py: pin-to-LPUART mapping is board-dependent
  (T4.0 vs T4.1), don't hard-code "pin 8 -> LPUART4" in help text.

Remaining CodeRabbit MAJOR finding (pin map missing pins 35/47/48
per kLPUARTTxPins contract) is T4.1-only / SD-bottom-pad coverage,
deferred to follow-up.

Verified: teensy40 AutoResearch builds clean, lpuart_encoder host
tests still 1/1 pass.

* fix(lpuart): Bus::UART specialization + remaining CodeRabbit fixes

Per user feedback:
- BusTraits<Bus::UART> specialised for Teensy 4.x to route through
  ChannelEngineLPUART. This matches the ESP32 pattern where Bus::UART
  binds to that platform's UART hardware; sketches that name
  Bus::UART work portably across both platforms.
- Bus::LPUART kept as an alias resolving to the same singleton
  instance so code that names the hardware directly still works.

CodeRabbit-flagged fixes:
- lpuart_encoder.h: replace `u8*` with `fl::span<u8, 4>` (static-
  extent span) so the 4-byte-output contract is checked at the type
  level. Call sites use `fl::span<u8, 4>{&buf[i*4], 4}`.
- lpuart_driver.cpp.hpp: reject oversize transfers instead of
  silently truncating them (was logging + truncating + returning
  success, leaving tail LEDs stale).
- lpuart_peripheral_real.cpp.hpp: return nullptr from createInstance
  if hardware init failed inside the constructor, instead of handing
  back a non-functional instance that would silently drop frames.
  Switch mTxBuffer from raw `new[]`/`delete[]` to
  `fl::unique_ptr<u8[]>` RAII.

Verified: bash test lpuart_encoder 8/8 pass; bash compile teensy40
AutoResearch clean.

* fix(lpuart): lint cleanup + single Bus::UART registration

- channel_drivers_teensy.impl.hpp: register only Bus::UART (not both
  Bus::UART and Bus::LPUART). Both resolve to the same singleton via
  the trait alias in bus_traits.h, so registering both was triggering
  the ChannelManager replace-driver path on every boot.

- lpuart_encoder.h: add IWYU pragma: private + FL_NO_EXCEPT on the
  two inline encode helpers.

- lpuart_driver.cpp.hpp: suppress BareAllocationChecker on the
  DMAChannel new/delete pair (Teensyduino DMAChannel has no
  fl smart-pointer factory).

- _build.cpp.hpp: alphabetize unity build includes (channel_engine
  before lpuart_*).

- flexio_driver.cpp.hpp: use FL_STATIC_ASSERT instead of raw
  static_assert per BannedMacrosChecker.

- third_party/object_fled/src/_build.cpp.hpp: alphabetize (ObjectFLED
  before ObjectFLEDDmaManager).

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

* fix(lpuart): per-pin mux_alt + audited T4.1 entries + trim JSON-RPC

Pin map audit (per user's "Audit pin map against every Teensyduino
HardwareSerial*.cpp" blocker):
- Cross-referenced every kLpuartPins entry against the corresponding
  HardwareSerial[1-8].cpp UARTn_Hardware struct's {pin, mux_val,
  select_input_reg, select_input_value} 4-tuple.
- Added per-entry mux_alt field so the T4.1 LPUART5_TX (pin 35,
  ALT 1, not 2) doesn't get force-driven through the wrong alt.
- Added T4.1-only entries (pins 35, 47, 53) gated on
  ARDUINO_TEENSY41. Verified IOMUXC offsets against imxrt.h.
- Corrected the kLPUARTTxPins public contract: the original list
  included pin 48 (which is actually LPUART5_RX_ALT on T4.1, not
  a TX pin) and was missing pin 53 (the real T4.1 LPUART6_TX_ALT).
  Fixed list is {1, 8, 14, 17, 20, 24, 29, 35, 47, 53}.

JSON-RPC minimization (per user "json-rpc should be kept to the
minimal possible without excessive spam"):
- runSingleTestImpl: skip flexPwmRxDiagnostics and flexIoDiagnostics
  emit for LPUART tests. Both are FlexIO/FlexPWM register snapshots
  that surface nothing LPUART-relevant; LPUART status already lives
  in lpuart_read_diagnostics. Trims ~660 bytes of JSON per response.
- ScopedLogDisable scope: kept enabled for all drivers including
  LPUART (per-driver carve-out empirically worsened hangs to 0/3
  due to USB-CDC saturation from FL_WARN spam during the 4-pattern
  loop).

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

* fix(autoresearch): gate FL_WARN sstream construction on log level

Resolves intermittent ~55s RPC timeout on Teensy 4 clockless tests
(LPUART, FlexIO, ObjectFLED autoresearch) when the test framework's
RPC ASYNC handler wraps execution in `fl::ScopedLogDisable`.

Root cause (marker-narrowed across this session):
`FL_WARN(...)` macro ALWAYS constructs `fl::sstream() << X` regardless
of log level -- `ScopedLogDisable` only suppresses OUTPUT inside
`log_emit`. The cumulative `fl::sstream`/`fl::string` heap alloc/free
cycles across this file's many FL_WARN sites (banner, per-run dump,
per-pattern hex dump, summary, OVERALL pass/fail) leave the Teensy 4
heap in a state where the function-exit destructor of a heap-backed
`fl::string` hangs indefinitely -- traced via Serial.println markers
to the `fl::variant<NotNullStringHolderPtr, ...>` destructor in
fl::sstream::~fl::sstream() at the close of runMultiTest.

Reproduction: ~80% of LPUART/FlexIO/ObjectFLED runs hung at exactly
`mt_pre_inner_close` marker → no `mt_dtors_done` → no
`art_after_multitest` → ~55s host timeout.

Fix: introduce `AR_FL_WARN` / `AR_FL_ERROR` macros that check
`fl::getLogLevel()` before expanding FL_WARN -- when under
ScopedLogDisable (level=NONE), the sstream is never constructed and
the heap stays clean. Sed-swept all 73 FL_WARN sites in
AutoResearchTest.cpp and 8 sites in AutoResearchHelpers.cpp.

Also gates `flexIoDiagnostics` / `flexPwmRxDiagnostics` JSON emit
to OBJECT_FLED only (their original #3343/#3410 purpose). LPUART
and FLEX_IO no longer carry that ~660-byte / 22-field JSON payload
that further compounds the heap pressure post-test.

Results (bench rig, Teensy 4.0, --lpuart --tx-pin 8 --rx-pin 22):
- LPUART:  1/5 baseline → 5/5 success (clean 0.3-2.0% noise floor)
- FlexIO:  0/5 baseline → 1-2/5 success (intermittent residual --
           likely additional heap pressure outside this file; not
           blocking since FlexIO landed via #3415 prior)
- LPUART tests now return reliable byte-corruption reports
  matching FlexIO/ObjectFLED noise floor, confirming the LPUART
  driver itself works correctly when the framework returns.

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

* fix(arduino/io): ride out Teensy 4 USB-CDC DTR debounce in fl::print(ln)

Per /goal "USB-CDC DTR race" research follow-up.

Teensy 4 `Serial.operator bool()` (usb_serial.h:166-169) returns
false for a hard-coded 15ms after every DTR transition (line
discipline settle window). Without a retry on the device side, the
first messages emitted by the device after a host re-opens the
serial port are silently dropped -- the `if (!Serial) return;`
guard in fl::print/fl::println short-circuits before the debounce
clears.

Reproduction surface: autoresearch RPC reconnects for each new test
session (close → re-open). Device output during the first ~15ms
after re-open vanishes -- visible as "missing log lines between
RPC sessions" or "first FL_WARN after reconnect never arrives".

Fix: extract a small `waitForSerialReady_DtrSettle()` helper that:
  - Fast-paths the common case (Serial already true → no wait)
  - Otherwise yields in a bounded 30ms loop (2× the Teensy 4
    debounce) waiting for `Serial.operator bool()` to settle true
  - Drops the message after 30ms if host is genuinely absent

On non-Teensy Arduino platforms `Serial.operator bool()` either
always returns true (real UART) or has its own non-blocking drop
path (ESP32 HWCDC: setTxTimeoutMs(0) applied by fl::begin()), so
the 30ms bound is invisible there.

Cross-platform compile verified: teensy40 ✓, esp32dev ✓, uno ✓.
Lint clean. 338/338 tests pass.

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

* fix(arduino/io): extend DTR settle wait to fl::flush + fl::serial_ready

Follow-up to 6c2d12e. The DTR debounce race window doesn't only
affect fl::print/fl::println -- fl::flush and fl::serial_ready use
the same `if (!Serial) return ...` short-circuit pattern, and would
also report "host absent" during the first ~15ms after a host
re-opens the USB-CDC port on Teensy 4.

Wire both through the same `waitForSerialReady_DtrSettle()` helper
so the device-side host-presence view stays consistent across all
three paths: print, flush, and the explicit ready-check.

`fl::write_bytes` is intentionally left untouched -- it does not
gate on `Serial`, so the underlying `Serial.write` path drives its
own back-pressure / drop semantics (Teensy 4 usb_serial_write has
its own 120ms tx-buffer-wait timeout). LPC platforms are also
intentionally left untouched -- their Arduino-core USB-VCOM bridge
has different debounce semantics that aren't documented to need
the same window.

Cross-platform compile: teensy40 ✓, esp32dev ✓.
Lint clean. 338/338 tests pass.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 27, 2026
…3296) (#3424)

* feat(lpuart): wave8 encoder + Teensy 4.x real driver + host unit tests

Adds Bus::LPUART workstream A from #3023:

- src/.../drivers/lpuart/lpuart_encoder.h: header-only WS2812 -> UART
  byte encoder. 2 WS2812 bits per UART byte using TXINV semantics.
  Wire pattern per bit at 4 Mbps:
    '0' -> H L L L L  (250 ns + 1000 ns)
    '1' -> H H H L L  (750 ns + 500 ns)
  Pair-to-byte table: (0,0)->0xEF, (0,1)->0x8F, (1,0)->0xEC, (1,1)->0x8C.
- src/.../drivers/lpuart/lpuart_driver.{h,cpp.hpp}: Teensy 4.x real
  driver. Configures LPUARTn for 4 Mbps with TXINV + TDMAE, programs
  the IOMUXC pad to ALT2 + SION, allocates a 4 KB DMAMEM buffer, and
  drives eDMA from the encoded byte stream to LPUARTn_DATA.
- src/.../drivers/lpuart/lpuart_peripheral_real.cpp.hpp: ILPUARTPeripheral
  factory for Teensy 4.x. Wraps the procedural driver in the existing
  ILPUARTInstance interface that the mock in
  src/platforms/shared/mock/arm/teensy4/drivers/lpuart/ already targets.
- tests/.../drivers/lpuart/lpuart_encoder.cpp: 8 host-side unit tests
  covering all-zeros, all-ones, MSB-first ordering, palindromic
  patterns, the pair-byte table, and the wire-format invariant.

Verified:
- bash test ilpuart_peripheral: existing mock interface tests pass
- bash test lpuart_encoder: 8/8 encoder tests pass on host
- bash compile teensy40 --examples Blink: clean build on T4.0 with
  the new driver in the unity build path

Pin map (T4.0): pin 1/8/14/17/20/24/29 map to LPUART6/4/2/3/8/1/7
TX respectively. Bench-rig pin 8 reuses the existing FlexIO/ObjectFLED
loopback jumper to FlexPWM-RX pin 22.

Refs #3023

* feat(lpuart): channel engine + BusTraits registration

Add the high-level ChannelEngineLPUART (mirrors ChannelEngineFlexIO)
plus a BusTraits<Bus::LPUART> specialisation so Bus::LPUART routes
through the real Teensy 4.x driver.

- channel_engine_lpuart.{h,cpp.hpp}: engine creates one ILPUARTInstance
  per (pin, strip-length) combination, encodes raw WS2812 bytes into
  the instance buffer using lpuart_encode_byte(), and calls
  instance->show().
- bus_traits.h: standard registerWithManager() pattern.
- lpuart_driver: add lpuart_show_encoded() for callers (the engine)
  that pre-encode externally; refactor common TCD arming into
  lpuart_arm_dma().
- bus_priorities.h: Bus::LPUART defaults to priority 1 (same as FlexIO
  and ObjectFLED).

Teensy 4.0 AutoResearch builds clean. Hardware test next.

* debug(lpuart): polled-tx diagnostic confirms LPUART4 transmits

Hardware bring-up progress on Teensy 4.0:
- Init sequence runs cleanly: clock gate, BAUD config, FIFO+CTRL,
  pin mux + IOMUXC SELECT_INPUT daisy.
- LPUART4 STAT = 0xC00000 after configure -> TC+TDRE both set,
  transmitter is alive.
- Polled writes successfully push 1200 wave8 UART bytes in 10 ms
  (= ~120 kbps actual due to per-byte STAT-polling overhead, well
  short of the 4 Mbps the BAUD divisor targets but proves the
  hardware path works).
- DMA arming sequence currently never sees the major-loop ISR fire;
  next iteration adds DMA_ES + CITER snapshots to diagnose whether
  TDMAE is being honored.

Also wires --lpuart through the autoresearch driver dispatcher and
enables Bus::LPUART in the Teensy 4.x enableAllChannelDrivers list.

Hardware test reproducible: bash autoresearch teensy40 --lpuart
--tx-pin 8 --rx-pin 22 reaches LPUART firmware and emits bytes on
pin 8 (polled path). Full WS2812-rate DMA path is the remaining
work.

* feat(lpuart): hardware-verified DMA path on Teensy 4.0

Working LPUART driver path bring-up:
- Force CCM_CSCDR1 UART_CLK_SEL=PLL3_80M / UART_CLK_PODF=1 so the
  LPUART clock is 80 MHz regardless of what the Teensyduino boot
  state left CSCDR1 at. Empirical: post-boot the LPUART clock was
  24 MHz, making OSR=4/SBR=4 produce ~1.2 Mbps instead of 4 Mbps.
- Move triggerAtHardwareEvent() + attachInterrupt() out of the
  per-show arm path into lpuart_dma_init() (set once at init).
- Add LPUART transmit-complete (STAT.TC) wait after the DMA major-
  loop ISR fires, so the final byte fully drains through the FIFO
  + shift register before show_encoded() returns.

Hardware verification (bench loopback, Teensy 4.0 pin 8 -> pin 22
via FlexPWM4_SM0_A RX):

  raw_sample: H753 L499 H746 L499 H753 L499 ... H253 L999 H246 L999
  -> exactly matches wave8 4-Mbps encoding:
       '1' bit = ~750 ns HIGH + ~500 ns LOW
       '0' bit = ~250 ns HIGH + ~1000 ns LOW
  -> Byte corruption: 1.4% (17/1200) on the first 4-pattern frame
     -- matches the FlexIO/ObjectFLED noise floor on the same rig.

DMA progression confirmed via CITER snapshots (in earlier diagnostic
revs): CITER decrements smoothly from BITER=1200 to 0 within ~3 ms
at 4 Mbps, then the major-loop ISR fires and resets CITER back to
BITER and sets sLpDmaComplete = true.

Still TODO: the autoresearch RPC sometimes times out after 2 TX
frames before the test framework collects results. The TX driver
itself completes cleanly each time -- the hang is in the test
harness's between-pattern handoff, not in the LPUART path.

* fix(lpuart): refactor engine, ws2812b-v5 reset=150us, add yield()

- Replace function-local static CachedInstance with proper member
  state (mInstance, mCurrentPin, mCurrentRawBytes, mCurrentTiming)
  mirroring ChannelEngineFlexIO's per-engine cache pattern.
- Add yield() after each show() so the USB-CDC RPC stack can flush
  responses; without it the autoresearch test pipeline stalls.
- Per user note: ws2812b-v5 datasheet specifies 150 us reset/latch,
  not the 280 us we had hard-coded. Update TIMING_WS2812B_MINI_V3
  (which TIMING_WS2812B_V5 aliases). The longer 280 us was a
  conservative carry-over from older WS2812 variants.

* fix(lpuart): audit pin map against Teensyduino HardwareSerial sources

Audited every entry in kLpuartPins[] against the matching
UARTn_Hardware struct in Teensyduino's HardwareSerial[1-7].cpp and
the IOMUXC_SW_MUX_CTL_PAD_GPIO_* offsets in imxrt.h. Found 6 of 7
entries had wrong mux_offset/pad_offset/select_input_value -- only
pin 8 was correct, which is why the bench rig works there but other
pins would have silently driven the wrong pad.

Corrected (all entries verified for Teensy 4.0):
  pin  1 -> LPUART6 TX, GPIO_AD_B0_12 (mux 0x0EC),  SELECT_INPUT=1
  pin  8 -> LPUART4 TX, GPIO_B1_00    (mux 0x17C),  SELECT_INPUT=2
  pin 14 -> LPUART2 TX, GPIO_AD_B1_02 (mux 0x104),  SELECT_INPUT=1
  pin 17 -> LPUART3 TX, GPIO_AD_B1_06 (mux 0x114),  SELECT_INPUT=0
  pin 20 -> LPUART8 TX, GPIO_AD_B1_10 (mux 0x124),  SELECT_INPUT=1
  pin 24 -> LPUART1 TX, GPIO_AD_B0_13 (mux 0x0F0),  no SELECT_INPUT
  pin 29 -> LPUART7 TX, GPIO_EMC_31   (mux 0x090),  SELECT_INPUT=1

Also revert WS2812B_V5 RESET back to 280 us per user follow-up.

Strip debug Serial.printf from engine + driver. Engine kept member-
state refactor (mInstance/mCurrentPin/mCurrentRawBytes) + yield()
after show.

Hardware status: bench rig with pin 8 LPUART loopback to pin 22
FlexPWM RX intermittently completes the 4-pattern test at the
~1% byte corruption noise floor matching FlexIO/ObjectFLED. Some
runs RPC-timeout downstream of the engine show() -- the LPUART TX
itself completes cleanly each time per the diagnostic snapshots.

* fix(autoresearch): LPUART takes the UART-decode path

In examples/AutoResearch/AutoResearchTest.cpp `is_uart_driver` was
narrowly checking `driver_name == "UART"`. The LPUART driver
emits a wave8-encoded 4 Mbps signal whose wire shape is functionally
identical to the existing UART path -- T0H=250 ns, T1H=750 ns,
T1L=500 ns -- so it should take the same decode branch (UART-specific
timing thresholds, 500 ms RX wait, gap_tolerance_ns=100us). Expand
the check to also match LPUART.

* fix(lpuart): address CodeRabbit review on PR #3421

5 actionable findings:

- bus_traits.h: move BusTraits<Bus::LPUART>::instancePtr() function-
  local static `gHolder` out of the header into the .cpp.hpp TU
  (per repo's no-static-in-headers rule).
- channel_engine_lpuart.h: move getName() / getCapabilities() bodies
  out of the header into the .cpp.hpp.
- channel_engine_lpuart.cpp.hpp: clear mHwInitialized/mCurrentPin/
  mCurrentRawBytes BEFORE attempting createInstance() so a failed
  create leaves the engine in a clean re-init-required state instead
  of a half-torn-down state that the next channel could inherit.
- lpuart_driver.cpp.hpp: honour reset_us. Record the previous
  frame's end-of-TC micros and stall the next show until reset_us
  has elapsed -- contractual fix per the public docstring.
- ci/autoresearch/args.py: pin-to-LPUART mapping is board-dependent
  (T4.0 vs T4.1), don't hard-code "pin 8 -> LPUART4" in help text.

Remaining CodeRabbit MAJOR finding (pin map missing pins 35/47/48
per kLPUARTTxPins contract) is T4.1-only / SD-bottom-pad coverage,
deferred to follow-up.

Verified: teensy40 AutoResearch builds clean, lpuart_encoder host
tests still 1/1 pass.

* fix(lpuart): Bus::UART specialization + remaining CodeRabbit fixes

Per user feedback:
- BusTraits<Bus::UART> specialised for Teensy 4.x to route through
  ChannelEngineLPUART. This matches the ESP32 pattern where Bus::UART
  binds to that platform's UART hardware; sketches that name
  Bus::UART work portably across both platforms.
- Bus::LPUART kept as an alias resolving to the same singleton
  instance so code that names the hardware directly still works.

CodeRabbit-flagged fixes:
- lpuart_encoder.h: replace `u8*` with `fl::span<u8, 4>` (static-
  extent span) so the 4-byte-output contract is checked at the type
  level. Call sites use `fl::span<u8, 4>{&buf[i*4], 4}`.
- lpuart_driver.cpp.hpp: reject oversize transfers instead of
  silently truncating them (was logging + truncating + returning
  success, leaving tail LEDs stale).
- lpuart_peripheral_real.cpp.hpp: return nullptr from createInstance
  if hardware init failed inside the constructor, instead of handing
  back a non-functional instance that would silently drop frames.
  Switch mTxBuffer from raw `new[]`/`delete[]` to
  `fl::unique_ptr<u8[]>` RAII.

Verified: bash test lpuart_encoder 8/8 pass; bash compile teensy40
AutoResearch clean.

* fix(lpuart): lint cleanup + single Bus::UART registration

- channel_drivers_teensy.impl.hpp: register only Bus::UART (not both
  Bus::UART and Bus::LPUART). Both resolve to the same singleton via
  the trait alias in bus_traits.h, so registering both was triggering
  the ChannelManager replace-driver path on every boot.

- lpuart_encoder.h: add IWYU pragma: private + FL_NO_EXCEPT on the
  two inline encode helpers.

- lpuart_driver.cpp.hpp: suppress BareAllocationChecker on the
  DMAChannel new/delete pair (Teensyduino DMAChannel has no
  fl smart-pointer factory).

- _build.cpp.hpp: alphabetize unity build includes (channel_engine
  before lpuart_*).

- flexio_driver.cpp.hpp: use FL_STATIC_ASSERT instead of raw
  static_assert per BannedMacrosChecker.

- third_party/object_fled/src/_build.cpp.hpp: alphabetize (ObjectFLED
  before ObjectFLEDDmaManager).

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

* fix(lpuart): per-pin mux_alt + audited T4.1 entries + trim JSON-RPC

Pin map audit (per user's "Audit pin map against every Teensyduino
HardwareSerial*.cpp" blocker):
- Cross-referenced every kLpuartPins entry against the corresponding
  HardwareSerial[1-8].cpp UARTn_Hardware struct's {pin, mux_val,
  select_input_reg, select_input_value} 4-tuple.
- Added per-entry mux_alt field so the T4.1 LPUART5_TX (pin 35,
  ALT 1, not 2) doesn't get force-driven through the wrong alt.
- Added T4.1-only entries (pins 35, 47, 53) gated on
  ARDUINO_TEENSY41. Verified IOMUXC offsets against imxrt.h.
- Corrected the kLPUARTTxPins public contract: the original list
  included pin 48 (which is actually LPUART5_RX_ALT on T4.1, not
  a TX pin) and was missing pin 53 (the real T4.1 LPUART6_TX_ALT).
  Fixed list is {1, 8, 14, 17, 20, 24, 29, 35, 47, 53}.

JSON-RPC minimization (per user "json-rpc should be kept to the
minimal possible without excessive spam"):
- runSingleTestImpl: skip flexPwmRxDiagnostics and flexIoDiagnostics
  emit for LPUART tests. Both are FlexIO/FlexPWM register snapshots
  that surface nothing LPUART-relevant; LPUART status already lives
  in lpuart_read_diagnostics. Trims ~660 bytes of JSON per response.
- ScopedLogDisable scope: kept enabled for all drivers including
  LPUART (per-driver carve-out empirically worsened hangs to 0/3
  due to USB-CDC saturation from FL_WARN spam during the 4-pattern
  loop).

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

* fix(autoresearch): gate FL_WARN sstream construction on log level

Resolves intermittent ~55s RPC timeout on Teensy 4 clockless tests
(LPUART, FlexIO, ObjectFLED autoresearch) when the test framework's
RPC ASYNC handler wraps execution in `fl::ScopedLogDisable`.

Root cause (marker-narrowed across this session):
`FL_WARN(...)` macro ALWAYS constructs `fl::sstream() << X` regardless
of log level -- `ScopedLogDisable` only suppresses OUTPUT inside
`log_emit`. The cumulative `fl::sstream`/`fl::string` heap alloc/free
cycles across this file's many FL_WARN sites (banner, per-run dump,
per-pattern hex dump, summary, OVERALL pass/fail) leave the Teensy 4
heap in a state where the function-exit destructor of a heap-backed
`fl::string` hangs indefinitely -- traced via Serial.println markers
to the `fl::variant<NotNullStringHolderPtr, ...>` destructor in
fl::sstream::~fl::sstream() at the close of runMultiTest.

Reproduction: ~80% of LPUART/FlexIO/ObjectFLED runs hung at exactly
`mt_pre_inner_close` marker → no `mt_dtors_done` → no
`art_after_multitest` → ~55s host timeout.

Fix: introduce `AR_FL_WARN` / `AR_FL_ERROR` macros that check
`fl::getLogLevel()` before expanding FL_WARN -- when under
ScopedLogDisable (level=NONE), the sstream is never constructed and
the heap stays clean. Sed-swept all 73 FL_WARN sites in
AutoResearchTest.cpp and 8 sites in AutoResearchHelpers.cpp.

Also gates `flexIoDiagnostics` / `flexPwmRxDiagnostics` JSON emit
to OBJECT_FLED only (their original #3343/#3410 purpose). LPUART
and FLEX_IO no longer carry that ~660-byte / 22-field JSON payload
that further compounds the heap pressure post-test.

Results (bench rig, Teensy 4.0, --lpuart --tx-pin 8 --rx-pin 22):
- LPUART:  1/5 baseline → 5/5 success (clean 0.3-2.0% noise floor)
- FlexIO:  0/5 baseline → 1-2/5 success (intermittent residual --
           likely additional heap pressure outside this file; not
           blocking since FlexIO landed via #3415 prior)
- LPUART tests now return reliable byte-corruption reports
  matching FlexIO/ObjectFLED noise floor, confirming the LPUART
  driver itself works correctly when the framework returns.

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

* fix(arduino/io): ride out Teensy 4 USB-CDC DTR debounce in fl::print(ln)

Per /goal "USB-CDC DTR race" research follow-up.

Teensy 4 `Serial.operator bool()` (usb_serial.h:166-169) returns
false for a hard-coded 15ms after every DTR transition (line
discipline settle window). Without a retry on the device side, the
first messages emitted by the device after a host re-opens the
serial port are silently dropped -- the `if (!Serial) return;`
guard in fl::print/fl::println short-circuits before the debounce
clears.

Reproduction surface: autoresearch RPC reconnects for each new test
session (close → re-open). Device output during the first ~15ms
after re-open vanishes -- visible as "missing log lines between
RPC sessions" or "first FL_WARN after reconnect never arrives".

Fix: extract a small `waitForSerialReady_DtrSettle()` helper that:
  - Fast-paths the common case (Serial already true → no wait)
  - Otherwise yields in a bounded 30ms loop (2× the Teensy 4
    debounce) waiting for `Serial.operator bool()` to settle true
  - Drops the message after 30ms if host is genuinely absent

On non-Teensy Arduino platforms `Serial.operator bool()` either
always returns true (real UART) or has its own non-blocking drop
path (ESP32 HWCDC: setTxTimeoutMs(0) applied by fl::begin()), so
the 30ms bound is invisible there.

Cross-platform compile verified: teensy40 ✓, esp32dev ✓, uno ✓.
Lint clean. 338/338 tests pass.

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

* fix(arduino/io): extend DTR settle wait to fl::flush + fl::serial_ready

Follow-up to 6c2d12e. The DTR debounce race window doesn't only
affect fl::print/fl::println -- fl::flush and fl::serial_ready use
the same `if (!Serial) return ...` short-circuit pattern, and would
also report "host absent" during the first ~15ms after a host
re-opens the USB-CDC port on Teensy 4.

Wire both through the same `waitForSerialReady_DtrSettle()` helper
so the device-side host-presence view stays consistent across all
three paths: print, flush, and the explicit ready-check.

`fl::write_bytes` is intentionally left untouched -- it does not
gate on `Serial`, so the underlying `Serial.write` path drives its
own back-pressure / drop semantics (Teensy 4 usb_serial_write has
its own 120ms tx-buffer-wait timeout). LPC platforms are also
intentionally left untouched -- their Arduino-core USB-VCOM bridge
has different debounce semantics that aren't documented to need
the same window.

Cross-platform compile: teensy40 ✓, esp32dev ✓.
Lint clean. 338/338 tests pass.

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

* docs(lpc/autoresearch): document --auto-discover-pins default behavior (closes #3296)

The --auto-discover-pins flag has been the default for autoresearch
runs (default=True in ci/autoresearch/args.py:485), but the
src/platforms/arm/lpc/README.md procedure didn't mention it. Add a
note to the loopback-setup section so agents reading the README
first see the discovery default and the --no-auto-discover-pins
opt-out.

Closes #3296.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 27, 2026
… (#3426)

* feat(lpuart): wave8 encoder + Teensy 4.x real driver + host unit tests

Adds Bus::LPUART workstream A from #3023:

- src/.../drivers/lpuart/lpuart_encoder.h: header-only WS2812 -> UART
  byte encoder. 2 WS2812 bits per UART byte using TXINV semantics.
  Wire pattern per bit at 4 Mbps:
    '0' -> H L L L L  (250 ns + 1000 ns)
    '1' -> H H H L L  (750 ns + 500 ns)
  Pair-to-byte table: (0,0)->0xEF, (0,1)->0x8F, (1,0)->0xEC, (1,1)->0x8C.
- src/.../drivers/lpuart/lpuart_driver.{h,cpp.hpp}: Teensy 4.x real
  driver. Configures LPUARTn for 4 Mbps with TXINV + TDMAE, programs
  the IOMUXC pad to ALT2 + SION, allocates a 4 KB DMAMEM buffer, and
  drives eDMA from the encoded byte stream to LPUARTn_DATA.
- src/.../drivers/lpuart/lpuart_peripheral_real.cpp.hpp: ILPUARTPeripheral
  factory for Teensy 4.x. Wraps the procedural driver in the existing
  ILPUARTInstance interface that the mock in
  src/platforms/shared/mock/arm/teensy4/drivers/lpuart/ already targets.
- tests/.../drivers/lpuart/lpuart_encoder.cpp: 8 host-side unit tests
  covering all-zeros, all-ones, MSB-first ordering, palindromic
  patterns, the pair-byte table, and the wire-format invariant.

Verified:
- bash test ilpuart_peripheral: existing mock interface tests pass
- bash test lpuart_encoder: 8/8 encoder tests pass on host
- bash compile teensy40 --examples Blink: clean build on T4.0 with
  the new driver in the unity build path

Pin map (T4.0): pin 1/8/14/17/20/24/29 map to LPUART6/4/2/3/8/1/7
TX respectively. Bench-rig pin 8 reuses the existing FlexIO/ObjectFLED
loopback jumper to FlexPWM-RX pin 22.

Refs #3023

* feat(lpuart): channel engine + BusTraits registration

Add the high-level ChannelEngineLPUART (mirrors ChannelEngineFlexIO)
plus a BusTraits<Bus::LPUART> specialisation so Bus::LPUART routes
through the real Teensy 4.x driver.

- channel_engine_lpuart.{h,cpp.hpp}: engine creates one ILPUARTInstance
  per (pin, strip-length) combination, encodes raw WS2812 bytes into
  the instance buffer using lpuart_encode_byte(), and calls
  instance->show().
- bus_traits.h: standard registerWithManager() pattern.
- lpuart_driver: add lpuart_show_encoded() for callers (the engine)
  that pre-encode externally; refactor common TCD arming into
  lpuart_arm_dma().
- bus_priorities.h: Bus::LPUART defaults to priority 1 (same as FlexIO
  and ObjectFLED).

Teensy 4.0 AutoResearch builds clean. Hardware test next.

* debug(lpuart): polled-tx diagnostic confirms LPUART4 transmits

Hardware bring-up progress on Teensy 4.0:
- Init sequence runs cleanly: clock gate, BAUD config, FIFO+CTRL,
  pin mux + IOMUXC SELECT_INPUT daisy.
- LPUART4 STAT = 0xC00000 after configure -> TC+TDRE both set,
  transmitter is alive.
- Polled writes successfully push 1200 wave8 UART bytes in 10 ms
  (= ~120 kbps actual due to per-byte STAT-polling overhead, well
  short of the 4 Mbps the BAUD divisor targets but proves the
  hardware path works).
- DMA arming sequence currently never sees the major-loop ISR fire;
  next iteration adds DMA_ES + CITER snapshots to diagnose whether
  TDMAE is being honored.

Also wires --lpuart through the autoresearch driver dispatcher and
enables Bus::LPUART in the Teensy 4.x enableAllChannelDrivers list.

Hardware test reproducible: bash autoresearch teensy40 --lpuart
--tx-pin 8 --rx-pin 22 reaches LPUART firmware and emits bytes on
pin 8 (polled path). Full WS2812-rate DMA path is the remaining
work.

* feat(lpuart): hardware-verified DMA path on Teensy 4.0

Working LPUART driver path bring-up:
- Force CCM_CSCDR1 UART_CLK_SEL=PLL3_80M / UART_CLK_PODF=1 so the
  LPUART clock is 80 MHz regardless of what the Teensyduino boot
  state left CSCDR1 at. Empirical: post-boot the LPUART clock was
  24 MHz, making OSR=4/SBR=4 produce ~1.2 Mbps instead of 4 Mbps.
- Move triggerAtHardwareEvent() + attachInterrupt() out of the
  per-show arm path into lpuart_dma_init() (set once at init).
- Add LPUART transmit-complete (STAT.TC) wait after the DMA major-
  loop ISR fires, so the final byte fully drains through the FIFO
  + shift register before show_encoded() returns.

Hardware verification (bench loopback, Teensy 4.0 pin 8 -> pin 22
via FlexPWM4_SM0_A RX):

  raw_sample: H753 L499 H746 L499 H753 L499 ... H253 L999 H246 L999
  -> exactly matches wave8 4-Mbps encoding:
       '1' bit = ~750 ns HIGH + ~500 ns LOW
       '0' bit = ~250 ns HIGH + ~1000 ns LOW
  -> Byte corruption: 1.4% (17/1200) on the first 4-pattern frame
     -- matches the FlexIO/ObjectFLED noise floor on the same rig.

DMA progression confirmed via CITER snapshots (in earlier diagnostic
revs): CITER decrements smoothly from BITER=1200 to 0 within ~3 ms
at 4 Mbps, then the major-loop ISR fires and resets CITER back to
BITER and sets sLpDmaComplete = true.

Still TODO: the autoresearch RPC sometimes times out after 2 TX
frames before the test framework collects results. The TX driver
itself completes cleanly each time -- the hang is in the test
harness's between-pattern handoff, not in the LPUART path.

* fix(lpuart): refactor engine, ws2812b-v5 reset=150us, add yield()

- Replace function-local static CachedInstance with proper member
  state (mInstance, mCurrentPin, mCurrentRawBytes, mCurrentTiming)
  mirroring ChannelEngineFlexIO's per-engine cache pattern.
- Add yield() after each show() so the USB-CDC RPC stack can flush
  responses; without it the autoresearch test pipeline stalls.
- Per user note: ws2812b-v5 datasheet specifies 150 us reset/latch,
  not the 280 us we had hard-coded. Update TIMING_WS2812B_MINI_V3
  (which TIMING_WS2812B_V5 aliases). The longer 280 us was a
  conservative carry-over from older WS2812 variants.

* fix(lpuart): audit pin map against Teensyduino HardwareSerial sources

Audited every entry in kLpuartPins[] against the matching
UARTn_Hardware struct in Teensyduino's HardwareSerial[1-7].cpp and
the IOMUXC_SW_MUX_CTL_PAD_GPIO_* offsets in imxrt.h. Found 6 of 7
entries had wrong mux_offset/pad_offset/select_input_value -- only
pin 8 was correct, which is why the bench rig works there but other
pins would have silently driven the wrong pad.

Corrected (all entries verified for Teensy 4.0):
  pin  1 -> LPUART6 TX, GPIO_AD_B0_12 (mux 0x0EC),  SELECT_INPUT=1
  pin  8 -> LPUART4 TX, GPIO_B1_00    (mux 0x17C),  SELECT_INPUT=2
  pin 14 -> LPUART2 TX, GPIO_AD_B1_02 (mux 0x104),  SELECT_INPUT=1
  pin 17 -> LPUART3 TX, GPIO_AD_B1_06 (mux 0x114),  SELECT_INPUT=0
  pin 20 -> LPUART8 TX, GPIO_AD_B1_10 (mux 0x124),  SELECT_INPUT=1
  pin 24 -> LPUART1 TX, GPIO_AD_B0_13 (mux 0x0F0),  no SELECT_INPUT
  pin 29 -> LPUART7 TX, GPIO_EMC_31   (mux 0x090),  SELECT_INPUT=1

Also revert WS2812B_V5 RESET back to 280 us per user follow-up.

Strip debug Serial.printf from engine + driver. Engine kept member-
state refactor (mInstance/mCurrentPin/mCurrentRawBytes) + yield()
after show.

Hardware status: bench rig with pin 8 LPUART loopback to pin 22
FlexPWM RX intermittently completes the 4-pattern test at the
~1% byte corruption noise floor matching FlexIO/ObjectFLED. Some
runs RPC-timeout downstream of the engine show() -- the LPUART TX
itself completes cleanly each time per the diagnostic snapshots.

* fix(autoresearch): LPUART takes the UART-decode path

In examples/AutoResearch/AutoResearchTest.cpp `is_uart_driver` was
narrowly checking `driver_name == "UART"`. The LPUART driver
emits a wave8-encoded 4 Mbps signal whose wire shape is functionally
identical to the existing UART path -- T0H=250 ns, T1H=750 ns,
T1L=500 ns -- so it should take the same decode branch (UART-specific
timing thresholds, 500 ms RX wait, gap_tolerance_ns=100us). Expand
the check to also match LPUART.

* fix(lpuart): address CodeRabbit review on PR #3421

5 actionable findings:

- bus_traits.h: move BusTraits<Bus::LPUART>::instancePtr() function-
  local static `gHolder` out of the header into the .cpp.hpp TU
  (per repo's no-static-in-headers rule).
- channel_engine_lpuart.h: move getName() / getCapabilities() bodies
  out of the header into the .cpp.hpp.
- channel_engine_lpuart.cpp.hpp: clear mHwInitialized/mCurrentPin/
  mCurrentRawBytes BEFORE attempting createInstance() so a failed
  create leaves the engine in a clean re-init-required state instead
  of a half-torn-down state that the next channel could inherit.
- lpuart_driver.cpp.hpp: honour reset_us. Record the previous
  frame's end-of-TC micros and stall the next show until reset_us
  has elapsed -- contractual fix per the public docstring.
- ci/autoresearch/args.py: pin-to-LPUART mapping is board-dependent
  (T4.0 vs T4.1), don't hard-code "pin 8 -> LPUART4" in help text.

Remaining CodeRabbit MAJOR finding (pin map missing pins 35/47/48
per kLPUARTTxPins contract) is T4.1-only / SD-bottom-pad coverage,
deferred to follow-up.

Verified: teensy40 AutoResearch builds clean, lpuart_encoder host
tests still 1/1 pass.

* fix(lpuart): Bus::UART specialization + remaining CodeRabbit fixes

Per user feedback:
- BusTraits<Bus::UART> specialised for Teensy 4.x to route through
  ChannelEngineLPUART. This matches the ESP32 pattern where Bus::UART
  binds to that platform's UART hardware; sketches that name
  Bus::UART work portably across both platforms.
- Bus::LPUART kept as an alias resolving to the same singleton
  instance so code that names the hardware directly still works.

CodeRabbit-flagged fixes:
- lpuart_encoder.h: replace `u8*` with `fl::span<u8, 4>` (static-
  extent span) so the 4-byte-output contract is checked at the type
  level. Call sites use `fl::span<u8, 4>{&buf[i*4], 4}`.
- lpuart_driver.cpp.hpp: reject oversize transfers instead of
  silently truncating them (was logging + truncating + returning
  success, leaving tail LEDs stale).
- lpuart_peripheral_real.cpp.hpp: return nullptr from createInstance
  if hardware init failed inside the constructor, instead of handing
  back a non-functional instance that would silently drop frames.
  Switch mTxBuffer from raw `new[]`/`delete[]` to
  `fl::unique_ptr<u8[]>` RAII.

Verified: bash test lpuart_encoder 8/8 pass; bash compile teensy40
AutoResearch clean.

* fix(lpuart): lint cleanup + single Bus::UART registration

- channel_drivers_teensy.impl.hpp: register only Bus::UART (not both
  Bus::UART and Bus::LPUART). Both resolve to the same singleton via
  the trait alias in bus_traits.h, so registering both was triggering
  the ChannelManager replace-driver path on every boot.

- lpuart_encoder.h: add IWYU pragma: private + FL_NO_EXCEPT on the
  two inline encode helpers.

- lpuart_driver.cpp.hpp: suppress BareAllocationChecker on the
  DMAChannel new/delete pair (Teensyduino DMAChannel has no
  fl smart-pointer factory).

- _build.cpp.hpp: alphabetize unity build includes (channel_engine
  before lpuart_*).

- flexio_driver.cpp.hpp: use FL_STATIC_ASSERT instead of raw
  static_assert per BannedMacrosChecker.

- third_party/object_fled/src/_build.cpp.hpp: alphabetize (ObjectFLED
  before ObjectFLEDDmaManager).

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

* fix(lpuart): per-pin mux_alt + audited T4.1 entries + trim JSON-RPC

Pin map audit (per user's "Audit pin map against every Teensyduino
HardwareSerial*.cpp" blocker):
- Cross-referenced every kLpuartPins entry against the corresponding
  HardwareSerial[1-8].cpp UARTn_Hardware struct's {pin, mux_val,
  select_input_reg, select_input_value} 4-tuple.
- Added per-entry mux_alt field so the T4.1 LPUART5_TX (pin 35,
  ALT 1, not 2) doesn't get force-driven through the wrong alt.
- Added T4.1-only entries (pins 35, 47, 53) gated on
  ARDUINO_TEENSY41. Verified IOMUXC offsets against imxrt.h.
- Corrected the kLPUARTTxPins public contract: the original list
  included pin 48 (which is actually LPUART5_RX_ALT on T4.1, not
  a TX pin) and was missing pin 53 (the real T4.1 LPUART6_TX_ALT).
  Fixed list is {1, 8, 14, 17, 20, 24, 29, 35, 47, 53}.

JSON-RPC minimization (per user "json-rpc should be kept to the
minimal possible without excessive spam"):
- runSingleTestImpl: skip flexPwmRxDiagnostics and flexIoDiagnostics
  emit for LPUART tests. Both are FlexIO/FlexPWM register snapshots
  that surface nothing LPUART-relevant; LPUART status already lives
  in lpuart_read_diagnostics. Trims ~660 bytes of JSON per response.
- ScopedLogDisable scope: kept enabled for all drivers including
  LPUART (per-driver carve-out empirically worsened hangs to 0/3
  due to USB-CDC saturation from FL_WARN spam during the 4-pattern
  loop).

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

* fix(autoresearch): gate FL_WARN sstream construction on log level

Resolves intermittent ~55s RPC timeout on Teensy 4 clockless tests
(LPUART, FlexIO, ObjectFLED autoresearch) when the test framework's
RPC ASYNC handler wraps execution in `fl::ScopedLogDisable`.

Root cause (marker-narrowed across this session):
`FL_WARN(...)` macro ALWAYS constructs `fl::sstream() << X` regardless
of log level -- `ScopedLogDisable` only suppresses OUTPUT inside
`log_emit`. The cumulative `fl::sstream`/`fl::string` heap alloc/free
cycles across this file's many FL_WARN sites (banner, per-run dump,
per-pattern hex dump, summary, OVERALL pass/fail) leave the Teensy 4
heap in a state where the function-exit destructor of a heap-backed
`fl::string` hangs indefinitely -- traced via Serial.println markers
to the `fl::variant<NotNullStringHolderPtr, ...>` destructor in
fl::sstream::~fl::sstream() at the close of runMultiTest.

Reproduction: ~80% of LPUART/FlexIO/ObjectFLED runs hung at exactly
`mt_pre_inner_close` marker → no `mt_dtors_done` → no
`art_after_multitest` → ~55s host timeout.

Fix: introduce `AR_FL_WARN` / `AR_FL_ERROR` macros that check
`fl::getLogLevel()` before expanding FL_WARN -- when under
ScopedLogDisable (level=NONE), the sstream is never constructed and
the heap stays clean. Sed-swept all 73 FL_WARN sites in
AutoResearchTest.cpp and 8 sites in AutoResearchHelpers.cpp.

Also gates `flexIoDiagnostics` / `flexPwmRxDiagnostics` JSON emit
to OBJECT_FLED only (their original #3343/#3410 purpose). LPUART
and FLEX_IO no longer carry that ~660-byte / 22-field JSON payload
that further compounds the heap pressure post-test.

Results (bench rig, Teensy 4.0, --lpuart --tx-pin 8 --rx-pin 22):
- LPUART:  1/5 baseline → 5/5 success (clean 0.3-2.0% noise floor)
- FlexIO:  0/5 baseline → 1-2/5 success (intermittent residual --
           likely additional heap pressure outside this file; not
           blocking since FlexIO landed via #3415 prior)
- LPUART tests now return reliable byte-corruption reports
  matching FlexIO/ObjectFLED noise floor, confirming the LPUART
  driver itself works correctly when the framework returns.

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

* fix(arduino/io): ride out Teensy 4 USB-CDC DTR debounce in fl::print(ln)

Per /goal "USB-CDC DTR race" research follow-up.

Teensy 4 `Serial.operator bool()` (usb_serial.h:166-169) returns
false for a hard-coded 15ms after every DTR transition (line
discipline settle window). Without a retry on the device side, the
first messages emitted by the device after a host re-opens the
serial port are silently dropped -- the `if (!Serial) return;`
guard in fl::print/fl::println short-circuits before the debounce
clears.

Reproduction surface: autoresearch RPC reconnects for each new test
session (close → re-open). Device output during the first ~15ms
after re-open vanishes -- visible as "missing log lines between
RPC sessions" or "first FL_WARN after reconnect never arrives".

Fix: extract a small `waitForSerialReady_DtrSettle()` helper that:
  - Fast-paths the common case (Serial already true → no wait)
  - Otherwise yields in a bounded 30ms loop (2× the Teensy 4
    debounce) waiting for `Serial.operator bool()` to settle true
  - Drops the message after 30ms if host is genuinely absent

On non-Teensy Arduino platforms `Serial.operator bool()` either
always returns true (real UART) or has its own non-blocking drop
path (ESP32 HWCDC: setTxTimeoutMs(0) applied by fl::begin()), so
the 30ms bound is invisible there.

Cross-platform compile verified: teensy40 ✓, esp32dev ✓, uno ✓.
Lint clean. 338/338 tests pass.

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

* fix(arduino/io): extend DTR settle wait to fl::flush + fl::serial_ready

Follow-up to 6c2d12e. The DTR debounce race window doesn't only
affect fl::print/fl::println -- fl::flush and fl::serial_ready use
the same `if (!Serial) return ...` short-circuit pattern, and would
also report "host absent" during the first ~15ms after a host
re-opens the USB-CDC port on Teensy 4.

Wire both through the same `waitForSerialReady_DtrSettle()` helper
so the device-side host-presence view stays consistent across all
three paths: print, flush, and the explicit ready-check.

`fl::write_bytes` is intentionally left untouched -- it does not
gate on `Serial`, so the underlying `Serial.write` path drives its
own back-pressure / drop semantics (Teensy 4 usb_serial_write has
its own 120ms tx-buffer-wait timeout). LPC platforms are also
intentionally left untouched -- their Arduino-core USB-VCOM bridge
has different debounce semantics that aren't documented to need
the same window.

Cross-platform compile: teensy40 ✓, esp32dev ✓.
Lint clean. 338/338 tests pass.

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

* docs(lpc/autoresearch): document --auto-discover-pins default behavior (closes #3296)

The --auto-discover-pins flag has been the default for autoresearch
runs (default=True in ci/autoresearch/args.py:485), but the
src/platforms/arm/lpc/README.md procedure didn't mention it. Add a
note to the loopback-setup section so agents reading the README
first see the discovery default and the --no-auto-discover-pins
opt-out.

Closes #3296.

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

* feat(simd/arm-dsp): wire UXTB16/PKHBT/PKHTB/USAT16/SEL ops (refs #3425)

Promotes the remaining 🟢 (high-ROI) ops from scalar fallback to
Cortex-M DSP-ext intrinsics in src/platforms/arm/teensy/simd_arm_dsp.hpp.
Each was added one-at-a-time and validated via the device-side SIMD
self-test suite (85/85 passing after every op):

- **avg_round_u8_16** — rounded average via UHADD8 NOT-trick:
  per byte `(a+b+1)>>1` = `~UHADD8(~a, ~b)`. 4 DSP ops + 4 NOT vs 16-iter
  scalar widening loop. Replaces the (a + b + 1) >> 1 reference path.

- **widen_lo_u8_to_u16 / widen_hi_u8_to_u16** — zero-extend 8 bytes to
  8 halfwords via UXTB16 (bytes 0,2) + UXTB16 ROR #8 (bytes 1,3) +
  PKHBT/PKHTB to re-pack lanes into sequential halfword order. 4 DSP
  ops per pair of output u32 words vs 8 LDRB+STRH scalar pairs.

- **narrow_u16_to_u8** — USAT16 #8 saturates two halfwords to [0,255]
  in one DSP op; scalar mask+shift then packs 4 halfword-LSBs into one
  output u32 byte-aligned. Replaces the per-lane `> 255 ? 255 : value`
  branch sequence.

- **min_u8_16 / max_u8_16** — USUB8 sets APSR.GE[3:0] per byte from the
  unsigned-subtract result; SEL picks the matching byte. 2 DSP ops per
  4 bytes vs 16 conditional moves. Marked `"cc"` clobber so the
  compiler can't reorder SEL ahead of USUB8 (GE flags are the only
  data-dependency carrier).

All u8x32 / u16x16 ops in this file delegate to the u8x16 / u16x8
variants above, so they pick up the DSP acceleration automatically
(avg_round_u8_32, widen_lo_u8x32_to_u16, widen_hi_u8x32_to_u16,
narrow_u16x16_to_u8).

Deferred to a follow-up (🟡 ops): scale_u8_16, blend_u8_16, mullo_u16_8
-- the PKHBT/UXTB16/SMUAD chains needed for the multiply-then-narrow
fused ops are more code than win-per-op until a specific hot path
demands them.

Verification: `bash autoresearch teensy40 --simd --skip-lint` reports
85/85 SIMD tests passing after each individual op was added (per
issue #3425's one-at-a-time mandate). Bit-exact against the noop
reference. Compile clean on teensy40 (Cortex-M7) and esp32dev (gates
correctly through __ARM_FEATURE_DSP).

Closes #3425 (🟢 ops portion).

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

---------

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