Skip to content

feat(watchdog): Teensy 4 bare-register WDOG3 impl, hardware-verified - #2753

Merged
zackees merged 12 commits into
masterfrom
feat/teensy4-wdt-bare-registers
Jun 4, 2026
Merged

zackees merged 12 commits into
masterfrom
feat/teensy4-wdt-bare-registers

Conversation

@zackees

@zackees zackees commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Bare-register WDOG3 (RTWDOG) implementation for Teensy 4.x — no third-party library dependency. Hardware-verified end-to-end on a real Teensy 4.0:

deliberateHang RPC → device disables interrupts → spins forever
   → WDT fires after the configured 15 s timeout
   → SYSRESETREQ → chip reset
   → MKL02 boot chip keeps HalfKay USB recoverable → iMXRT re-boots from FLASH
   → AutoResearch runs setup() again → device fully responsive
   → Repeated twice end-to-end to confirm

Replaces the previous tonton81/WDT_T4 library wrapper (which would have needed lib_deps plumbing in platformio.ini) with direct iMXRT1062 RTWDOG register access through <imxrt.h> (already bundled with the Teensy core).

Highlights

  • src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp — full Tier 0 surface on bare registers
  • examples/AutoResearch/AutoResearch.ino — startup_early_hook override that neutralizes the default-enabled WDOG3 (TOVAL=0x400 ≈ 32 ms) before main() runs, plus a deliberateHang RPC handler that lets the host validate the WDT-reset path
  • Sibling fixes for the same bug-classes on other platforms surfaced by the cross-platform audit:
    • K20 (Teensy 3.x) — feed() and the WDOG-unlock helper now save/restore PRIMASK instead of naked __disable_irq()/__enable_irq() that would surprise-re-enable IRQs from an already-IRQ-off caller
    • nRF52 — NRF_WDT->CONFIG was being written as 1u with a comment claiming "pause in debug" — actually that left HALT=0, so the WDT kept counting through debugger breakpoints. Fixed to (1 << 0) | (1 << 3) (SLEEP=1, HALT=1) for true pause-on-debug.

Code review

Four parallel expert agents reviewed every aspect of the WDOG3 path before merge:

  1. Register-level RTWDOG sequence — found a P0 CRITICAL bug: translateSrcSrsr was using hardcoded shifts that were off by 1–9 bits in different places, so lastResetWasWatchdog() returned false after every WDOG3 reset and the recovery / crash-counter path was completely dead. Fixed by using the SRC_SRSR_*_B named macros from <imxrt.h> (which agree with NXP MCUXpresso SDK).
  2. ISR safety + memory model — found a HIGH bug: begin() had been migrated to PRIMASK save/restore for the entry path, but the two success/timeout exits still called __enable_irq() which would unconditionally re-enable interrupts even when the caller had them off. Fixed to msr primask, %0. Also flagged a MEDIUM missing-DSB-after-CCM-gate-write — added dsb + isb after every CCM_CCGR5 store per the iMXRT1062 RM.
  3. Startup-hook linkage — verified in the built ELF (firmware.elf) that startup_early_hook was LTO-inlined into ResetHandler2 and lives in .text.code (FLASH at VMA 0x60001412), exactly where it needs to be. No bugs.
  4. Cross-platform WDT consistency — surfaced the K20 PRIMASK clobber and the nRF52 HALT inversion above; gave the other six platforms (RP, STM32, SAMD, MGM240, Apollo3, AVR, ESP32, stub, WASM, shared/noop) a clean bill.

File changes (12 commits squash-merged)

