py32l020-watchdog-safety-6.ino
Activates the Independent Watchdog (IWDG) to reset the module if the software does not refresh within the set time.
The PY32L020 uses a watchdog based on the internal LSI clock. Once started, it cannot be stopped, only refreshed. Verify IWDG register addresses in the PY32L020 technical documentation. Refreshing must be done periodically in the main loop.
py32l020-watchdog-safety-6.ino
/*
* M5Stamp Timer Power 2 (PY32L020) - Independent Watchdog (IWDG)
* Platform: Arduino (PY32L020 Core) / HAL
* Purpose: Ensure system recovery from hangs.
*/
#include <Arduino.h>
// PY32L020 specific Watchdog handling might depend on Core version
// Using standard Arduino watchdog if implemented, or direct register access
void feedWatchdog() {
#ifdef HAL_WDG_MODULE_ENABLED
HAL_WDG_Clear(&hw_wdg_handle); // If HAL is available
#else
// Direct register write for PY32L020 IWDG
// Refresh Register address: 0x40003018 (Check PY32L020 Reference Manual)
*(volatile uint32_t*)0x40003018 = 0xAAAA;
#endif
}
void setup() {
Serial.begin(115200);
Serial.println("Starting System with Watchdog");
// Initialize and Start Watchdog
// Timeout depends on LSI clock (~40kHz) and prescaler/reload values
// Example: Setup for ~2 seconds timeout
// RCC Enable LSI (needed for IWDG)
RCC->CSR |= RCC_CSR_LSION;
while (!(RCC->CSR & RCC_CSR_LSIRDY));
// Enable IWDG Clock
RCC->APB1ENR |= RCC_APB1ENR_IWDGEN;
// Unlock IWDG
IWDG->KR = 0x5555;
// Set Prescaler (e.g., 64) and Reload Value
IWDG->PR = 0x06; // Prescaler 64
IWDG->RLR = 0xFFF; // Max reload
// Start IWDG
IWDG->KR = 0xCCCC;
Serial.println("Watchdog Started");
}
void loop() {
Serial.println("Loop Running...");
// Simulate work
delay(500);
// CRITICAL: Feed the Watchdog
feedWatchdog();
// Simulation of a hang (Uncomment to test reset)
// while(true);
delay(500);
// Feed again
feedWatchdog();
}