Skip to content

feat(rx/lpc): SCT input-capture + pin-toggle loopback (refs #3021) - #3024

Merged
zackees merged 3 commits into
masterfrom
feat/3021-lpc-sct-rx-phase1
Jun 14, 2026
Merged

zackees merged 3 commits into
masterfrom
feat/3021-lpc-sct-rx-phase1

Conversation

@zackees

@zackees zackees commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 1 of FastLED #3021 — wires real SCT input-capture register programming into the LPC SCT-RX scaffold landed by #3015/#3016, plus the autoresearch RPC + Python orchestrator that exercises pin-toggle TX → SCT-RX loopback at 1 / 10 / 100 kHz.

What this PR does

Driver — src/platforms/arm/lpc/rx_sct_capture.{h,cpp.hpp}

Behind a new FASTLED_LPC_RX_SCT compile gate (default off — preserves flash budget for sketches that don't opt in):

  • begin() powers up SCT + SWM in SYSCON, routes the user's pin to SCT0_GPIO_IN_A_I via SWM PINASSIGN6, programs a 32-bit unified free-running counter, and wires events EV0/EV1 to capture into CAP[0]/CAP[1] on rising / falling edges.
  • pollOnce() (new public method) drains EVFLAG + CAP[0..1] into the EdgeTime ring. Designed to be called from a TX bit-bang loop on the M0+ — the SCT overwrites each CAP register on every edge before wait() could read it. Phase 2's SCT→DMA upgrade will reduce this to a no-op.
  • wait() spins on pollOnce() until timeout or buffer full.
  • Destructor halts the SCT and unmaps the SWM pin so a follow-up driver can claim it.

All offsets / bit positions cross-checked against UM11029 Rev 1.7 §8 (SYSCON), §10 (SWM), §21 (SCT). The hardware-validated SYSCON layout in watchdog_lpc.impl.hpp was used as the reference. The existing PWM_DMA TX driver shim has known offset bugs (REGMODE width, SYSCON offset, DMA CFG.HWTRIGEN bit position) — RX driver uses its own anonymous-namespace constants instead of reusing the broken shim. (Fixing the TX driver shim is left as a separate cleanup follow-up — out of scope for #3021.)

Sketch — examples/AutoResearchLpc/AutoResearchLpc.ino

Adds pinToggleRx(tx, rx, freq_hz, dur_ms) -> CSV JSON-RPC binding. The CSV-string return shape (instead of the FlexIO-style fl::json object) minimizes flash on the 64 KB LPC845 budget — 7 integer fields packed as success,edges,periods,mean_ns,sigma_ns,min_ns,max_ns.

#define FASTLED_LPC_RX_SCT 1 is set at the top of the sketch so the real SCT register code activates.

Autoresearch runner

  • ci/autoresearch/args.py — new --pin-toggle-rx CLI flag.
  • ci/autoresearch/phases.py — _run_lpc_pin_toggle_rx_tests() dispatcher that delegates to a fresh subprocess running the Python bench script.
  • ci/autoresearch/test_lpc_pin_toggle_rx.py — Python orchestrator mirroring test_flexio_rx_squarewave.py, adapted to the LPC sketch's positional-args + CSV-string RPC contract. Three cases: 1 kHz / 10 kHz / 100 kHz with σ < {1000, 500, 500} ns, mean ±2 %.

Wiring: jumper P0_10 ↔ P0_11 on the LPC845-BRK header.

Test plan

  • Host unit tests still pass — tests/fl/channels/rx_sct_capture.cpp (synthetic-edge round-trip via injectEdges() → decode()) unaffected.
  • bash lint clean on all touched files (C++ + Python).
  • Hardware bench — bash autoresearch lpc845brk --pin-toggle-rx --upload-port COM10 on a real LPC845-BRK with P0_10↔P0_11 jumpered. Expected: all 3 freq cases PASS.

Hardware validation is the remaining item — code is bench-ready but I do not have an LPC845-BRK currently attached to verify against silicon. Once verified, the Phase 1 acceptance from #3021 closes.

Out of scope

  • Phase 2 (WS2812 byte-match loopback) — separate follow-up PR. Phase 2 will upgrade the SCT capture path from polling to SCT→DMA (polling can't keep up with WS2812's 800 kHz edge rate on the 30 MHz M0+).
  • TX SCT shim register offset / bit fixes in clockless_arm_lpc_pwm_dma.h — that file's shim is misaligned (see commit message). Cleanup deferred to a separate PR so the RX driver doesn't drag the unvalidated TX driver into a single review surface.
  • Channels API integration for TX — per the issue's "Out of scope" the TX side stays on the existing sync bit-bang driver (clockless_arm_lpc.h).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added LPC845 SCT-RX pin-toggle automated hardware validation with configurable frequency/duration cases and timing assertions.
    • Introduced an opt-in SCT-RX bring-up/validation workflow (including JSON-RPC pin-toggle method) and a CLI switch to run the SCT-RX loopback bench with TX/RX wiring guidance.
    • Reports per-case PASS/FAIL based on captured period accuracy and sigma limits.
  • Platform Improvements
    • Improved LPC845 SCT-RX capture to use a polling-driven path for more reliable edge-timing collection and statistics.

Closes Phase 1 of FastLED #3021 — wires real SCT input-capture
register programming into the LPC SCT-RX scaffold landed by #3015/#3016,
adds the `pinToggleRx` JSON-RPC handler to the LPC845-BRK bring-up
sketch, and adds an `--pin-toggle-rx` autoresearch subcommand + Python
orchestrator that exercises the full loopback at 1 / 10 / 100 kHz.

Driver implementation (src/platforms/arm/lpc/rx_sct_capture.{h,cpp.hpp})
-----------------------------------------------------------------------

Behind a new `FASTLED_LPC_RX_SCT` compile gate (default off — preserves
the existing flash budget for sketches that don't opt in):

  * `begin()` powers up SCT + SWM in SYSCON, routes the user's pin to
    SCT0_GPIO_IN_A_I via SWM PINASSIGN6, programs a 32-bit unified
    free-running counter, and wires events EV0/EV1 to capture into
    CAP[0]/CAP[1] on rising / falling edges of the input.

  * `pollOnce()` (new public method) drains the SCT EVFLAG/CAP[0..1]
    pair into the EdgeTime ring buffer. Designed to be called from a
    TX bit-bang loop on the M0+ — without inline polling the SCT
    overwrites each CAP register on every edge before user code can
    read it. Phase 2's SCT->DMA upgrade will reduce `pollOnce()` to
    a no-op; the API stays for compatibility.

  * `wait()` spins on `pollOnce()` until timeout or buffer full.

  * Destructor halts the SCT and unmaps the SWM pin so a follow-up
    driver can claim it.

All register offsets / bit positions cross-checked against UM11029
Rev 1.7 §8 (SYSCON), §10 (SWM), §21 (SCT). Hardware-validated SYSCON
layout matched against `watchdog_lpc.impl.hpp`. Existing PWM_DMA TX
driver shim has known offset bugs (REGMODE width, SYSCON offset,
DMA CFG.HWTRIGEN bit position) — RX driver uses its own anonymous
namespace of correct constants instead of reusing the broken shim.

Sketch (examples/AutoResearchLpc/AutoResearchLpc.ino)
-----------------------------------------------------

Adds `pinToggleRx(tx, rx, freq_hz, dur_ms) -> CSV string` JSON-RPC
binding. The CSV-string return shape (instead of the FlexIO-style
fl::json object) keeps flash overhead minimal on the 64 KB LPC845
budget: 7 integer fields packed as
`success,edges,periods,mean_ns,sigma_ns,min_ns,max_ns`.

The handler bit-bangs a software square wave on tx_pin while
concurrently calling rx->pollOnce() between each digitalWrite, then
computes period mean / σ / min / max stats over the captured edges.

`#define FASTLED_LPC_RX_SCT 1` is set at the top of the sketch so the
real SCT register programming activates.

Autoresearch runner (ci/autoresearch/{args,phases}.py)
------------------------------------------------------

  * New `--pin-toggle-rx` CLI flag in args.py.
  * New `_run_lpc_pin_toggle_rx_tests()` dispatch in phases.py that
    routes lpc845brk + --pin-toggle-rx to a fresh subprocess running
    the Python bench script.

Python orchestrator (ci/autoresearch/test_lpc_pin_toggle_rx.py)
---------------------------------------------------------------

Mirrors `test_flexio_rx_squarewave.py` but adapted to the LPC sketch's
positional-args + CSV-string RPC contract:

  Case 1.1 — 1 kHz  / 200 ms — σ < 1000 ns, mean ±2 %
  Case 1.2 — 10 kHz / 100 ms — σ < 500 ns,  mean ±2 %
  Case 1.3 — 100 kHz/ 100 ms — σ < 500 ns,  mean ±2 %

(Looser σ vs the Teensy 4 FlexIO bench because M0+ polling adds
1–2 µs of capture jitter per edge — see pollOnce() timing budget.)

Wiring: jumper P0_10 ↔ P0_11 on the LPC845-BRK header.

Hardware validation
-------------------

Code is bench-ready but NOT yet validated on real LPC845 silicon —
this PR ships the implementation contract so Phase 1 acceptance can
be confirmed in a follow-up bench session against the LPC845-BRK
attached to COM10.

To run on hardware once the board is connected:
  bash autoresearch lpc845brk --pin-toggle-rx --upload-port COM10
@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1ea7067c-8c9b-4e3d-a298-21a44f9c18cc

📥 Commits

Reviewing files that changed from the base of the PR and between 7ae7ba5 and fc8d39a.

📒 Files selected for processing (1)
  • examples/AutoResearchLpc/AutoResearchLpc.ino
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/AutoResearchLpc/AutoResearchLpc.ino

📝 Walkthrough

Walkthrough

Implements LPC845 SCT-RX Phase 1 validation: the LpcSctRxChannel hardware capture class gains a real begin(), a pollOnce() EVFLAG-drain method, and a custom destructor. The AutoResearchLpc sketch adds a pinToggleRx JSON-RPC handler. A new Python bench script drives and validates the RPC. CI orchestration wires a --pin-toggle-rx flag to invoke the bench.

Changes

LPC845 SCT-RX Phase 1 Pin-Toggle Bench

Layer / File(s) Summary
LpcSctRxChannel hardware capture layer
src/platforms/arm/lpc/rx_sct_capture.h, src/platforms/arm/lpc/rx_sct_capture.cpp.hpp
Declares pollOnce() and an explicit destructor; extends private state with mCapacity, mPrevTick, mPrevSeen, mLastRising. Implements full LPC845 SCT register setup (MMIO helpers, SWM routing, unified capture, EV0/EV1, EVFLAG), pollOnce() drain loop with tick-to-nanosecond conversion, and spin-poll wait() that halts SCT and returns SUCCESS/TIMEOUT.
AutoResearchLpc pinToggleRx RPC handler
examples/AutoResearchLpc/AutoResearchLpc.ino
Adds FASTLED_LPC_RX_SCT compile flag and documents pinToggleRx JSON-RPC contract with CSV return layout. Defines PinTogglePeriodStats and computePeriodStats(). Implements pinToggleRx(tx_pin, rx_pin, freq_hz, duration_ms) RPC handler: validates inputs, configures LpcSctRxChannel, bit-bangs TX while calling pollOnce() per edge, drains remaining capture via wait(1), computes period statistics, and returns CSV string.
Python SCT-RX bench test script
ci/autoresearch/test_lpc_pin_toggle_rx.py
New standalone script defining BenchCase for 1/10/100 kHz cases, send_rpc() for JSON-RPC over serial, parse_csv_result(), evaluate() with tolerance and sigma checks, and main() with serial setup, echo health-check, per-case pinToggleRx invocations with expanded timeout, and exit-code aggregation.
CI args and phase orchestration
ci/autoresearch/args.py, ci/autoresearch/phases.py
Adds pin_toggle_rx: bool to Args, the --pin-toggle-rx CLI argument group, and wires it into parse_args(). Extends _run_tests_or_special_mode() to route LPC bring-up to a new _run_lpc_pin_toggle_rx_tests() subprocess helper when the flag is set, printing required wiring instructions and mapping exit code.

Sequence Diagram(s)

sequenceDiagram
    participant CI as CI phases.py
    participant Script as test_lpc_pin_toggle_rx.py
    participant FW as AutoResearchLpc (LPC845)
    participant SCT as SCT hardware

    CI->>Script: uv run python test_lpc_pin_toggle_rx.py --port ... --tx-pin ... --rx-pin ...
    Script->>FW: JSON-RPC echo (health check)
    FW-->>Script: echo response
    loop each BenchCase (1/10/100 kHz)
        Script->>FW: JSON-RPC pinToggleRx(tx, rx, freq_hz, duration_ms)
        FW->>SCT: begin(): configure SWM, EV0/EV1, release HALT
        loop each TX edge
            FW->>SCT: pollOnce(): read EVFLAG/CAP, clear W1C
            SCT-->>FW: EdgeTime appended
        end
        FW->>SCT: wait(1): halt SCT
        FW-->>Script: CSV (success, edges, periods, mean, sigma, min, max)
        Script->>Script: parse_csv_result() + evaluate()
        Script-->>CI: PASS / FAIL per case
    end
    Script-->>CI: exit 0 (all pass) or exit 1
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#3016: Both PRs directly evolve the same LPC SCT RX backend—introducing/expanding fl::LpcSctRxChannel in src/platforms/arm/lpc/rx_sct_capture.{h,cpp.hpp} (retrieved PR scaffolds injectEdges/decoder, while main PR upgrades it for LPC845 hardware capture with begin/pollOnce runtime state).
  • FastLED/FastLED#3009: This PR extends the LPC845 bring-up test dispatch in ci/autoresearch/phases.py that #3009 established, adding the --pin-toggle-rx routing branch to _run_tests_or_special_mode.

Poem

🐇 Hoppity-hop through registers low,
SCT events captured, edge by edge they flow,
pollOnce() drains the EVFLAG with care,
CSV stats bounce through the serial air,
Mean within two percent, sigma stays small—
Phase one complete! The bunny hops through all. 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.28% 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 directly and accurately summarizes the main change: implementing SCT input-capture with pin-toggle loopback functionality for the LPC platform's RX driver, matching the PR's primary objective.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 feat/3021-lpc-sct-rx-phase1

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 and usage tips.

@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 14, 2026

@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/lpc/rx_sct_capture.cpp.hpp`:
- Line 203: The assignment to mCapacity in the constructor silently defaults to
4096 edges when config.buffer_size is 0, which can cause out-of-memory on
LPC845. Instead of using a silent fallback, validate that config.buffer_size is
greater than 0 and either assign it directly or fail fast with a descriptive
error message that indicates the buffer_size must be explicitly provided and not
zero. This ensures invalid configurations are caught immediately rather than
causing memory exhaustion at runtime.
🪄 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: e6c8301b-82f6-4898-b01a-5f8d4590620c

📥 Commits

Reviewing files that changed from the base of the PR and between 6157361 and 0af8e1c.

📒 Files selected for processing (6)
  • ci/autoresearch/args.py
  • ci/autoresearch/phases.py
  • ci/autoresearch/test_lpc_pin_toggle_rx.py
  • examples/AutoResearchLpc/AutoResearchLpc.ino
  • src/platforms/arm/lpc/rx_sct_capture.cpp.hpp
  • src/platforms/arm/lpc/rx_sct_capture.h

// edge buffer stays empty until `injectEdges()` populates it from
// the test harness or the follow-up firmware-side capture path.
// ------------------------------------------------------------------------
mCapacity = config.buffer_size > 0 ? config.buffer_size : 4096u;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Silent fallback to 4096 on zero buffer_size risks OOM on LPC845.

Line 203 falls back to 4096 edges when config.buffer_size is 0. On LPC845 with 16 KB SRAM, 4096 × 8 bytes = 32 KB exceeds available memory and would OOM. As per coding guidelines: "Never use silent fallbacks for missing critical resources - always fail fast with descriptive errors."

The pinToggleRx path avoids this by setting buffer_size explicitly, but other call sites could hit this.

🛡️ Proposed fix: fail fast on zero buffer_size
-    mCapacity = config.buffer_size > 0 ? config.buffer_size : 4096u;
+    if (config.buffer_size == 0) {
+        FL_WARN("LpcSctRxChannel::begin: config.buffer_size must be > 0");
+        return false;
+    }
+    mCapacity = config.buffer_size;
🤖 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/lpc/rx_sct_capture.cpp.hpp` at line 203, The assignment to
mCapacity in the constructor silently defaults to 4096 edges when
config.buffer_size is 0, which can cause out-of-memory on LPC845. Instead of
using a silent fallback, validate that config.buffer_size is greater than 0 and
either assign it directly or fail fast with a descriptive error message that
indicates the buffer_size must be explicitly provided and not zero. This ensures
invalid configurations are caught immediately rather than causing memory
exhaustion at runtime.

Source: Coding guidelines

zackees added 2 commits June 14, 2026 09:56
…ing)

CI caught: `examples/AutoResearchLpc/AutoResearchLpc.ino:233:17:
error: no type named 'strstream' in namespace 'fl'; did you mean
'sstream'?`. The header file is `fl/stl/strstream.h` but the class
inside is `fl::sstream` — file name is misleading. Fix the four use
sites in the pinToggleRx handler.

The uno CI failure on the same run is pre-existing (`math.cpp.hpp:162`
F(1.0/6.0) initializer fails on AVR g++ — not introduced by this PR).
CI surfaced: the example DLL host-stub build (Linux example tests)
compiles AutoResearchLpc.ino with STUB_PLATFORM, where
`fl::LpcSctRxChannel`, `fl::RxConfig`, `fl::EdgeTime`, and the
Arduino-native `delayMicroseconds` all do not exist. Wrap the
pinToggleRx handler body + helpers in `#if defined(FL_IS_ARM_LPC)`
so the host build still gets a valid empty-handler sketch.

The runtime behavior on real LPC845 silicon is unchanged — FL_IS_ARM_LPC
evaluates true there. Host stub now skips the RX section cleanly.
@zackees
zackees merged commit 7383315 into master Jun 14, 2026
6 of 7 checks passed
@zackees
zackees deleted the feat/3021-lpc-sct-rx-phase1 branch June 14, 2026 17:45
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 14, 2026
zackees added a commit that referenced this pull request Jun 14, 2026
Adds the Phase-2 surface area for FastLED #3021 — the ws2812SctTest
JSON-RPC handler in the LPC845-BRK sketch (gated behind
FASTLED_LPC_RX_SCT_WS2812 + FL_IS_ARM_LPC), the --ws2812-loopback
autoresearch subcommand, and the Python orchestrator that exercises
the 5 fixed WS2812 patterns mirroring flexioObjectFledTest.

Hardware acceptance for this RPC is blocked on two pre-existing
follow-ups (independent of #3021 itself):
  1. SCT->DMA RX upgrade — polling-mode pollOnce() on M0+ can't
     keep up with WS2812 800 kHz edge rate (300-700 ns per poll vs
     400-850 ns sub-pulses). DMA upgrade tracked as a follow-up.
  2. fl::json soft-FP flash bloat (#3002) — #include <FastLED.h>
     overflows the LPC845 64 KB budget alongside fl::Remote until
     #3002 lands. FASTLED_LPC_RX_SCT_WS2812 is therefore default OFF
     in the sketch; the flag flips on for the lpc845brk fbuild
     target once #3002 closes.

Rebased onto master after #3024 (Phase 1) was squash-merged.
zackees added a commit that referenced this pull request Jun 14, 2026
)

Adds the Phase-2 surface area for FastLED #3021 — the ws2812SctTest
JSON-RPC handler in the LPC845-BRK sketch (gated behind
FASTLED_LPC_RX_SCT_WS2812 + FL_IS_ARM_LPC), the --ws2812-loopback
autoresearch subcommand, and the Python orchestrator that exercises
the 5 fixed WS2812 patterns mirroring flexioObjectFledTest.

Hardware acceptance for this RPC is blocked on two pre-existing
follow-ups (independent of #3021 itself):
  1. SCT->DMA RX upgrade — polling-mode pollOnce() on M0+ can't
     keep up with WS2812 800 kHz edge rate (300-700 ns per poll vs
     400-850 ns sub-pulses). DMA upgrade tracked as a follow-up.
  2. fl::json soft-FP flash bloat (#3002) — #include <FastLED.h>
     overflows the LPC845 64 KB budget alongside fl::Remote until
     #3002 lands. FASTLED_LPC_RX_SCT_WS2812 is therefore default OFF
     in the sketch; the flag flips on for the lpc845brk fbuild
     target once #3002 closes.

Rebased onto master after #3024 (Phase 1) was squash-merged.
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