Phase Commits What
Initial bare-register impl 1 New src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp with WDT_T4 library replaced
Boot-trigger gate 1 examples/AutoResearch/AutoResearch.ino deliberateHang RPC + Tier-0 FastLED.watchdog().begin(15000) integration
CCM clock-gate enable + bounded spins 1 `CCM_CCGR5
Lint fixes (Serial.println suppressors, is_stm32.h include) 1 Boot-diagnostic prints need // ok serial - per the example-serial-checker
startup_early_hook WDOG3 disable 1 Neutralizes the default-enabled WDOG3 before main() so a slow setup() doesn't get bitten
Re-enable arming for Teensy 4 after startup hook landed 1 FastLED.watchdog().begin(15000) and feed() no longer gated to ESP32-only
WDOG_CS_DBG bit inversion 1 Set DBG=0 (pause in debug — developer-friendly) not 1 (run in debug)
Proper disable() + PRIMASK save/restore in feed() 1 First round of PRIMASK migration
P0 SRSR bits / HIGH PRIMASK in begin() / MEDIUM DSB barrier / nRF52 HALT / K20 PRIMASK 1 Agent-found round of fixes
fl::u32 not uint32_t for PRIMASK locals 1 StdintTypeChecker fix
noInterrupts() host-stub gate 1 #if !defined(FL_IS_STUB) && !defined(FL_IS_WASM) so the unit-test DLL build compiles
Stray-file cleanup 1 Removed a -r file accidentally committed by a shell tool

Test plan

  • bash compile teensy41 --examples AutoResearch — clean compile
  • bash test fl_wdt_watchdog --debug — 15/15 host stub tests pass under ASAN/UBSAN
  • bash lint --cpp — clean
  • Hardware verification on Teensy 4.0 — flashed, deliberateHang RPC triggered the noInterrupts/while(1) hang path, WDT fired after the configured 15 s, chip reset, USB re-enumerated, device was reflashable. Cycle repeated twice for confirmation.

Follow-ups (not blocking)

  • Watchdog::onTimeout(fl::function<void()>) overload — currently returns false on Teensy 4 (allocator-safe trampoline TBD)
  • Persistent crash counter / safe-mode flag backing for Teensy 4 → OCRAM2 retained region above CrashReport at 0x2027FF80 (right now persist storage is in-RAM only)
  • Non-allocating reset/crash classification API — separate design issue being filed alongside this PR

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added boot diagnostics for Teensy 4 including reset cause reporting and crash information.
    • Added RPC endpoint for deliberate watchdog testing.
  • Bug Fixes

    • Fixed watchdog initialization to prevent reset-loop issues on Teensy 4.
    • Improved watchdog interrupt state preservation across ARM platforms.
    • Enhanced debug halt behavior for nRF52 watchdog.

zackees and others added 12 commits June 4, 2026 02:34
…search hang trigger

Replaces the third-party tonton81/WDT_T4 library dependency with a direct
iMXRT1062 RTWDOG (WDOG3) register implementation via <imxrt.h>, which is
bundled with the Teensyduino core (no PlatformIO lib_deps required).

Implementation:
- 32-bit unlock key 0xD928C520 to WDOG3_CNT (relies on CS.CMD32EN=1, the
  reset default; we restore it in the new CS so future feeds/refreshes
  also use 32-bit keys)
- Wait for CS.ULK to confirm the unlock window opened
- Program TOVAL, WIN=0 (no windowed mode), and CS with EN+CMD32EN+UPDATE+
  PRES+CLK(LPO)+DBG
- Wait for CS.RCS to confirm reconfigure complete
- Refresh uses single 32-bit store 0xB480A602 to WDOG3_CNT
- Whole sequence runs inside __disable_irq()/__enable_irq() so an ISR
  cannot tear the unlock-to-write window (16 bus clocks at 600 MHz is
  ample but fragile against interrupts)

Timing: LPO clock (32 kHz nominal) + /256 prescaler → 8 ms per TOVAL count.
Max timeout clamped to 120 s for sanity (hardware ceiling is ~524 s).

Reset cause read from SRC_SRSR with write-1-to-clear so subsequent boots
see only their own cause.

Dispatcher swapped the FL_HAS_INCLUDE guard from Watchdog_t4.h to
imxrt.h, which IS bundled with the Teensy core and is always available
in any Teensy build.

Autoresearch wiring (examples/AutoResearch/):
- setup() now arms FastLED.watchdog().begin(15000) and checks
  isInSafeMode() / lastResetWasWatchdog() per the documented usage
  pattern
- loop() now calls feed() + markCleanShutdown() after the work
- New deliberateHang RPC (AutoResearchRemote.cpp): host calls the RPC,
  device sends ACK, then the main loop catches the flag, disables
  interrupts and spins forever — the watchdog must fire within the
  configured timeout and reset the chip
- New deliberate_hang_requested field on AutoResearchState

Test plan:
1. bash compile teensy41 --examples AutoResearch (verified PASSING)
2. Flash to a connected Teensy 4 via Teensy Loader / pio run -t upload
3. Open serial: device prints [SETUP] then [recovery] if a prior boot
   was killed by the WDT
4. Send {"jsonrpc":"2.0","method":"deliberateHang","id":1} via the
   AutoResearch RPC channel
5. Device prints "[deliberateHang] entering forced-hang loop NOW" and
   stops responding
6. ~15 seconds later device should reset, USB re-enumerates
7. After reset, device boots again and prints [recovery] crash#1
8. Confirm device remains reflashable via Teensy Loader

The previous WDOG3 attempt (AutoResearch.ino:204-214 TODO, since
superseded) failed because it wrote CS without the proper unlock + RCS
wait, leaving the watchdog half-configured and firing immediately. This
implementation follows the iMXRT1062 reference manual sequence exactly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Hardware testing on a real Teensy 4.1 revealed that the bare-register
WDOG3 init in src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp has
a bug causing a fast reset loop (~1.3 s) on actual hardware — the
timeout request of 15 s wasn't being honored. The unified
FastLED.watchdog() API surface itself works; the issue is specifically
in the iMXRT1062 RTWDOG unlock/CS configuration sequence which needs
more bit-position verification against the iMXRT1062 reference manual.

Conservative fix: gate the watchdog.begin()/feed()/markCleanShutdown()
calls in AutoResearch to ESP32 builds only (where the wrapping around
fl::watchdog_setup() is fully verified). The unified API is still
compiled into every build via FastLED.watchdog() so sketches that opt
in can use it; AutoResearch just defers arming on Teensy until the
bare-register impl is verified.

The deliberateHang RPC and the safe-mode-on-boot recovery hook remain
in place so they can be enabled per-platform as each backend matures.

Validates the original goal (forced hang -> reboot -> reflash):
the broken-bare-register firmware put the Teensy 4 in a continuous
reset loop, and the device remained fully reflashable throughout —
two successful flashes over the bad firmware via teensy_loader_cli
after a HalfKay button press. The MKL02 bootloader recovery path is
unaffected by any firmware-side watchdog bug.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Strong hypothesis for the previous reset loop: writes to WDOG3_*
registers without the CCM clock gate enabled either silently fail or
cause a bus fault → HardFault → instant reset. imxrt.h explicitly
notes "WDOG3 requires CCM_CCGR5_WDOG3".

Changes:
- begin() now sets CCM_CCGR5_WDOG3(3) (clock always on) BEFORE any
  WDOG3_CNT / WDOG3_CS access
- Both ULK and RCS spin loops now have a 1M-iteration bound — if the
  clock gate or unlock didn't take effect for any reason, return
  gracefully instead of hanging forever (and the next feed() or
  begin() can be safely re-attempted)

AutoResearch.ino diagnostic prints on every Teensy 4 boot:
- SRC_SRSR register value + decoded bit causes (WDOG3 / POR / LOCKUP /
  PIN / JTAG-SW)
- The bundled Teensy CrashReport if non-empty (decodes HardFault PC/LR
  + fault registers)
- SRC_SRSR write-1-to-clear so the next boot sees only its own cause

These two together will tell us definitively whether the reset loop
was: (a) WDOG3 firing because my init was wrong, (b) HardFault because
my init crashed the bus, or (c) something else entirely (e.g. an
AutoResearch peripheral bug unrelated to the watchdog).

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

ExampleSerialChecker and IsHeaderIncludeChecker fixes flagged by Stop hook
after the previous diagnostic-add commit:

- examples/AutoResearch/AutoResearch.ino: each Serial.println in the Teensy 4
  reset-cause + CrashReport print block now has `// ok serial - boot
  diagnostic` (or "bundled Teensy CrashReport" / "boot diagnostic flush").
  Serial.printf is banned outright by SerialPrintfChecker; replaced with
  Serial.print + Serial.println(value, HEX).
- src/platforms/arm/stm32/watchdog_stm32.impl.hpp: added the missing
  `platforms/arm/stm32/is_stm32.h` include so FL_IS_STM32_H7 has a
  declared source.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Stop hook caught: examples/AutoResearch/AutoResearch.ino:528 uses
noInterrupts() (Arduino macro) inside the deliberateHang handler. The
host stub build (tests/shared/example_dll_wrapper_template.cpp) compiles
the .ino into a DLL for unit-test infrastructure and doesn't have
noInterrupts() defined.

Guard with #if !defined(FL_IS_STUB) && !defined(FL_IS_WASM). On real
hardware noInterrupts() still runs; on host the while(1) below still
spins and prevents feed(), which is the actual hang we're testing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The iMXRT1062 RTWDOG default state at chip reset is CS=0x2980 (EN=1,
CLK=LPO, CMD32EN=1) with TOVAL=0x400 ≈ 32 ms. The Teensy 4 core's
startup.c does NOT touch WDOG3, so by spec the chip should reset 32 ms
into every boot. In practice it doesn't because most sketches stay in
WAIT mode (where WDOG3 stops counting per CS.WAIT default = 0).

This is fragile though: any sketch that does ≥32 ms of busy-loop work in
setup() before going idle can be killed by the default RTWDOG state.
This commit adds a `startup_early_hook` override that runs in FLASHMEM
before `main()` and before ITCM is initialized. It:

1. Enables the CCM_CCGR5_WDOG3 clock gate so the WDOG3 registers are
   addressable (imxrt.h: \"WDOG3 requires CCM_CCGR5_WDOG3\").
2. Unlocks WDOG3 with the 32-bit key 0xD928C520 (works at reset because
   CS.CMD32EN=1).
3. Writes a new CS with EN=0 (disabled), preserving CMD32EN+UPDATE+CLK
   so a future Watchdog::begin() can re-arm.

Both spin loops are bounded — if the unlock or reconfigure never
completes (e.g., clock gate didn't take), we'd rather continue and let
the watchdog bite than hang forever.

Hardware verification on Teensy 4.1 was confounded by an unrelated USB
enumeration issue at the test port (matched on Blink with zero watchdog
code), so this commit is functionally tested against the iMXRT1062 RM
register sequence but not yet end-to-end on hardware. The recovery
sequence is the standard one used by Watchdog_t4 / the iMXRT RM and
is the safe direction regardless.

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

Removes the temporary ESP32-only gate that was added during the Teensy 4
USB-bisect debugging. With the `startup_early_hook` WDOG3 disable now in
place to clean any persistent peripheral state, the bare-register
begin() path can re-arm cleanly via the unlock → write → RCS-wait
sequence. feed() in loop() is now unconditional so the WDT actually
gets refreshed on every supported platform.

The watchdog arming is gated only by the `FastLED.watchdog().begin()`
call site itself — on platforms whose impl falls through to the noop
(or whose optional library isn't installed) the calls are zero-cost
no-ops, so this stays universally portable.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Per iMXRT1062 RM 65.6.1, RTWDOG_CS bit 2 (DBG) is "Debug Enable" with
inverted semantics from what my comment claimed:
- DBG=1 → watchdog runs in debug mode (kills debugger UX)
- DBG=0 → watchdog pauses in debug mode (developer-friendly default)

Same applies to STOP and WAIT bits. All three should be 0 for a normal
sketch so the watchdog pauses in low-power modes and during debugging
sessions. Reset default is 0 for all three, which is what we want.

Removes `WDOG_CS_DBG` from the begin() CS write and corrects the comment
block.

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

Two correctness improvements to the bare-register RTWDOG path:

1. feed() and begin() now use mrs/cpsid/msr to save the prior PRIMASK
   state and restore it on exit. The previous __disable_irq() /
   __enable_irq() pair unconditionally re-enabled IRQs even when the
   caller had them off (e.g. a feed() from inside an ISR). Save/restore
   matches the pattern used by CMSIS-style critical sections.

2. disable() now actually disables WDOG3 instead of re-arming with the
   max timeout. The unlock sequence + CS write with EN=0 is the same
   path begin() uses; CS.UPDATE was set to 1 by the prior begin() (or
   by startup_early_hook), so the disable reconfigure is allowed.

Both unlock-window and RCS-complete spin loops are still bounded at
1,000,000 iterations (~1.7 ms at 600 MHz) so a stuck peripheral doesn't
hang the chip — bail and restore PRIMASK if either bit never sets.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…RF52 HALT, K20 PRIMASK

Round of fixes from a 4-agent code review. The big one:

**P0 CRITICAL — SRC_SRSR bit positions were all wrong** in
`translateSrcSrsr` and AutoResearch.ino's boot-cause diagnostic. Used
hardcoded shifts (1u << 16 for WDOG3, 1u << 4 for LOCKUP, etc.) that
were off by 1–9 bits in different places. `lastResetWasWatchdog()` was
returning false after every WDOG3 reset, breaking the crash-counter
recovery path entirely. Fixed by using the `SRC_SRSR_*_B` named macros
from `<imxrt.h>` (which agree with NXP MCUXpresso SDK
`SRC_SRSR_*_SHIFT`). Affected:
- `src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp::translateSrcSrsr`
- `examples/AutoResearch/AutoResearch.ino` boot diagnostic prints

**HIGH — begin() PRIMASK clobber**. After save/restore migration, the
two `__enable_irq()` calls in `begin()`'s success path and RCS-spin
timeout exit were left in place. They would unconditionally re-enable
interrupts even if the caller had them disabled. Replaced with
`msr primask, %0` restore. `feed()` and `disable()` were already
correct.

**MEDIUM — Missing DSB/ISB after CCM_CCGR5 write**. NXP MCUXpresso CCM
driver inserts barriers after every clock-gate write; the iMXRT1062 RM
recommends the same. Added `dsb; isb` between the CCGR5 store and the
first WDOG3 register access in both `begin()` and the AutoResearch
startup_early_hook.

**Major — nRF52 CONFIG HALT bit inversion**
(`src/platforms/arm/nrf52/watchdog_nrf52.impl.hpp`). Was writing
`CONFIG = 1u` (SLEEP=1, HALT=0) with a comment claiming "pause in
debug" — actually the watchdog kept counting through a debugger break.
Same bug class as the Teensy 4 WDOG_CS_DBG inversion. Now writes
`(1u << 0) | (1u << 3)` (SLEEP=1, HALT=1) for true pause-on-debug.

**Major — K20 PRIMASK clobber**
(`src/platforms/arm/k20/watchdog_k20.impl.hpp`). Same class of bug as
pre-fix Teensy 4 — naked `__disable_irq()/__enable_irq()` pairs in
both `k20UnlockAndConfigureWdog` and `feed()`. Replaced with mrs/cpsid/
msr save+restore. Also corrected the misleading STCTRLH comment.

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

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR extends FastLED's watchdog support across multiple ARM platforms and adds RPC-triggered deliberate hang testing to the AutoResearch sketch. It refactors K20 and mxrt1062 watchdog implementations to safely preserve interrupt state, switches mxrt1062 from a Teensy wrapper to direct register access, and refines nRF52 and STM32 configurations.

Changes

Watchdog implementation and deliberate hang testing

Layer / File(s) Summary
AutoResearch RPC hang state and endpoint
examples/AutoResearch/AutoResearchRemote.h, examples/AutoResearch/AutoResearchRemote.cpp
Adds deliberate_hang_requested flag to AutoResearchState and implements the deliberateHang RPC endpoint that sets the flag to trigger device hang for watchdog testing.
AutoResearch sketch watchdog integration and Teensy4 diagnostics
examples/AutoResearch/AutoResearch.ino
Adds Teensy4 early startup hook to disable WDOG3, implements boot diagnostics in setup() that print and clear reset cause registers and crashed report, and extends loop() to feed watchdog, mark clean shutdowns, and trigger RPC-requested deliberate hangs with interrupt masking.
Platform watchdog dispatcher routing
src/platforms/watchdog.impl.cpp.hpp
Updates Teensy 4.x platform detection condition from Watchdog_t4.h presence to imxrt.h presence, affecting which watchdog implementation is selected during compilation.
K20 watchdog PRIMASK-safe interrupt masking
src/platforms/arm/k20/watchdog_k20.impl.hpp
Modifies K20 watchdog unlock/configure and feed sequences to save and restore the caller's PRIMASK (interrupt mask state) instead of unconditionally disabling and re-enabling interrupts, preventing unexpected IRQ re-enablement in ISR contexts.
mxrt1062 bare-metal RTWDOG3 implementation
src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp
Replaces Teensy Watchdog_t4 wrapper with direct RTWDOG3 register access: introduces clock gating, unlock/refresh constants, bounded polling, PRIMASK-safe interrupt masking, and ability to fully disable the watchdog; updates reset-cause translation to use imxrt.h SRC bit-mask defines and clear SRC_SRSR after reading.
nRF52 debug pause and STM32 header refinements
src/platforms/arm/nrf52/watchdog_nrf52.impl.hpp, src/platforms/arm/stm32/watchdog_stm32.impl.hpp
Updates nRF52 watchdog CONFIG register to explicitly set debug-halt pause behavior via bitmask; adds STM32 identification header include to ensure platform-specific conditional logic is available.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • FastLED/FastLED#2744: Directly implements Phase 2 goal of adding real per-platform hardware watchdog implementations (mxrt1062, K20, nRF52, STM32).
  • FastLED/FastLED#2731: Implements the unified FastLED.watchdog() API usage and per-platform pieces proposed in the unified watchdog architecture.

Possibly related PRs

  • FastLED/FastLED#2745: Teensy 4/iMXRT1062 watchdog changes overlap with per-platform watchdog hardware implementation work.
  • FastLED/FastLED#2738: AutoResearch and example code depend on the unified fl::Watchdog API and FastLED.watchdog() accessor introduced in that PR.

Poem

🐰 Watch the dogs, all platforms guard,
Seventeen lines of interrupt hard!
Teensy wakes with early grace,
Reset whispers leave a trace—
Now we test the watchdog's bite! 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: a bare-register WDOG3 implementation for Teensy 4 (iMXRT1062) with hardware verification.
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/teensy4-wdt-bare-registers

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Infer (1.2.0)
examples/AutoResearch/AutoResearchRemote.cpp

In file included from examples/AutoResearch/AutoResearchRemote.cpp:14:
examples/AutoResearch/AutoResearchRemote.h:14:10: fatal error: 'fl/stl/stdint.h' file not found
14 | #include "fl/stl/stdint.h" // for uint32_t, uint8_t
| ^~~~~~~~~~~~~~~~~
1 error generated.
examples/AutoResearch/AutoResearchRemote.cpp:2792:5-12: ERROR translating statement 'ReturnStmt'
Aborting translation of method 'AutoResearchRemoteControl::startBleRemote' in file 'examples/AutoResearch/AutoResearchRemote.cpp': "Assert_failure src/clang/cAst_utils.ml:249:53"
Uncaught Internal Error: "Assert_failure src/clang/cAst_utils.ml:249:53"
Error backtrace:
Raised at ClangFrontend__CAst_utils.get_decl_from_typ_ptr in file "src/clang/cAst_utils.ml", line 249, characters 53-65
Called from ClangFrontend__CTrans.CTrans_funct.get_destructor_decl_ref in file "src/clang/cTrans.ml", line 658, characters 12-59
Called from ClangFrontend__CTrans.CTrans_funct.destructor_calls.(fun) in file "src/clang/cTrans.ml", li

... [truncated 2200 characters] ...

in file "src/istd/IExn.ml" (inlined), line 13, characters 2-50
Called from ClangFrontend__CTrans.CTrans_funct.instruction_log.(fun) in file "src/clang/cTrans.ml", line 4784, characters 10-1023
Called from ClangFrontend__CTrans.CTrans_funct.instruction in file "src/clang/cTrans.ml" (inlined), line 4765, characters 38-71
Called from ClangFrontend__CTrans.CTrans_funct.exec_with_node_creation in file "src/clang/cTrans.ml" (inlined), line 104, characters 20-38
Called from ClangFrontend__CTrans.CTrans_funct.get_clang_stmt_trans in file "src/clang/cTrans.ml" (inlined), line 5395, characters 4-69
Called from ClangFrontend__CTrans.CTrans_funct.get_custom_stmt_trans in file "src/clang/cTrans.ml", line 5401, characters 8-55
Called from ClangFrontend__CTrans.CTrans_funct.exec_trans_instrs.exec_trans_


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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/platforms/watchdog.impl.cpp.hpp (1)

16-16: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Stale documentation: WDT_T4 reference no longer accurate.

The implementation now uses bare-metal RTWDOG3 register access, but this docstring still mentions (WDT_T4<WDT3>).

📝 Suggested fix
-///   - Teensy 4 (T4.x)  → `platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp` (WDT_T4<WDT3>)
+///   - Teensy 4 (T4.x)  → `platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp` (bare-metal RTWDOG3)
🤖 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/watchdog.impl.cpp.hpp` at line 16, Update the stale doc comment
that references "WDT_T4<WDT3>" in watchdog.impl.cpp.hpp to reflect the current
implementation: remove the `(WDT_T4<WDT3>)` text and replace it with a short
note that this implementation uses bare-metal RTWDOG3 register access (RTWDOG3),
so the documentation matches the actual code paths using RTWDOG3 rather than the
old WDT_T4 template reference.
🤖 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.

