In this lesson, you will learn how to design automated routines that harvest and transmit a system's state from non-volatile memory following a spontaneous crash.
When a field-deployed device resets due to a fault, the volatile RAM is typically cleared, erasing the evidence of what caused the failure. To perform post-mortem analysis, we must implement a two-stage approach: the Crash Handler and the Extraction Routine.
The Crash Handler
Your firmware must contain a "Last Gasp" routine. When a hard fault or watchdog timeout occurs, the CPU jumps to a custom exception handler. Instead of simply resetting, this routine captures the Program Counter (PC), Link Register (LR), and critical stack frames into a dedicated, reserved section of non-volatile storage (like internal Flash or FRAM).
void HardFault_Handler(void) {
// Save current register state to a persistent memory partition
volatile uint32_t *crash_log = (uint32_t*)PERSISTENT_STORAGE_ADDR;
crash_log[0] = __get_MSP(); // Stack Pointer
crash_log[1] = get_pc_from_stack(); // Saved PC
crash_log[2] = FAULT_MAGIC_NUMBER; // Marker for bootloader
NVIC_SystemReset(); // Trigger reboot after saving
}
The Extraction Routine
After the system reboots, the bootloader or the main initialization sequence checks for the FAULT_MAGIC_NUMBER in the persistent storage. If found, the system switches into a "Diagnostic Mode." Rather than resuming normal operation, the firmware wraps the raw memory dump into a standardized format (like ELF core headers) and pushes it to the telemetry uplink.
By building an automated diagnostic routine that triggers upon detecting this "magic number," you transform a silent reset into a data-rich event. This allows you to reconstruct the call stack and register contents remotely, effectively bringing the "debugger" to the device, even when it is thousands of miles away in a production environment. Once the telemetry handshake confirms the dump has been uploaded, the routine clears the persistent flag, allowing the device to return to its standard operational state.
Key Takeaway: By using a reserved persistent memory partition to store register contexts during a fault, you can reconstruct the state of a remote device post-crash to identify the root cause of spontaneous resets.