Electronics · Optional embedded electronics and a sensor logger
Reset, watchdogs and power-mode recovery
Restarting a stalled controller is useful only if it returns to a defined state. Old output commands, uncommitted records and an interrupted clock can survive in different ways. A recovery design must decide what to retain, what to invalidate and what fresh evidence is required.
Lesson preparation and course links
Use the optional first-program/timer concepts and input-validity reasoning. The watchdog, journal, qualification and wake rules are defined here. The supplied trace/records form a complete investigation without enabling a watchdog, resetting a device, writing flash or installing firmware.
Back to the Electronics chapterAfter reading, you can
Trace a declared startup/stall/reset and retention-wake case. Tie watchdog feeding to meaningful progress, validate a recovery record, invalidate old freshness and require new evidence before normal operation. Separate a reset mechanism from its root cause and a successful example from general reliability.
Write the recovery policy before injecting a fault
This supplied-evidence task uses an indicator with explicit software states. STARTUP requests indicator OFF, initializes working counters to 0 and marks input freshness invalid. It restores only validated historical metadata, never an old ON command as the present output decision.
After configuration and clock checks, enter QUALIFY with count 0. Require two consecutive new valid samples before RUN. An invalid sample resets that count and keeps the OFF request. In RUN, a handled invalid sample enters DEGRADED with OFF and a diagnostic; returning to operation requires renewed qualification.
RUN means the normal indicator rule is allowed to use newly qualified data, not that the indicator is automatically ON. A foreground stall is an observed failure condition, not a state transition that stalled foreground code can reliably execute.
OFF here is a software request after initialization or a handled transition. Physical output defaults during a stall, reset transition or loss of power require separate hardware evidence. The supplied trace does not certify a continuously safe pin state.
| Condition | State/counter action | Indicator request/data policy |
|---|---|---|
| New boot | STARTUP; counters 0 | OFF; freshness invalid; restore history only |
| Configuration/clock checks complete | QUALIFY,count0 | OFF |
| New valid sample in QUALIFY | Increment consecutive count; RUN at 2 | OFF until qualified; then normal rule allowed |
| Invalid sample in QUALIFY | Reset count 0 | OFF; retain diagnostic |
| Handled invalid sample in RUN | DEGRADED | OFF; diagnose and requalify |
| Foreground stalls | No promised foreground action | Software alone cannot guarantee output safety |
Count from the last feed, not the noticed stall
A watchdog is a timer that can trigger reset if its required refresh/feed does not arrive. Use a declared nominal 2000 ms timeout with valid feeds at external times 0, 100 and 200 ms. The foreground stalls at 250 ms, and no further feed occurs.
The nominal expiry is 200+2000=2200 ms, which is 1950 ms after the stall. Adding 2000 ms to 250 ms would incorrectly start the watchdog interval at the observation of failure rather than the last feed.
This calculation assumes the watchdog’s selected clock/mode continues with the stated timeout. Clock tolerance, debug/sleep pauses, reset selection and implementation delay need their actual rules before this becomes a wall-time bound. No watchdog is enabled or reset injected for this lesson.
For a concrete application programming interface (API) boundary, MicroPython v1.26.0 documents that a started watchdog timer (WDT) cannot be stopped or reconfigured through that API; the RP2040 maximum timeout is 8388 ms. The 2000 ms fixture is an assumption inside that documented range, not a command executed here.
Feed after required progress and consistency checks
The feed must represent the health requirement. In this model, a supervisor feeds only after the required acquisition/control/record progress and consistency checks complete, or after an explicitly permitted diagnosed DEGRADED cycle completes its own obligations.
Blindly feeding from a periodic interrupt can keep the watchdog satisfied while the foreground remains stalled. Reaching a loop instruction or toggling a pin also does not prove that data are fresh or the answer is correct.
A watchdog can detect absence of its required feed under its clock/coverage conditions. It can miss wrong-but-progressing computation, an incorrectly permissive supervisor, a feed path that keeps running despite a failed task, or failures outside its reset coverage. A diagnosed sensor fault may be handled in DEGRADED without an endless reboot loop; that policy needs explicit allowed behaviour.
Keep an external timeline separate from each boot’s ticks
The complete supplied trace below uses an external reference timeline across two boots. Its times are expected case data, not a captured device log. Boot 2 begins at external 2200 ms; later 2300/2400 ms correspond to 100/200 ms after that point in this simplified timeline.
After reset, initialization requests OFF and invalidates freshness. At 2220 ms configuration is ready; the first new valid sample at 2300 ms gives qualification count 1 and still OFF. The second consecutive new valid sample at 2400 ms permits RUN.
Do not subtract a previous boot’s raw local ticks from a new boot’s ticks as though one uninterrupted clock existed. Preserve boot/session identity and the timebase definition. The externally maintained case timeline is what makes the cross-reset comparison meaningful here.
| External ms | Event | Boot | State/observation | Indicator policy |
|---|---|---|---|---|
| 0 | Validated cycle; feed | 1 | RUN | Normal rule allowed |
| 100 | Validated cycle; feed | 1 | RUN | Normal rule allowed |
| 200 | Last validated cycle; feed | 1 | RUN | Normal rule allowed |
| 250 | Foreground stalls; no more feed | 1 | Observed stall | No software safety guarantee |
| 2200 | Nominal watchdog reset; new boot | 2 | STARTUP | OFF request at initialization |
| 2220 | Cause/record/configuration checks complete | 2 | QUALIFY,count0 | OFF |
| 2300 | First new valid sample | 2 | QUALIFY,count1 | OFF |
| 2400 | Second consecutive new valid sample | 2 | RUN | Normal rule allowed |
Reset-cause evidence identifies a mechanism, not a diagnosis
For the named RP2040 example, the watchdog REASON register has TIMER and FORCE bits. A timer-trigger indication identifies that reset mechanism; it does not identify which function, blocked resource or supervision error caused progress to stop. Both bits zero for a hardware reset also does not uniquely prove power-on.
Record the raw supported cause evidence and its exact interpretation before giving a root-cause explanation. Combine it with last known progress, status and timing. “Watchdog timer reset after no feed” is supported by the declared case; “the sensor driver is definitely broken” is not.
RP2040 watchdog scratch registers can retain information through soft resets, but RUN/core-supply reset clears them and bootrom/SDK conventions may use them. They are not general durable storage across power loss or freely available bytes to overwrite without checking the implementation contract.
Validate a logical recovery record before selecting the newest
Use the supplied two-slot logical journal. A candidate is eligible only when its commit marker is true, state_version is compatible (=1 here), and its cyclic redundancy check (CRC32) matches. Among eligible records choose the highest generation; this fixture has no generation wrap. Commit is checked separately from the checksum.
For reproducibility, checksum the UTF-8 compact JSON object containing generation and payload, with sorted keys, no added spaces and no trailing newline. The protected payload includes state_version and last_committed_attempt. For example the generation 41 input is {"generation":41,"payload":{"last_committed_attempt":120,"state_version":1}}. The arithmetic uses the standard zlib.crc32 result as an unsigned 32-bit value.
Generation 41 stores 3374156396 and recomputes to the same value. Generation 42 stores 3499155122 but recomputes to 3499155123; it also has commit=false. Select 41 and report rollback/rejection of 42. Some volatile work after committed attempt 120 can be missing; do not silently imply it was durably saved.
CRC is an error-detection check with possible collisions, not authentication or proof against all corruption. Covering generation and payload avoids deliberately leaving those fields outside this check. Version compatibility and the commit marker remain independent requirements.
This is a logical selection fixture, not a flash/filesystem implementation. It does not establish atomic writes, durable ordering, endurance or behaviour during power failure. If no record is eligible, report that condition and use the defined startup/diagnostic policy rather than trusting an invalid slot.
| Generation | Payload: attempt/version | Committed? | Stored CRC32 | Computed CRC32 | Selection |
|---|---|---|---|---|---|
| 41 | 120 /1 | true | 3374156396 | 3374156396 | Eligible; selected |
| 42 | 121 /1 | false | 3499155122 | 3499155123 | Reject: uncommitted and mismatch |
Retention wake does not make retained data fresh
For a separate declared retention-sleep case, suppose RAM survives while acquisition stops for 1000 ms and the chosen local timer is paused. These are model assumptions, not a statement about every RP2040 or MicroPython sleep mode.
On wake, retain historical records as history, invalidate current freshness, re-establish the selected mode’s clocks/peripherals and require two new valid samples through QUALIFY. A paused timer that advanced by 0 cannot certify that a retained sample is only 0 ms older in external time.
Reset and retention wake can therefore take different physical paths while needing similar data requalification. Check which clocks, memories, pin states and watchdog functions continue in the actual chosen mode. Do not infer those properties from the words “sleep” or “low power.”
Write a recovery record with its remaining unknowns
Record the new boot/session identity; raw reset-cause evidence and supported interpretation; last known progress; selected/rejected journal generation and reason; initialization/freshness policy; new qualification samples and transition time; and any unknown or lost volatile work.
Then distinguish the supplied results: the missing-feed case reaches the declared nominal reset time, the record rule selects 41, and two new valid samples permit RUN. No actual fault injection, firmware execution or storage write was performed here; the complete investigation can be done from the supplied trace and logical records.
One successful recovery case supports those transitions under those assumptions. It does not establish all-fault reliability, a safe physical output throughout reset, correct answers from every task or a universal recovery deadline. Use the failure mechanism and evidence to choose the next specific test.
Recover history while rebuilding present trust
The last feed at external 200 ms gives a nominal expiry at 2200 ms. The observed stall begins at 250 ms, so the missing-feed wait after that observation is 1950 ms. Boot 2 then starts its own epoch; use the external timeline for cross-reset arithmetic.
Validate records instead of choosing 42 merely because it is newer. Its commit is false and checksum mismatches, so select committed, version-compatible, checksum-valid 41. Restore its historical checkpoint metadata; initialize current counters/output/freshness separately.
At 2300 ms one new valid sample is insufficient; keep the OFF request in QUALIFY,count1. At 2400 ms the second consecutive valid sample permits RUN. An invalid sample between them would reset the qualification count and require two subsequent valid samples.
Keep the causal claim bounded: a watchdog timer trigger does not identify the underlying failed function, and the software initialization request does not prove the physical pin remained safe during the stall/reset. Record those unknowns alongside the recovered state.
Try the reasoning
A nominal 2000 ms watchdog was last fed at 200 ms; the foreground stalls at 250 ms. When is expiry in the declared model?
Show the answer and reasoning
At 200+2000=2200 ms, or 1950 ms after the observed stall. The watchdog interval begins at the last feed. Actual clock/mode/reset delays need their own implementation bounds.
Why can unconditional periodic-interrupt feeding hide a foreground stall?
Show the answer and reasoning
The interrupt can keep refreshing the watchdog even though required foreground work stopped. Feed only after the required progress/consistency checks or an explicitly permitted healthy degraded-cycle contract.
Does a watchdog TIMER indication identify the failed function, and do zero reason bits prove power-on?
Show the answer and reasoning
No. TIMER identifies a reset trigger mechanism, not its underlying software/system cause. Both RP2040 watchdog reason bits are zero for hardware reset and do not uniquely distinguish power-on from other supported hardware-reset causes.
Which supplied journal generation is selected and why?
Show the answer and reasoning
41 is committed, version-compatible and checksum-valid. Newer 42 is uncommitted and its stored 3499155122 differs from computed 3499155123. Reject 42 and record rollback/possible lost volatile work; CRC is not authentication or a guarantee against every corruption.
May recovery restore an old ON command as the current indicator decision?
Show the answer and reasoning
No. Restore only validated historical metadata, initialize the OFF request/counters and invalidate freshness. Normal output decisions require new qualification. Physical pin behaviour through reset needs separate evidence.
Why is RUN not permitted at 2300 ms but permitted at 2400 ms in the supplied trace?
Show the answer and reasoning
The policy requires two consecutive new valid samples. The first gives QUALIFY,count1 with OFF; the second permits RUN. An intervening invalid sample resets that count, and RUN merely allows the normal indicator rule.
Does a local timer showing no advance during the declared 1000 ms retention sleep prove a retained value is fresh?
Show the answer and reasoning
No. That timer was assumed paused. Preserve historical data, invalidate freshness, re-establish the timebase/peripherals and acquire two new valid samples. Sleep-mode clock/retention properties are implementation-specific.
What does the logical CRC/commit test leave unproved?
Show the answer and reasoning
It checks the supplied record-selection rule and arithmetic. It does not establish atomic or durable flash writes, filesystem crash recovery, endurance, authentication or detection of every corruption. Generation wrap is outside this fixture.
What should a recovery report preserve, and what does one successful case establish?
Show the answer and reasoning
Preserve boot/cause/progress evidence, selected and rejected records, initialization/freshness decisions, qualification transitions and unknown/lost work. A successful supplied case supports those stated transitions only, not general reliability or a physical safety guarantee.
What to carry forward
Recovery rebuilds current trust from explicit evidence. Feed for meaningful progress, distinguish reset mechanism from cause, validate retained history and requalify fresh inputs. A restart or checksum success answers a narrower question than overall reliability.
References
Sources supporting this lesson’s explanations and examples.
- RP2040 Datasheet: A microcontroller by Raspberry PiRaspberry Pi LtdTechnical documentation · PDF
MicroPython project, runtime maintainer3 sources
- class WDT – watchdog timer — MicroPython v1.26.0 documentationMicroPython project, runtime maintainerTechnical documentation
- Working with filesystems — MicroPython v1.26.0 documentationMicroPython project, runtime maintainerTechnical documentation
- time – time related functions — MicroPython v1.26.0 documentationMicroPython project, runtime maintainerTechnical documentation