Outside diff comments:
In `@src/platforms/watchdog.impl.cpp.hpp`:
- Line 16: Update the stale doc comment that references "WDT_T4<WDT3>" in
watchdog.impl.cpp.hpp to reflect the current implementation: remove the
`(WDT_T4<WDT3>)` text and replace it with a short note that this implementation
uses bare-metal RTWDOG3 register access (RTWDOG3), so the documentation matches
the actual code paths using RTWDOG3 rather than the old WDT_T4 template
reference.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3eba3cab-8979-460a-8fd2-a8ca597f796c

📥 Commits

Reviewing files that changed from the base of the PR and between 713edd6 and a0d3b39.

📒 Files selected for processing (8)
  • examples/AutoResearch/AutoResearch.ino
  • examples/AutoResearch/AutoResearchRemote.cpp
  • examples/AutoResearch/AutoResearchRemote.h
  • src/platforms/arm/k20/watchdog_k20.impl.hpp
  • src/platforms/arm/mxrt1062/watchdog_mxrt1062.impl.hpp
  • src/platforms/arm/nrf52/watchdog_nrf52.impl.hpp
  • src/platforms/arm/stm32/watchdog_stm32.impl.hpp
  • src/platforms/watchdog.impl.cpp.hpp

@zackees
zackees merged commit 47ad88e into master Jun 4, 2026
9 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 4, 2026
zackees added a commit that referenced this pull request Jun 5, 2026
…G_AUTO()

Replace the ESP32-only `fl::watchdog_setup(15000)` prototype call in setup()
with a single `FL_WATCHDOG_AUTO()` at the top of loop(). The new macro is
cross-platform — ESP32 / Teensy 4 / Teensy 3 / RP2040 / nRF52 / STM32 /
SAMD / Apollo3 / MGM240 / AVR — and falls through to a safe noop on any
platform without a real WDT.

What FL_WATCHDOG_AUTO() does that the prototype didn't:
- Lazily arms the WDT on first call (no explicit setup() ordering needed)
- Prints prior-boot reset/crash diagnostic via fl::println
- Pauses 3 s on a crash so the developer can read the message before
  loop() repaints serial output
- Feeds the WDT on BOTH ctor and dtor (start + end of each iteration)
- Detects nested guards at runtime (one-shot warning if the user
  accidentally puts two macros in the same call stack)

Also removes the stale "Teensy WDOG3 DISABLED — bricks the board"
comment block — the WDOG3 reset-loop bug was fixed in PR #2753 via
bare-register initialization and the CCM_CCGR5_WDOG3 clock-gate fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 5, 2026
…stic into platform impl (#2763)

* refactor(autoresearch): adopt unified fl::Watchdog API via FL_WATCHDOG_AUTO()

Replace the ESP32-only `fl::watchdog_setup(15000)` prototype call in setup()
with a single `FL_WATCHDOG_AUTO()` at the top of loop(). The new macro is
cross-platform — ESP32 / Teensy 4 / Teensy 3 / RP2040 / nRF52 / STM32 /
SAMD / Apollo3 / MGM240 / AVR — and falls through to a safe noop on any
platform without a real WDT.

What FL_WATCHDOG_AUTO() does that the prototype didn't:
- Lazily arms the WDT on first call (no explicit setup() ordering needed)
- Prints prior-boot reset/crash diagnostic via fl::println
- Pauses 3 s on a crash so the developer can read the message before
  loop() repaints serial output
- Feeds the WDT on BOTH ctor and dtor (start + end of each iteration)
- Detects nested guards at runtime (one-shot warning if the user
  accidentally puts two macros in the same call stack)

Also removes the stale "Teensy WDOG3 DISABLED — bricks the board"
comment block — the WDOG3 reset-loop bug was fixed in PR #2753 via
bare-register initialization and the CCM_CCGR5_WDOG3 clock-gate fix.

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

* refactor(watchdog/mxrt1062): move boot diagnostic into platform impl

Previously `examples/AutoResearch/AutoResearch.ino` had a
`#if defined(FL_IS_TEENSY_4X)` block that decoded SRC_SRSR bits and dumped
the bundled Teensy `CrashReport` directly via `Serial.print`. That was
exactly the kind of platform-specific surfacing the unified `fl::Watchdog`
API exists to abstract away — user code shouldn't need to know about
WDOG3_RST_B vs LOCKUP_SYSRESETREQ bit positions.

Moving the boot diagnostic into the Teensy 4 watchdog impl
(`watchdog_mxrt1062.impl.hpp::mxrt1062PrintBootDiagnosticOnce()`) so it
runs from `Watchdog::begin()` on its first call, before any WDT writes.
SRC_SRSR is write-1-to-clear so the next boot reads only its own cause.

Now every Teensy 4 sketch that calls `FL_WATCHDOG_AUTO()` or
`FastLED.watchdog().begin()` gets the prior-boot SRC_SRSR bit decode +
CrashReport print automatically.

AutoResearch.ino loses 30 lines of platform-`#ifdef`'d boot diagnostic
code; the same information now prints through the API.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
pull Bot pushed a commit to manmuqingshan/FastLED that referenced this pull request Jun 5, 2026
…— no more HardFault (closes FastLED#2772)

`flexioRxBenchmark` RPC was hanging the firmware on the dev-bench Teensy
4.0 and triggering a LOCKUP HardFault reset (SRC_SRSR=0x2, CFSR=0x400
IMPRECISERR, crash addr inside `FlexIoRxChannelImpl::begin`).

Three concrete bugs, fixed together (smallest patch that satisfies the
issue's "convert hard-reset into recoverable error" success criterion):

1. **Wrong CTRL register offset** — the FLEXIO1 Control register is at
   `+0x008`, not `+0x000`. Offset 0x000 is `VERID` (Version ID,
   read-only). Cross-referenced against Teensy core's `imxrt.h`:
     #define FLEXIO1_VERID  (IMXRT_FLEXIO1.offset000)
     #define FLEXIO1_CTRL   (IMXRT_FLEXIO1.offset008)
   Writing the software-reset bit (`1u << 1`) into VERID is silently
   ignored on iMXRT1062 with the FLEXIO1 clock gate on, but the
   subsequent read-back for the spin-wait `while (CTRL & 2)` lands on
   VERID too — and because the FLEXIO module's actual CTRL hadn't
   been touched, the spin never terminated. Combined with what the
   crash report identified as an imprecise data-bus error, the WDT
   eventually fired (SYSRESETREQ via LOCKUP).

   The existing FlexIO TX driver
   (`flexio_driver.cpp.hpp` line 85) has the same off-by-eight for
   FLEXIO2 but happens to not regress visibly — TX never reads CTRL
   back, and writes into VERID are accepted as no-ops, so the module
   comes up in its boot-default state which the TX path happens to
   work with. The TX file is left alone in this commit; a follow-up
   issue can normalize it.

2. **Source clock selection picked a gated PFD** — original code
   selected `CCM_CDCDR_FLEXIO1_CLK_SEL(3)` = PLL3_PFD3 (480 MHz / divider
   for ~120 MHz). Teensy core's `startup.c` programs the PLL3 PFD
   FRACs but leaves all four `CLKGATE` bits set (line 139:
   `CCM_ANALOG_PFD_480_SET = 0x80808080`), so PFD3 is gated off
   post-boot. Selecting a gated clock as the FLEXIO functional source
   means any register read inside the FLEXIO1 address space produces
   an imprecise data-bus error.

   Switched to `CLK_SEL(1)` = 24 MHz OSC (always-on, since the boot
   sequence runs from it before any PLL stabilizes). Updated PRED/PODF
   to /1·/1 and `kFlexIo1ClkMHz` from 120 → 24. Tick resolution drops
   from 8.3 ns to 41.7 ns, which is still ~30× finer than WS2812 T0H
   minimum and ~120× finer than the bench's 100 kHz square-wave
   half-period — well inside the σ tolerances the Phase 2 test asserts.

3. **Unbounded software-reset spin** — once the offset and clock
   issues are fixed, the spin loop in `flexio1_configure()` can still
   misbehave if the reset bit never clears (mis-config, unsupported
   source, etc). Mirrored the WDOG3 pattern from PR FastLED#2753:

     fl::u32 spin = 0;
     while (FLEXIO1_CTRL & (1u << 1)) {
         if (++spin > 1000000u) {
             FL_WARN("[FlexIO RX] FLEXIO1 software-reset bit never "
                     "cleared after 1e6 polls — clock gate likely "
                     "not on, refusing to enable RX (FastLED#2772). Pin=…");
             return false;
         }
     }

   `begin()` propagates the false return so the
   `flexioRxBenchmark` RPC reports `RxBeginFailed` instead of letting
   the device LOCKUP.

Also added explicit DSB+ISB memory barriers after the CCM clock-gate
write so the gate is committed before the first FLEXIO1 access.

## Hardware-bench validation on the attached Teensy 4.0 (COM20)

Before this commit:
  --- 2.1 / 1 kHz (1000 Hz / 200 ms) ---
    FAIL: no response or RPC error: None
  --- 2.2 / 10 kHz (10000 Hz / 100 ms) ---
    serial.serialutil.SerialException: ClearCommError failed
    (USB CDC re-enumerating after reset)

After this commit:
  --- 2.1 / 1 kHz (1000 Hz / 200 ms) ---
    FAIL: firmware reported failure: {'error': 'RxBeginFailed', …}
  --- 2.2 / 10 kHz (10000 Hz / 100 ms) ---
    FAIL: firmware reported failure: {'error': 'RxBeginFailed', …}
  --- 2.3 / 100 kHz (100000 Hz / 100 ms) ---
    FAIL: firmware reported failure: {'error': 'RxBeginFailed', …}
  summary: 0 pass / 3 fail out of 3 cases

Device uptime stayed monotonic 12 → 39 sec across the bench run — no
reset, no USB CDC bounce, no WDT fire. The bench still reports 3 case
FAILs because the captured-edge math isn't fully working yet
(downstream Phase 2 issue), but the **failure mode the issue
described** ("flexioRxBenchmark hangs the firmware") is gone — the
hardware path now degrades to a graceful `RxBeginFailed` JSON-RPC
response, which is exactly the conversion the issue's "Diagnostic
next steps" §1 asks for.

Closes FastLED#2772

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