Labs / MicroPython tutorials

15 WDT Watchdog Timer - Preliminary Documentation Tutorial

Author: Li Zisheng · Source: FreakStudio open documentation, v1.1.0 · License: CC BY 4.0

Contents

1. Hardware Explanation

1.1 Introduction to WDT Watchdog Timer

1.1.1 Introduction to WDT Watchdog Timer

In a single-chip microcomputer system, as its operating environment is usually complex and vulnerable to interference from factors such as external electromagnetic fields, the following problems may arise:

To address these issues, the Watchdog Timer (WDT) plays the following key roles in the system. The Watchdog Timer (WDT) is a hardware timer used to monitor the operating status of the system. Its main function is to prevent the system from getting stuck in an infinite loop or a frozen state. When the system software is running normally, it needs to reset the Watchdog Timer periodically. If the system malfunctions and fails to reset the Watchdog Timer in time, the timer will trigger a system restart or other predefined actions to ensure that the system can return to a normal state.

15 WDT Watchdog Timer - Preliminary Documentation Tutorial
The watchdog command has the highest priority among program interrupts: this means that no matter what task the system is executing, the reset signal of the watchdog timer can interrupt the current task and perform a reset.

The basic working principle thereof is as follows:

  1. Start the watchdog timer: The core of the watchdog timer is a simple countdown timer, which is used to reset the microprocessor after a specific time interval. When the watchdog timer is enabled, it will start counting down.
  2. Periodic Reset: A normally running program needs to periodically reset the watchdog timer before its countdown completes (commonly referred to as "feeding the watchdog" or "kicking the watchdog"), which is typically achieved by calling the function that resets the watchdog in the main program loop or a timer.
  3. System reset: If the watchdog timer counts down to zero without being reset, it will usually trigger a system reset (reboot), which helps the system recover from an abnormal state.

In terms of working principle, watchdogs can be divided into the independent watchdog (IWDG) and the window watchdog (WWDG):

Example image missing

15 WDT Watchdog Timer - Preliminary Documentation Tutorial
The window watchdog peripheral in the STM32. A window watchdog has an upper limit and a lower limit. Feeding the watchdog while the counter is between the window upper limit (set by the user) and the lower limit (0x40) does not generate a reset. The initial value of the window watchdog is a 7-bit down-counter; the initial value must be set by the user, with a maximum of 0x7F, and by setting the early wakeup interrupt bit in the configuration register, an interrupt can be generated when the counter decreases to 0x40.

In terms of composition structure, watchdogs can be divided into built-in watchdog peripherals and external watchdog chips:

In terms of implementation methods, watchdogs can be divided into software watchdogs and hardware watchdogs:

Here, when developing a project, it is recommended that you use the built-in watchdog timer peripheral and additionally equip an external watchdog chip: when the hardware of the MCU itself fails (such as power voltage fluctuation, clock failure, memory corruption, etc.), the built-in WDT may also be affected, making it unable to reset the system normally, while the external WDT can operate completely independently of the normal functions of the MCU, without being affected by the limitations of the MCU's internal resources.

Simply put, an external WDT provides an additional layer of security, enhancing the system's redundancy and reliability to prevent a single point of failure from crashing the entire system, ensuring that even in the worst-case scenario, the system can still safely reset and resume operation.

1.2 Introduction to the WDT Peripheral in Raspberry Pi Pico

The on-board RP2040 chip of the Raspberry Pi Pico has a built-in hardware watchdog timer (WDT) peripheral:

15 WDT Watchdog Timer - Preliminary Documentation Tutorial
The built-in watchdog peripheral of the Raspberry Pi Pico is attached to the APB bus

The watchdog timer of the RP2040 features a 24-bit counter with a maximum value of 0xFFFFFF (i. e. 16,777,215).

1.2.1 Watchdog Clock Input

In the RP2040 microcontroller, the reference clock used by the Watchdog Timer (WDT) clk_tick is driven by clk_ref:

RP2040 GPCLK0 1

clk_tick typically has a period of 1 microsecond (μs), which means the watchdog timer counts at 1-microsecond intervals, enabling it to accurately monitor the operating status of the system.

We can configure the TICK register to set the clock division ratio and adjust the time interval of the watchdog timer:

0x2c

1.2.2 Reset of the Watchdog Timer

The watchdog timer is reset via the rst_n_run signal. When the digital core power supply (DVDD) is powered on and stable, and the RUN pin is at a high level, rst_n_run signal is activated, causing the watchdog timer to reset.

rst_n_run is a reset signal, which is closely related to the power management and reset control logic of the chip. Earlier when we introduced the Raspberry Pi Pico, we mentioned the basic concept of the power-on finite-state machine: the power-on finite-state machine of the RP2040 is responsible for releasing the reset state of each internal hardware module of the chip in a specific order, and this process ensures that each module is initialized in the correct sequence during startup, so as to avoid conflicts or errors during the reset period.

15 WDT Watchdog Timer - Preliminary Documentation Tutorial
Power-on state machine restart sequence table

The reset of each module is controlled by the internal rst_n signal, and each module will generate a rst_done high-active reset completion signal after completing reset. The power-on finite-state machine waits for the rst_done signal of each module, and proceeds to the next module only after ensuring that all modules are correctly reset. After the power-on finite-state machine completes the reset operation for all modules, the rst_n_run signal is used to exit the specific reset state.This signal is typically used for modules that require initialization at startup but do not need to be reset during the power-on finite-state machine reset, such as ring oscillators, logic circuits in crystal oscillators, as well as clock dividers and watchdog timers that need to operate continuously.

1.2.3 Watchdog Counter

In the watchdog timer of the RP2040 microcontroller, the operation of the counter involves LOAD register and the CTRL register's TIME data bits:

0x04 31-24 23-0 0xffffff 2 RP2040
RP2040 23 0 0xffffff 0xffffff/2

Here, it should be noted that due to a logic error (as mentioned in the RP2040-E1 errata), the watchdog counter is decremented twice in each clk_tick cycle, which means the actual countdown period is half of the expected value. Therefore, when the value of the LOAD register is set to 0xffffff (i. e., 16,777,215), the watchdog timer will actually trigger a reset after 0xffffff / 2 clk_tick cycles.

Since the period of a clk_tick is typically 1 microsecond (μs), the time corresponding to the maximum counter value is:

16,777,215/(2*1,000,000) s = 8.388 s = 8388 ms

This means that the timing range of the watchdog timer is approximately from 1 microsecond to 500 milliseconds.

Meanwhile, we can control the CTRL register's PAUSE_DBG1, PAUSE_DBG0 and PAUSE_JTAG bits to pause the watchdog timer when processor 0 and processor 1 enter debug mode or the JTAG debug interface is used to access the bus, so as to prevent the watchdog timer from interfering with the debugging process.

We can also access the REASON register to obtain the cause of the last reset:

0x08 0 31 2 1 0x0

to determine whether the last reset was a forced reset triggered by the watchdog timer, or caused by a watchdog timer timeout or a hardware reset:

1.2.4 Scratch Registers and Magic Numbers

The watchdog timer of the RP2040 microcontroller includes eight 32-bit scratch registers, which can store information between soft resets of the chip:

RP2040 0x0c 8 SCRATCH0 SCRATCH7
RP2040 SCRATCH0 SCRATCH7 8 0x0c 0x10 0x14 0x18 0x1c 0x20

When the rst_n_run signal is triggered (for example, by toggling the RUN pin or powering on the digital core power supply DVDD again), these registers will be reset to their initial states.

In the case of non-power-on reset (Non-POR) or non-boot reset (Non-BOR), users can use these registers to specify a particular boot code. The Bootrom will check the specific "magic number" in these registers during startup, so as to determine whether to execute the user-defined boot code.

Here, a "magic number" refers to a special value used to verify data integrity, identify data formats, or confirm file structures:

  1. A magic number is used in the Scratch register of the watchdog timer to determine whether to execute the specific boot code
  2. This enables users to install their own boot handlers and skip the main boot sequence during non-power-on resets.

Wherein:

The Bootrom checks Scratch 4 and Scratch 5 for magic values: if these values match, the Bootrom clears Scratch 4 and transfers control to the specified code segment; if the magic values do not match, the Bootrom will not execute the user-defined boot code, and the system will boot according to the default boot sequence. Through this mechanism, users can control the execution of specific code or perform system debugging during system startup, which is very useful for system testing and debugging.

1.3 DS1232 External Watchdog Chip

1.3.1 Introduction to the DS1232 Chip

DS1232LPS-2 1 2 3 4 8 7 6 5 DS1232L

DS1232 is a microprocessor monitor chip launched by Maxim.

Its main functions are as follows:

Therefore, the DS1232 is commonly used in scenarios requiring high reliability such as microcontrollers and embedded systems.

1.3.2 Introduction to Pins of DS1232 Chip

DS1232 8-Pin 300-mil 16-Pin 118-mil 150-mil

DS1232 The pin functions of the chip are shown in the following table:

Pin Name

Function Description

VCC

Power Input (+ 5V)

GND

Power Ground

RST counter

Reset output (active low, connected to MCU RESET pin)

RST

Reset Output (Active High, Optional)

ST

Watchdog refresh signal input (high-to-low transition)

PBRST

External manual reset input (low-level triggered, internal debounce)

TOL

Power supply threshold selection (connect to GND = 4.75V, connect to VCC = 4.5V)

TD Watchdog Timeout Selection (the wiring determines 150ms/600ms/1.2s)

TD

Watchdog timeout selection (150ms/600ms/1.2s configurable via wiring)

NC

NC (No function, for SOIC package)

DS1232 4

Chip DS1232 requires a continuous series of pulses to be input to the ST pin during system operation; the time interval between these pulses is set by the TD pin. If the pulse interval exceeds the set value of the TD pin, the chip will output a reset pulse to the RST pin and the RST# pin to reset the microcontroller. This function is commonly referred to as a watchdog, and the series of pulses input to the watchdog is called "feeding the dog".

1.3.3 Internal Structure and Working Principle of the DS1232 Chip

DS1232

DS1232 The internal structure of the chip is shown in the figure, which mainly consists of the following parts:

DS1232 250ms

DS1232 monitors the VCC voltage via the power supply monitoring unit to detect whether it is lower than the set threshold; once an abnormality is detected, it immediately outputs a reset signal, and maintains a reset delay of at least 250ms after the power supply is restored to ensure system stability. Meanwhile, this chip supports key reset input, and will generate a reset pulse of no less than 250ms after internal debouncing. In addition, it has a built-in watchdog timer: if no trigger pulse from the processor is received within the set timeout period (150ms/600ms/1.2s), it will determine that the system is halted and automatically send out a reset signal.All reset requests pass through the delay processing unit and are then output uniformly by the output driver RST / RST̅, to ensure that the microprocessor receives reliable reset control.

1.3.4 Reference Application Circuits and Notes

DS1232 5V Z80
DS1232 DS1232LPS-2+T C1 C2

The figure above shows the peripheral circuit of the DS1232 chip, which monitors the undervoltage of VCC and generates a reset (RST high level, /RST low level) in case of abnormality, with a built-in watchdog at the same time:

Note that the DS1232 is designed for 5V operation. If the IO level standard of the MCU in use is 3.3V, ensure proper level compatibility or select a 3.3V monitoring chip to avoid damaging the MCU.

The following are the results of our module test. After powering on the module, we connected Channel 0 of the logic analyzer to the RST interface of the watchdog module:

When TD is connected to VCC, the pulse interval shall not be greater than 1.2 seconds, and a square wave with an input frequency of 2 Hz is recommended:

LA1010 0 10
DS1232 1.2s 0.6s 1.23905212s 1.8589498s 66.678573 0.537938141Hz 1.2

TD When floating, the pulse interval shall not exceed 600 ms, and a square wave with an input frequency of 10 Hz is recommended:

0ms 1000ms 530ms 500ms 0.15 30Hz

TD When connected to GND, the pulse interval shall not exceed 0.15 seconds, and a square wave with an input frequency of 30Hz is recommended:

0.13 0.53 133.1614 665.5343 20.081949 1.50255216

Here we can see that in practical applications, the watchdog feeding frequency needs to be higher than that specified in the chip datasheet. This is due to factors such as the internal timing accuracy error, sampling delay, and pulse width requirements of the DS1232, which make it highly likely to fail if the watchdog is strictly fed according to the theoretical limit. Therefore, in engineering practice, it is recommended to set the watchdog feeding period to 1/2 of the timeout period or even shorter.

In the provided datasheet, we can also see that the timing accuracy is approximately −58.33% / + 66.67%(relative to the typical value):

DS1232 1 62.5 150 250 600 1000 500 1200 2000

2. Software Control Method

2.1 Constructor of machine.WDT

The constructor of the machine.WDT class is as follows:

class machine.WDT(id=0, timeout=5000)

Construct a WDT watchdog object with the given parameters; once started, the WDT cannot be stopped or reconfigured.

The parameters are defined as follows:

  • id : Specifies the instance ID of the WDT. For most implementations, this parameter is fixed, typically 0, and it can be used to select a specific WDT instance in systems that support multiple watchdog timers.
  • timeout: Sets the timeout period of the watchdog (unit: milliseconds). The timeout period must be specified during initialization. Once created, the timeout period cannot be changed, and the WDT cannot be stopped. For rp2040 devices, the maximum timeout period is 8388 milliseconds.

2.2 Other Methods of machine.WDT

The machine.RTC class has other methods as well:

Method

Description

WDT.feed()

Feed the watchdog to prevent it from timing out and resetting the system. Applications should place this call after ensuring that the system is operating properly.

3. Application Examples

3.1 Built-in Watchdog Experiment

In the following code, we create a WDT object and set its timeout to 4 seconds (note that the timeout must not be less than approximately 2 seconds; if the timeout is set too short, the device will keep restarting continuously once the watchdog takes effect, making it impossible to flash programs or establish remote connections), which means that if the feed () method is not called within 2 seconds, the WDT will trigger a system restart.

Then a 30-second loop starts: in each iteration, the program prints the current test time, delays for 3 seconds, and then calls the feed () method to feed the watchdog to prevent the WDT from timing out. After 10 consecutive iterations, the loop is exited, the watchdog is no longer fed, and the device will reset shortly after.

The following code can be found in the material package we provide, in the elegance-devkit v1\Demo\52 WDG_Hardware folder.

The sample code is as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/8/15 3:12 PM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : WDT watchdog timer class experiment, using the Pico's built-in watchdog peripheral

# ======================================== Import Modules ========================================

# Import hardware-related modules
from machine import WDT
# Import time-related modules
import time

# ======================================== Global Variables ============================================

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information
print("FreakStudio : Built-in Watchdog Timer Test")

# Initialize the watchdog object
# Set the watchdog timer timeout to 4 seconds
wdt = WDT(timeout=4000)

# ========================================  Main Program  ===========================================

# Feed the watchdog 10 times in a loop
for i in range(10):
    # Print debug information
    print("FreakStudio : Run Test in {} seconds".format(i))
    # Delay 3s
    time.sleep(3)
    # Feed the watchdog
    wdt.feed()

# After running for 37 s, the watchdog timer times out and restarts
print("FreakStudio : Watchdog Timer Timeout, Restarting...")

The overall Sequence Diagram of the operation is shown as follows:

4000 4

Burn the code, open the terminal, and use mpremote to connect to the Raspberry Pi Pico, with the following output:

5 13

3.1 Application Experiment.mp4 899 KB

It can be seen that after the dog feeding is stopped, the watchdog timer will restart the device once the timeout period is reached.

3.2 Implementing Watchdog Experiments with Software Timers

In the example in the previous section, we used the built-in watchdog of the Raspberry Pi Pico to monitor the operating status of the system and restart the device, but it can be found in the documentation that the built-in watchdog also has some drawbacks:

0 5000

It mainly focuses on the following two parts:

In practical applications, when a program encounters a runaway or abnormal situation, we usually first attempt to fix the problem through recovery operations, such as reinitializing key modules, restarting partial functions, or performing log recording. The software watchdog is designed precisely for this purpose; in a microcontroller system, the software watchdog can be implemented by means of a timer or a counter.The principle is to use a timer or counter as the timing trigger source. The timer counts down continuously, and if it is not reloaded or "kicked" within the set time, the system is considered to have fallen into an infinite loop or become unresponsive, thus triggering the watchdog function, such as system reset or executing other safety operations.

In the code we provide below, we implement a multi-functional software watchdog based on timers, whose main features include:

It has the following methods and properties:

15 WDT Watchdog Timer - Preliminary Documentation Tutorial
15 WDT Watchdog Timer - Preliminary Documentation Tutorial

The code for the custom software watchdog class is as follows:

# Allocate the emergency exception buffer (must be placed before all interrupt code)
micropython.alloc_emergency_exception_buf(100)

# Software watchdog class
class SoftwareWatchdog:
    """
    Software watchdog class, implementing watchdog functionality using MicroPython's Timer.
    This class encapsulates timer-based watchdog logic, supporting timeout detection, feeding operations, state recording, trigger condition checking and recovery operations.
    By registering callback functions, users can customize the state recording, trigger condition and recovery operation logic.

    Attributes:
        timeout (int): Watchdog timeout, in milliseconds (default 4000 ms).
        debug (bool): Whether to enable debug mode (enabled by default).
        max_failures (int): Maximum number of consecutive feeding failures (default 1).
        reset_delay (int): Delay before triggering a reset, in milliseconds (default 3000 ms).
        feed_successful (bool): Feed flag, indicating whether the watchdog was fed successfully.
        timer (Timer): Software timer instance, used to periodically check the feeding status.
        feed_count (int): Counter of the number of feedings.
        trigger_count (int): Counter of the number of watchdog triggers.
        failure_count (int): Counter of consecutive feeding failures.
        _state_recorder (callable): User-defined state recording callback function.
        _trigger_condition (callable): User-defined trigger condition callback function.
        _recovery_handler (callable): User-defined recovery action callback function.

    Methods:
        __init__(self, timeout: int = 4000, debug: bool = True, max_failures: int = 1, reset_delay: int = 3000) -> None:
            Initialize the software watchdog instance.

        _initialize_timer(self) -> None:
            Initialize the timer and set the callback function.

        register_state_recorder(self, recorder: callable[[], None]) -> None:
            Register the status recording callback function.

        set_trigger_condition(self, condition: callable[[], bool]) -> None:
            Set the trigger condition callback function.

        register_recovery_handler(self, handler: callable[[], bool]) -> None:
            Register the recovery action callback function.

        _watchdog_callback(self, t: Timer) -> None:
            Timer callback function. Checks whether the watchdog was fed in time, and also records status and checks the condition to decide whether to trigger a reset.

        feed(self) -> None:
            Feed the watchdog and reset the feed flag.

        stop(self) -> None:
            Stop the watchdog timer.

        __del__(self) -> None:
            Destructor, ensures the timer resources are released.
    """
    def __init__(self, timeout: int = 4000, debug: bool = True, max_failures: int = 1, reset_delay: int = 3000) -> None:
        """
        Initialize the software watchdog.

        Args:
            timeout (int): Watchdog timeout, in milliseconds (default 4000 ms).
            debug (bool): Whether to enable debug mode (enabled by default).
            max_failures (int): Maximum number of consecutive feeding failures (default 1).
            reset_delay (int): Delay before triggering a reset, in milliseconds (default 3000 ms).

        Returns:
            None

        Raises:
            ValueError: If the parameters timeout, max_failures, or reset_delay are not positive integers, or debug is not a boolean.
        """
        # Check the entry parameters
        if not isinstance(reset_delay, int) or reset_delay <= 0:
            raise ValueError("reset_delay must be a positive integer")

        if not isinstance(timeout, int) or timeout <= 0:
            raise ValueError("timeout must be a positive integer")

        if not isinstance(max_failures, int) or max_failures <= 0:
            raise ValueError("max_failures must be a positive integer")

        if not isinstance(debug, bool):
            raise TypeError("debug must be a boolean value")

        # Set the timeout
        self.timeout = timeout
        # Set the debug mode
        self.debug = debug
        # Set the maximum number of failures
        self.max_failures = max_failures
        # Set the reset delay time
        self.reset_delay = reset_delay

        # Initialize the feed flag to False
        self.feed_successful = False
        # Initialize the software timer
        self.timer = Timer(-1)

        # Initialize the feed count
        self.feed_count = 0
        # Initialize the watchdog trigger count
        self.trigger_count = 0
        # Initialize the consecutive feed failure count
        self.failure_count = 0

        # Initialize the user-defined status recording function to None
        self._state_recorder = None
        # Initialize the user-defined trigger condition function to None
        self._trigger_condition = None
        # Initialize the recovery action callback function to None
        self._recovery_handler = None

        # Initialize the timer
        self._initialize_timer()

    def _initialize_timer(self) -> None:
        """
        Initialize the timer and set the callback function.

        Args:
            None

        Returns:
            None
        """
        # Initialize the timer, set the period and callback function
        self.timer.init(period=self.timeout, mode=Timer.PERIODIC, callback=lambda t: schedule(self._watchdog_callback, t))

    def register_state_recorder(self, recorder: callable[[], None]) -> None:
        """
        Register the status recording callback function.

        Args:
            recorder (callable): Callback function with no parameters and no return value, used to record status

        Returns:
            None

        Raises:
            TypeError: If the parameter recorder is not of callable type.
        """
        # Check whether recorder is a callable object
        if not callable(recorder):
            raise TypeError("State recorder must be callable")

        # Set the status recording callback function
        self._state_recorder = recorder

    def set_trigger_condition(self, condition: callable[[], bool]) -> None:
        """
        Set the trigger condition callback function.

        Args:
            condition (callable): Callback function with no parameters that returns bool; returning True means a restart is allowed to trigger.

        Returns:
            None

        Raises:
            TypeError: If the parameter condition is not of callable type.
        """
        # Check whether condition is a callable object
        if not callable(condition):
            raise TypeError("Trigger condition must be callable")

        # Set the trigger condition callback function
        self._trigger_condition = condition

    def register_recovery_handler(self, handler: callable[[], bool]) -> None:
        """
        Register the recovery action callback function.

        Args:
            handler (callable): Callback function with no parameters that returns a value, used to perform the recovery action; a return value of True means the recovery action succeeded, False means it failed.

        Returns:
            None

        Raises:
            TypeError: If the parameter handler is not of callable type.
        """
        # Check whether handler is a callable object
        if not callable(handler):
            raise TypeError("Recovery handler must be callable")

        # Set the recovery action callback function
        self._recovery_handler = handler

    # Use the @timed_function decorator to measure the run time of the SoftwareWatchdog._watchdog_callback method
    @timed_function
    def _watchdog_callback(self, t: Timer) -> None:
        """
        Timer callback function. Checks whether the watchdog was fed in time, and also records status and checks the condition to decide whether to trigger a reset.

        Args:
            t (Timer): Timer object (passed in automatically by Timer).

        Returns:
            None

        Raises:
            Exception: If an error occurs while executing the status recording callback function.
            Exception: If an error occurs while executing the recovery action callback function.
            TypeError: If the return value of the recovery action callback function is not of boolean type.
            Exception: If an error occurs while executing the trigger condition callback function.
        """

        # Read the feed flag atomically
        irq_state = disable_irq()
        feed_flag = self.feed_successful
        enable_irq(irq_state)

        # Check whether the watchdog was fed in time
        if not feed_flag:
            # Increase the consecutive failure count
            self.failure_count += 1
            # Increase the trigger count
            self.trigger_count += 1

            # If debug mode is on, print the trigger information
            if self.debug:
                print("[Watchdog] Triggered ({} failures, {} total triggers)".format(
                    self.failure_count, self.trigger_count))

            # Execute status recording (if registered)
            if self._state_recorder:
                try:
                    self._state_recorder()
                except Exception as e:
                    if self.debug:
                        print("[Error] Failed to record state:", str(e))

            # Check whether the consecutive failure count has reached the maximum
            if self.failure_count >= self.max_failures:

                # Flag indicating whether the recovery action succeeded
                recovery_successful = False

                # Try the recovery action
                if self._recovery_handler:
                    try:
                        if self.debug:
                            print("[Watchdog] Attempting recovery...")
                        # Try the recovery action
                        recovery_successful = self._recovery_handler()
                        # Check whether recovery_successful is a bool variable
                        if not isinstance(recovery_successful, bool):
                            raise TypeError("Recovery handler must return a boolean value")
                    except Exception as e:
                        if self.debug:
                            print("[Error] Recovery handler failed:", str(e))

                # Check whether the recovery action succeeded
                if recovery_successful:
                    # Reset the consecutive failure count
                    self.failure_count = 0
                    # Reset the should-trigger flag
                    self.should_trigger = False
                    if self.debug:
                        print("[Watchdog] Recovery successful, resetting failure count...")
                else:
                    # If recovery failed, check the trigger condition

                    # Trigger by default
                    should_trigger = True
                    # Check whether the trigger condition is registered
                    if self._trigger_condition:
                        try:
                            # Execute the trigger condition check
                            should_trigger = self._trigger_condition()
                        except Exception as e:
                            if self.debug:
                                print("[Error] Trigger condition check failed:", str(e))
                            # Trigger by default
                            should_trigger = True

                    # If the trigger condition is met, trigger a reset
                    if should_trigger:
                        if self.debug:
                            print("[Watchdog] Max failures reached, resetting system after %d ms..." %(self.reset_delay))
                        # Create a one-shot timer that performs the reset after the specified delay
                        self.reset_timer = Timer(-1)
                        self.reset_timer.init(period=self.reset_delay, mode=Timer.ONE_SHOT, callback=lambda t: reset())
        else:
            # Reset the consecutive failure count
            self.failure_count = 0

            # Atomic reset
            irq_state = disable_irq()
            # Reset the feed flag
            self.feed_successful = False
            enable_irq(irq_state)

    def feed(self) -> None:
        """
        Feed the watchdog and reset the feed flag.

        Args:
            None

        Returns:
            None
        """
        irq_state = disable_irq()
        self.feed_successful = True
        # Increase the feed count
        self.feed_count += 1
        enable_irq(irq_state)

        # If debug mode is on, print the feed time
        if self.debug:
            print("Watchdog fed at:", time.ticks_ms())

    def stop(self) -> None:
        """
        Stop the watchdog timer.

        Args:
            None

        Returns:
            None
        """
        # Stop the timer
        self.timer.deinit()
        if self.debug:
            print("Watchdog stopped.")

    def __del__(self):
        """
        Destructor: ensures the timer resources are released.

        Args:
            None

        Returns:
            None
        """
        self.timer.deinit()
        if self.debug:
            print("Watchdog resources released.")

It can be seen that before defining the class, we first allocate an emergency exception memory buffer, which is used to store the exception information when an exception occurs in the interrupt context, so as to ensure that even if an exception occurs in the interrupt, the exception information can be captured and recorded, which facilitates subsequent debugging and problem troubleshooting.

The basic principle of this class, as mentioned above, is to use the Timer module of MicroPython to create a periodic timer in the _initialize_timer () method, which regularly calls the _watchdog_callback callback function to check the watchdog feeding flag, thereby implementing a watchdog mechanism similar to hardware watchdog; when consecutive failure to feed the watchdog (i. e., the system fails to respond normally) is detected, it triggers a recovery operation or system reset to prevent the system from staying in an abnormal state for a long time.

The core method for implementing extended functions is the timer callback function _watchdog_callback:

15 WDT Watchdog Timer - Preliminary Documentation Tutorial

The process can be summarized as follows:

  1. Watchdog feeding detection: First, read the feed_successful flag to check whether a watchdog feeding operation has been performed. If no watchdog feeding signal is received within the current cycle (i. e., feed_successful is False), increment the consecutive failure count and total trigger count, and output debug information.
  2. Status record: If the user has registered the status record function, this function will be called to record the current status when the watchdog is not fed.
  3. Recovery and Reset Decision:
    1. When the number of consecutive failures reaches the maximum allowed number of consecutive watchdog non-feeding attempts max_failures, the recovery operation will be attempted first.
    2. If the recovery operation succeeds, the consecutive failure count is reset; if the recovery fails, whether to initiate a system reset is determined by triggering condition judgment (if a condition function is registered).
    3. System reset is implemented by creating a one-shot timer, which invokes reset_delay after a delay of milliseconds reset () to perform the reset.

The specific timing sequence is shown in the following figure:

15 WDT Watchdog Timer - Preliminary Documentation Tutorial

Users can implement custom callback function registration through the following three methods:

Next, we define several custom callback functions to test this class:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/8/16 AM 10:51
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : WDT watchdog timer class experiment, implemented with a Pico software timer

# ======================================== Import Modules ========================================

# Import hardware-related modules
from machine import Timer, reset, disable_irq, enable_irq
# Import time-related modules
import time
# Import the scheduler method
from micropython import schedule
# Import micropython-related modules
import micropython

# ======================================== Global Variables ============================================

# Set the threshold for the trigger condition
threshold = 10
# Assume the current value is 0
current_value = 12
# Declare the watchdog object
watchdog = None

# ======================================== Functions ============================================

# User-defined status recording function
def user_log_critical_time() -> None:
    """
    User-defined status recording function, used to write the current timestamp, current value, watchdog trigger count, and consecutive feed failure count to the log file.
    When the log file exceeds 50 lines, a new log file is created automatically.

    Args:
        None

    Returns:
        None

    Raises:
        Exception: If an error occurs while writing to the log file.
    """
    # Declare global variables
    global watchdog, current_value

    # Get the current timestamp
    timestamp = time.ticks_ms()

    # Base name of the log file
    log_base_name = "/log"
    log_extension = ".txt"
    log_index = 0
    log_file = f"{log_base_name}{log_index}{log_extension}"

    # Find the latest log file
    while True:
        try:
            # Try to open the file to check whether it exists
            with open(log_file, "r") as f:
                lines = f.readlines()
                # If the file has fewer than 10 lines, keep using the current file
                if len(lines) < 10:
                    break
        except OSError:
            # If the file does not exist, use the current file
            break
        # If the file has more than 10 lines, increment the index and try the next file
        log_index += 1
        log_file = f"{log_base_name}{log_index}{log_extension}"

    # Write the timestamp, current value, watchdog trigger count, and consecutive feed failure count to the log file
    try:
        with open(log_file, "a") as f:
            # Use % to format the string
            log_entry = "Timestamp: %d ms, Current Value: %d, Triggers: %d, Failures: %d\n" % (
                timestamp, current_value, watchdog.trigger_count, watchdog.failure_count
            )
            f.write(log_entry)
            # Ensure the data is written to the storage device
            f.flush()
    except Exception as e:
        print("[Error] Failed to write log:", str(e))

# User-defined trigger condition function
@micropython.native
def user_check_threshold() -> bool:
    """
    User-defined trigger condition function, used to determine whether the threshold has been reached.

    Args:
        None

    Returns:
        bool: True means the threshold has been reached, False means it has not been reached

    Raises:
        None
    """
    # Declare global variables
    global current_value, threshold

    # Check whether the threshold has been reached
    if current_value >= threshold:
        # Trigger threshold reached, return True and print information
        print("[Trigger] Threshold reached, triggering watchdog...")
        return True

    # Threshold not reached, return False and print information
    print("[Info] Current value is below threshold, no need to trigger watchdog...")
    return False

# Custom recovery action function
@micropython.native
def user_recovery_handler() -> bool:
    """
    User-defined recovery action function, used to perform the recovery action.

    Args:
        None

    Returns:
        bool: True means the recovery action succeeded, False means the recovery action failed

    Raises:
        Exception: If an error occurs while performing the recovery action.
    """
    # Declare global variables
    global watchdog

    # Print the recovery action information
    print("[Recovery] Attempting to recover system...")

    # Simulate the recovery action
    try:
        # The user can perform the recovery action here, for example restarting the system or reconnecting to the network.
        pass
    except Exception as e:
        print("[Error] Failed to recover system:", str(e))
        # Return False to indicate the recovery action failed
        return False

    # Print the recovery action success message
    print("[Recovery] Recovery operation completed successfully.")

    # Return True to indicate the recovery action succeeded
    return True

Next, we will explain its function:

Here, in the trigger condition judgment user_check_threshold () function and the recovery operation user_recovery_handler () function, we use the function decorator @micropython.native to enable the native code emitter; the generated native code runs faster with a significant performance improvement (approximately twice that of bytecode), at the cost of a larger native code size that occupies more storage space.

Meanwhile, import a timing decorator additionally, which is used to calculate and print the running time of the function/method:

# Timing decorator, used to measure function run time
@micropython.native
def timed_function(f: callable, *args: tuple, **kwargs: dict) -> callable:
    """
    Timing decorator, used to measure and print function/method run time.

    Args:
        f (callable): The function/method to be passed in
        args (tuple): Any number of positional arguments passed to function/method f
        kwargs (dict): Any number of keyword arguments passed to function/method f

    Returns:
        callable: Returns the timed function
    """
    myname = str(f).split(' ')[1]

    def new_func(*args: tuple, **kwargs: dict) -> any:
        t: int = time.ticks_us()
        result = f(*args, **kwargs)
        delta: int = time.ticks_diff(time.ticks_us(), t)
        print('Function {} Time = {:6.3f}ms'.format(myname, delta / 1000))
        return result

    return new_func

After initializing the software watchdog instance, you can use the register_state_recorder () method, the set_trigger_condition () method, and the register_recovery_handler () method to register relevant functions. Its implementation principle is realized by passing in and storing function references. Take the following register_recovery_handler () method as an example:

def register_state_recorder(self, recorder: callable[[], None]) -> None:
    """
    Register the status recording callback function.

    Args:
        recorder (callable): Callback function with no parameters and no return value, used to record status

    Returns:
        None

    Raises:
        TypeError: If the parameter recorder is not of callable type.
    """
    # Check whether recorder is a callable object
    if not callable(recorder):
        raise TypeError("State recorder must be callable")

    # Set the status recording callback function
    self._state_recorder = recorder

Here, recorder is just a function reference that points to the function passed in by the user; afterwards, when self._state_recorder () is invoked, it will execute the code of the original function.

We can register the relevant function with the following statement:

# Initialize the software watchdog, set the timeout to 4 seconds, the maximum consecutive failures to 3, and the reset delay to 1 second
watchdog = SoftwareWatchdog(timeout=4000, debug=True, max_failures=3, reset_delay=1000)
# Register the status recording callback function
watchdog.register_state_recorder(user_log_critical_time)
# Set the trigger condition callback function
watchdog.set_trigger_condition(user_check_threshold)
# Register the recovery action callback function
watchdog.register_recovery_handler(user_recovery_handler)

The following code can be found in the material package we provide elegance-devkit v1\Demo\53 WDG_Timer folder.

In the following example, we will use the SoftwareWatchdog software timer class implemented above to monitor the running status of the system, and perform a recovery operation when an exception occurs in the system. The complete code is shown below:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/8/16 AM 10:51
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : WDT watchdog timer class experiment, implemented with a Pico software timer

# ======================================== Import Modules ========================================

# Import hardware-related modules
from machine import Timer, reset, disable_irq, enable_irq
# Import time-related modules
import time
# Import the scheduler method
from micropython import schedule
# Import micropython-related modules
import micropython

# ======================================== Global Variables ============================================

# Set the threshold for the trigger condition
threshold = 10
# Assume the current value is 0
current_value = 12
# Declare the watchdog object
watchdog = None

# ======================================== Functions ============================================

# User-defined status recording function
def user_log_critical_time() -> None:
    """
    User-defined status recording function, used to write the current timestamp, current value, watchdog trigger count, and consecutive feed failure count to the log file.
    When the log file exceeds 50 lines, a new log file is created automatically.

    Args:
        None

    Returns:
        None

    Raises:
        Exception: If an error occurs while writing to the log file.
    """
    # Declare global variables
    global watchdog, current_value

    # Get the current timestamp
    timestamp = time.ticks_ms()

    # Base name of the log file
    log_base_name = "/log"
    log_extension = ".txt"
    log_index = 0
    log_file = f"{log_base_name}{log_index}{log_extension}"

    # Find the latest log file
    while True:
        try:
            # Try to open the file to check whether it exists
            with open(log_file, "r") as f:
                lines = f.readlines()
                # If the file has fewer than 10 lines, keep using the current file
                if len(lines) < 10:
                    break
        except OSError:
            # If the file does not exist, use the current file
            break
        # If the file has more than 10 lines, increment the index and try the next file
        log_index += 1
        log_file = f"{log_base_name}{log_index}{log_extension}"

    # Write the timestamp, current value, watchdog trigger count, and consecutive feed failure count to the log file
    try:
        with open(log_file, "a") as f:
            # Use % to format the string
            log_entry = "Timestamp: %d ms, Current Value: %d, Triggers: %d, Failures: %d\n" % (
                timestamp, current_value, watchdog.trigger_count, watchdog.failure_count
            )
            f.write(log_entry)
            # Ensure the data is written to the storage device
            f.flush()
    except Exception as e:
        print("[Error] Failed to write log:", str(e))

# User-defined trigger condition function
@micropython.native
def user_check_threshold() -> bool:
    """
    User-defined trigger condition function, used to determine whether the threshold has been reached.

    Args:
        None

    Returns:
        bool: True means the threshold has been reached, False means it has not been reached

    Raises:
        None
    """
    # Declare global variables
    global current_value, threshold

    # Check whether the threshold has been reached
    if current_value >= threshold:
        # Trigger threshold reached, return True and print information
        print("[Trigger] Threshold reached, triggering watchdog...")
        return True

    # Threshold not reached, return False and print information
    print("[Info] Current value is below threshold, no need to trigger watchdog...")
    return False

# Custom recovery action function
@micropython.native
def user_recovery_handler() -> bool:
    """
    User-defined recovery action function, used to perform the recovery action.

    Args:
        None

    Returns:
        bool: True means the recovery action succeeded, False means the recovery action failed

    Raises:
        Exception: If an error occurs while performing the recovery action.
    """
    # Declare global variables
    global watchdog

    # Print the recovery action information
    print("[Recovery] Attempting to recover system...")

    # Simulate the recovery action
    try:
        # The user can perform the recovery action here, for example restarting the system or reconnecting to the network.
        pass
    except Exception as e:
        print("[Error] Failed to recover system:", str(e))
        # Return False to indicate the recovery action failed
        return False

    # Print the recovery action success message
    print("[Recovery] Recovery operation completed successfully.")

    # Return True to indicate the recovery action succeeded
    return True

# Timing decorator, used to measure function run time
@micropython.native
def timed_function(f: callable, *args: tuple, **kwargs: dict) -> callable:
    """
    Timing decorator, used to measure and print function/method run time.

    Args:
        f (callable): The function/method to be passed in
        args (tuple): Any number of positional arguments passed to function/method f
        kwargs (dict): Any number of keyword arguments passed to function/method f

    Returns:
        callable: Returns the timed function
    """
    myname = str(f).split(' ')[1]

    def new_func(*args: tuple, **kwargs: dict) -> any:
        t: int = time.ticks_us()
        result = f(*args, **kwargs)
        delta: int = time.ticks_diff(time.ticks_us(), t)
        print('Function {} Time = {:6.3f}ms'.format(myname, delta / 1000))
        return result

    return new_func

# ======================================== Custom Classes ============================================

# Allocate the emergency exception buffer (must be placed before all interrupt code)
micropython.alloc_emergency_exception_buf(100)

# Software watchdog class
class SoftwareWatchdog:
    """
    Software watchdog class, implementing watchdog functionality using MicroPython's Timer.
    This class encapsulates timer-based watchdog logic, supporting timeout detection, feeding operations, state recording, trigger condition checking and recovery operations.
    By registering callback functions, users can customize the state recording, trigger condition and recovery operation logic.

    Attributes:
        timeout (int): Watchdog timeout, in milliseconds (default 4000 ms).
        debug (bool): Whether to enable debug mode (enabled by default).
        max_failures (int): Maximum number of consecutive feeding failures (default 1).
        reset_delay (int): Delay before triggering a reset, in milliseconds (default 3000 ms).
        feed_successful (bool): Feed flag, indicating whether the watchdog was fed successfully.
        timer (Timer): Software timer instance, used to periodically check the feeding status.
        feed_count (int): Counter of the number of feedings.
        trigger_count (int): Counter of the number of watchdog triggers.
        failure_count (int): Counter of consecutive feeding failures.
        _state_recorder (callable): User-defined state recording callback function.
        _trigger_condition (callable): User-defined trigger condition callback function.
        _recovery_handler (callable): User-defined recovery action callback function.

    Methods:
        __init__(self, timeout: int = 4000, debug: bool = True, max_failures: int = 1, reset_delay: int = 3000) -> None:
            Initialize the software watchdog instance.

        _initialize_timer(self) -> None:
            Initialize the timer and set the callback function.

        register_state_recorder(self, recorder: callable[[], None]) -> None:
            Register the status recording callback function.

        set_trigger_condition(self, condition: callable[[], bool]) -> None:
            Set the trigger condition callback function.

        register_recovery_handler(self, handler: callable[[], bool]) -> None:
            Register the recovery action callback function.

        _watchdog_callback(self, t: Timer) -> None:
            Timer callback function. Checks whether the watchdog was fed in time, and also records status and checks the condition to decide whether to trigger a reset.

        feed(self) -> None:
            Feed the watchdog and reset the feed flag.

        stop(self) -> None:
            Stop the watchdog timer.

        __del__(self) -> None:
            Destructor, ensures the timer resources are released.
    """
    def __init__(self, timeout: int = 4000, debug: bool = True, max_failures: int = 1, reset_delay: int = 3000) -> None:
        """
        Initialize the software watchdog.

        Args:
            timeout (int): Watchdog timeout, in milliseconds (default 4000 ms).
            debug (bool): Whether to enable debug mode (enabled by default).
            max_failures (int): Maximum number of consecutive feeding failures (default 1).
            reset_delay (int): Delay before triggering a reset, in milliseconds (default 3000 ms).

        Returns:
            None

        Raises:
            ValueError: If the parameters timeout, max_failures, or reset_delay are not positive integers, or debug is not a boolean.
        """
        # Check the entry parameters
        if not isinstance(reset_delay, int) or reset_delay <= 0:
            raise ValueError("reset_delay must be a positive integer")

        if not isinstance(timeout, int) or timeout <= 0:
            raise ValueError("timeout must be a positive integer")

        if not isinstance(max_failures, int) or max_failures <= 0:
            raise ValueError("max_failures must be a positive integer")

        if not isinstance(debug, bool):
            raise TypeError("debug must be a boolean value")

        # Set the timeout
        self.timeout = timeout
        # Set the debug mode
        self.debug = debug
        # Set the maximum number of failures
        self.max_failures = max_failures
        # Set the reset delay time
        self.reset_delay = reset_delay

        # Initialize the feed flag to False
        self.feed_successful = False
        # Initialize the software timer
        self.timer = Timer(-1)

        # Initialize the feed count
        self.feed_count = 0
        # Initialize the watchdog trigger count
        self.trigger_count = 0
        # Initialize the consecutive feed failure count
        self.failure_count = 0

        # Initialize the user-defined status recording function to None
        self._state_recorder = None
        # Initialize the user-defined trigger condition function to None
        self._trigger_condition = None
        # Initialize the recovery action callback function to None
        self._recovery_handler = None

        # Initialize the timer
        self._initialize_timer()

    def _initialize_timer(self) -> None:
        """
        Initialize the timer and set the callback function.

        Args:
            None

        Returns:
            None
        """
        # Initialize the timer, set the period and callback function
        self.timer.init(period=self.timeout, mode=Timer.PERIODIC, callback=lambda t: schedule(self._watchdog_callback, t))

    def register_state_recorder(self, recorder: callable[[], None]) -> None:
        """
        Register the status recording callback function.

        Args:
            recorder (callable): Callback function with no parameters and no return value, used to record status

        Returns:
            None

        Raises:
            TypeError: If the parameter recorder is not of callable type.
        """
        # Check whether recorder is a callable object
        if not callable(recorder):
            raise TypeError("State recorder must be callable")

        # Set the status recording callback function
        self._state_recorder = recorder

    def set_trigger_condition(self, condition: callable[[], bool]) -> None:
        """
        Set the trigger condition callback function.

        Args:
            condition (callable): Callback function with no parameters that returns bool; returning True means a restart is allowed to trigger.

        Returns:
            None

        Raises:
            TypeError: If the parameter condition is not of callable type.
        """
        # Check whether condition is a callable object
        if not callable(condition):
            raise TypeError("Trigger condition must be callable")

        # Set the trigger condition callback function
        self._trigger_condition = condition

    def register_recovery_handler(self, handler: callable[[], bool]) -> None:
        """
        Register the recovery action callback function.

        Args:
            handler (callable): Callback function with no parameters that returns a value, used to perform the recovery action; a return value of True means the recovery action succeeded, False means it failed.

        Returns:
            None

        Raises:
            TypeError: If the parameter handler is not of callable type.
        """
        # Check whether handler is a callable object
        if not callable(handler):
            raise TypeError("Recovery handler must be callable")

        # Set the recovery action callback function
        self._recovery_handler = handler

    # Use the @timed_function decorator to measure the run time of the SoftwareWatchdog._watchdog_callback method
    @timed_function
    def _watchdog_callback(self, t: Timer) -> None:
        """
        Timer callback function. Checks whether the watchdog was fed in time, and also records status and checks the condition to decide whether to trigger a reset.

        Args:
            t (Timer): Timer object (passed in automatically by Timer).

        Returns:
            None

        Raises:
            Exception: If an error occurs while executing the status recording callback function.
            Exception: If an error occurs while executing the recovery action callback function.
            TypeError: If the return value of the recovery action callback function is not of boolean type.
            Exception: If an error occurs while executing the trigger condition callback function.
        """

        # Read the feed flag atomically
        irq_state = disable_irq()
        feed_flag = self.feed_successful
        enable_irq(irq_state)

        # Check whether the watchdog was fed in time
        if not feed_flag:
            # Increase the consecutive failure count
            self.failure_count += 1
            # Increase the trigger count
            self.trigger_count += 1

            # If debug mode is on, print the trigger information
            if self.debug:
                print("[Watchdog] Triggered ({} failures, {} total triggers)".format(
                    self.failure_count, self.trigger_count))

            # Execute status recording (if registered)
            if self._state_recorder:
                try:
                    self._state_recorder()
                except Exception as e:
                    if self.debug:
                        print("[Error] Failed to record state:", str(e))

            # Check whether the consecutive failure count has reached the maximum
            if self.failure_count >= self.max_failures:

                # Flag indicating whether the recovery action succeeded
                recovery_successful = False

                # Try the recovery action
                if self._recovery_handler:
                    try:
                        if self.debug:
                            print("[Watchdog] Attempting recovery...")
                        # Try the recovery action
                        recovery_successful = self._recovery_handler()
                        # Check whether recovery_successful is a bool variable
                        if not isinstance(recovery_successful, bool):
                            raise TypeError("Recovery handler must return a boolean value")
                    except Exception as e:
                        if self.debug:
                            print("[Error] Recovery handler failed:", str(e))

                # Check whether the recovery action succeeded
                if recovery_successful:
                    # Reset the consecutive failure count
                    self.failure_count = 0
                    # Reset the should-trigger flag
                    self.should_trigger = False
                    if self.debug:
                        print("[Watchdog] Recovery successful, resetting failure count...")
                else:
                    # If recovery failed, check the trigger condition

                    # Trigger by default
                    should_trigger = True
                    # Check whether the trigger condition is registered
                    if self._trigger_condition:
                        try:
                            # Execute the trigger condition check
                            should_trigger = self._trigger_condition()
                        except Exception as e:
                            if self.debug:
                                print("[Error] Trigger condition check failed:", str(e))
                            # Trigger by default
                            should_trigger = True

                    # If the trigger condition is met, trigger a reset
                    if should_trigger:
                        if self.debug:
                            print("[Watchdog] Max failures reached, resetting system after %d ms..." %(self.reset_delay))
                        # Create a one-shot timer that performs the reset after the specified delay
                        self.reset_timer = Timer(-1)
                        self.reset_timer.init(period=self.reset_delay, mode=Timer.ONE_SHOT, callback=lambda t: reset())
        else:
            # Reset the consecutive failure count
            self.failure_count = 0

            # Atomic reset
            irq_state = disable_irq()
            # Reset the feed flag
            self.feed_successful = False
            enable_irq(irq_state)

    def feed(self) -> None:
        """
        Feed the watchdog and reset the feed flag.

        Args:
            None

        Returns:
            None
        """
        irq_state = disable_irq()
        self.feed_successful = True
        # Increase the feed count
        self.feed_count += 1
        enable_irq(irq_state)

        # If debug mode is on, print the feed time
        if self.debug:
            print("Watchdog fed at:", time.ticks_ms())

    def stop(self) -> None:
        """
        Stop the watchdog timer.

        Args:
            None

        Returns:
            None
        """
        # Stop the timer
        self.timer.deinit()
        if self.debug:
            print("Watchdog stopped.")

    def __del__(self):
        """
        Destructor: ensures the timer resources are released.

        Args:
            None

        Returns:
            None
        """
        self.timer.deinit()
        if self.debug:
            print("Watchdog resources released.")

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information
print("FreakStudio : Implement Watchdog Timer using a software timer Test")

# Initialize the software watchdog, set the timeout to 4 seconds, the maximum consecutive failures to 3, and the reset delay to 1 second
watchdog = SoftwareWatchdog(timeout=4000, debug=True, max_failures=3, reset_delay=1000)
# Register the status recording callback function
watchdog.register_state_recorder(user_log_critical_time)
# Set the trigger condition callback function
watchdog.set_trigger_condition(user_check_threshold)
# Register the recovery action callback function
watchdog.register_recovery_handler(user_recovery_handler)

# ========================================  Main Program  ===========================================

# Feed the watchdog ten times within the timeout, so the watchdog timer does not trigger a reset
for i in range(2):
    # Feed the watchdog
    watchdog.feed()
    # Delay 2 seconds
    time.sleep(2)

Burn the program, connect the Raspberry Pi Pico, and the terminal output is as follows:

15 WDT Watchdog Timer - Preliminary Documentation Tutorial

3.2.1 Application Experiment.mp4 6.2 MB

It can be seen that the basic flow of the program operation is as follows:

  1. Program Startup and Initial Watchdog Feeding: First, the program starts up, and the terminal first displays "FreakStudio : Implement Watchdog Timer using a software timer Test", then prints the "Watchdog fed at: …" message twice, indicating that watchdog.feed () has been called twice in the main program; these two calls successfully set the watchdog feeding flag to True and recorded the feeding time at the same time;Meanwhile, when the watchdog callback function is called for the first time (outputting "Function _watchdog_callback Time = … ms"), it indicates that the timer has been started and entered the periodic detection phase.
4000 3 2
  1. Periodic detection and consecutive watchdog feeding failures: As the main program loop terminates (and no further calls to feed () are made), the watchdog callback function detects that feed_successful is False in each subsequent cycle, thus entering the "watchdog not fed in time" state. During each cycle where the watchdog is not fed, the program operates according to the following steps:
    1. Increment the consecutive failure count (failure_count) and the total trigger count (trigger_count);
    2. When the dog is not fed for the first time, the output "[Watchdog] Triggered (1 failures, 1 total triggers)";
    3. During the second test, "[Watchdog] Triggered (2 failures, 2 total triggers)";
    4. When consecutive failures reach 3 times (for example, the first time it reaches "(3 failures, 3 total triggers)"), the system enters the recovery phase.
  2. Trigger of recovery operation: When the number of consecutive watchdog feeding failures reaches the preset maximum value (3 times in this example), output "[Watchdog] Attempting recovery. .." to start the recovery operation:
    15 WDT Watchdog Timer - Preliminary Documentation Tutorial
    1. Call the user-defined recovery operation function user_recovery_handler, and output in sequence:
      1. “[Recovery] Attempting to recover system...”;
      2. “[Recovery] Recovery operation completed successfully.”;
      3. “[Watchdog] Recovery successful, resetting failure count...”.

      Indicates that the recovery operation succeeded and the consecutive failure count has been reset to 0.

    2. After recovery succeeds, the watchdog resumes operation. Although the consecutive failure count is reset to zero at this point, the total trigger count continues to accumulate (for example, if the total number of triggers after the first cycle is 3, the first trigger of the next cycle will display "(1 failures, 4 total triggers)"; this pattern repeats continuously in subsequent cycles, and a recovery operation is performed once every 3 consecutive times that the watchdog is not fed.

We can use the mpremote tool to view the log file with the following command:

mpremote cat log0.txt

It can be seen that the log file records in detail the current timestamp, the current system status value, the number of watchdog triggers, and the number of consecutive watchdog feeding failures:

log0.txt 50493ms 86493ms 12 1 10 3

We can also use the mpremote cp : log0.txt./log0.txt command to copy this log file to the specified path:

log0.txt 50493 54493 12 1 10 2

3.2.2 Application Experiment.mp4 4.6 MB

Next, we try to skip the recovery operation by commenting out the statement that registers the recovery operation callback function, and run it again:

# Register the recovery action callback function
# watchdog.register_recovery_handler(user_recovery_handler)

It can be seen that the device resets after 3 consecutive watchdog feeding failures.

3

3.2.3 Application Experiment.mp4 2.6 MB

In practice, software watchdogs also have certain limitations. Since their operation relies on the system's own hardware and software resources, software watchdogs may fail when a serious system error occurs. For example, if there is a problem with the interrupt service routine (ISR) in the system, causing the entire system to become paralyzed, the software watchdog may fail to perform the reset operation in a timely manner, as it itself runs on the system's resources. In such cases, the system may be unable to recover on its own, leading to more severe consequences.

3.3 Multi-threaded Implementation of Watchdog Experiment

Similarly, a software timer-like mechanism can also be applied here

The core idea of the multi-threaded software watchdog is to use an independent watchdog thread to monitor the status of other worker threads, and each worker thread periodically "feeds the dog" to indicate that it is still operating normally: the watchdog thread is responsible for monitoring the global count variable and increments the variable at fixed intervals; after completing a certain operation, the worker thread clears the global count variable, which is the "dog feeding" operation. If the watchdog thread finds that the global count variable exceeds a predefined upper limit (for example, 2), it determines that the main program thread has stalled and takes measures to restart the device.

Here, there are two points to note:

Common errors that occur when performing a reset operation in a non-main thread are as follows:

>>> FATAL: uncaught exception 20008830 
OSError

Or:

>>> [Watchdog] Main thread is unresponsive. System should restart! 
FATAL: uncaught exception 20008830 
OSError:

Or:

>>> Watchdog: Main thread is unresponsive. System should restart! 
FATAL: uncaught exception 20008870 
OSError: TinyUSB callback can't recurse 

In the following code, we implement a multi-threaded software watchdog timer to monitor the running status of the main thread and the dog-feeding thread. When the dog-feeding thread fails to "feed the watchdog" periodically (i. e., fails to reset the counter regularly), the watchdog will determine that a system fault has occurred and attempt to restart the device.

The following code can be found in the material package we provide, in the elegance-devkit v1\Demo\54 WDG_Thread folder.

The sample code is as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/8/16 AM 11:14
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : WDT watchdog timer class experiment, implemented with Pico software multithreading

# ======================================== Import Modules ========================================

# Import the multithreading module
import _thread
# Import time-related modules
import time
# Import the hardware module
import machine
# Import the const constant
from micropython import const
import micropython

# ======================================== Global Variables ============================================

# Global variable, used for watchdog thread monitoring
watchdog_counter = 0

# If the watchdog is not fed within this count, the system restarts
WATCHDOG_MAX_COUNTER = const(2)
# Watchdog check interval (unit: seconds)
WATCHDOG_CHECK_INTERVAL = const(4)
# Feed thread execution interval (seconds)
FEED_INTERVAL = const(1)
# Maximum feed count, feeding stops once reached
FEED_COUNT = const(10)

# ======================================== Functions ============================================

# Allocate the emergency exception buffer (must be placed before all interrupt code)
micropython.alloc_emergency_exception_buf(100)

# Feeding-the-dog (watchdog feeding) thread
def feed_thread() -> None:
    """
    Watchdog feeding thread, used to periodically feed the watchdog and clear the watchdog counter to prevent the main thread from triggering a reset.

    Args:
        None

    Returns:
        None

    Raises:
        Exception: If an exception occurs during feeding, print the error message; it does not affect the main thread.
    """
    # Declare global variables
    global watchdog_counter

    # Watchdog feed counter
    feed_times = 0

    while True:
        try:
            # Feed the watchdog once every FEED_INTERVAL seconds
            time.sleep(FEED_INTERVAL)

            # Acquire the mutex
            lock.acquire()

            # If the feed count has not reached FEED_COUNT, perform the feed operation
            if feed_times < FEED_COUNT:
                # Feed the watchdog: clear watchdog_counter
                watchdog_counter = 0
                feed_times += 1
                print(f"[Feed] Feed the dog! ({feed_times}/{FEED_COUNT})")
            else:
                # Feed count reached FEED_COUNT, stop feeding
                print("[Feed] Stop feeding the dog!")
                # Exit the loop
                break

        except Exception as e:
            # Catch and print the exception
            print(f"[Feed] Error in feed thread: {e}")
        finally:
            # Release the mutex
            if lock.locked():
                lock.release()

# ======================================== Custom Classes ============================================

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information
print("FreakStudio : Implement Watchdog Timer using a multi-threading Test")
# Create an LED object
led = machine.Pin(25, machine.Pin.OUT)

# ========================================  Main Program  ===========================================

# Acquire the mutex to protect shared resources when multiple threads access them
lock = _thread.allocate_lock()
# Start the watchdog feeding thread
_thread.start_new_thread(feed_thread, ())

# Main thread: monitor whether `watchdog_counter` has timed out
try:
    # Check whether watchdog_counter has timed out once every WATCHDOG_CHECK_INTERVAL seconds
    while True:
        try:
            # Acquire the mutex
            lock.acquire()

            # Toggle the LED to indicate the program is running
            led.toggle()
            # Simulate the main thread performing other tasks
            time.sleep(WATCHDOG_CHECK_INTERVAL-1)
            print("[Main] Main thread is running, checking watchdog...")

            # Check whether watchdog_counter is greater than WATCHDOG_MAX_COUNTER
            if watchdog_counter > WATCHDOG_MAX_COUNTER:
                # The feeding thread cannot perform the feed operation due to a fault
                print("[Watchdog] Feed thread is unresponsive. System should restart!")
                # Delay 1 second to ensure the debug information is output
                time.sleep(1)

                # Release the mutex
                if lock.locked():
                    lock.release()

                # Try to restart the system
                try:
                    # Soft reset the system: delete all Python objects and reset the Python heap
                    machine.soft_reset()
                except Exception as e:
                    # Catch and print the exception
                    print(f"[Error] Failed to restart system: {e}")

            # Increment the value of watchdog_counter
            watchdog_counter += 1

        except Exception as e:
            # Catch and print the exception
            print(f"[Main] Error in main thread: {e}")
        finally:
            # Release the mutex
            if lock.locked():
                lock.release()

except KeyboardInterrupt:
    # Catch user interrupt (such as Ctrl+C)
    print("[Main] Program interrupted by user.")
finally:
    # Make sure resources are released when the program ends
    print("[Main] Program ended.")

In the sample code above, we have completed the following tasks:

The program Sequence Diagram is shown below:

15 WDT Watchdog Timer - Preliminary Documentation Tutorial

Here, we use machine.soft_reset () to restart the system:

15 WDT Watchdog Timer - Preliminary Documentation Tutorial

Unlike machine.reset (), a hard reboot reinitializes the entire system;machine.soft_reset () only restarts the MicroPython interpreter without reinitializing the hardware. It clears the runtime state of MicroPython (such as variables, objects, stack, etc.), re-executes the startup scripts (such as boot.py and main.py), and does not disconnect the REPL connection in the meantime.

After flashing the code and connecting to the Raspberry Pi Pico remotely, the terminal output is as follows:

0 10

3.3 Application Experiment.mp4 1.8 MB

It can be seen that after stopping feeding the dog, the watchdog main thread restarts the device when the timeout period is reached. In a multi-tasking environment, we can use the watchdog multi-thread to quickly respond to problems occurring in the main thread.

3.4 External Watchdog Experiment

3.4.1 Design of DS1232 Chip Driver Code

DS1232 is an external watchdog chip used for hardware reset protection of the MCU. The driver objectives are as follows:

The driver code files are listed as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2025/8/25 6:46 PM
# @Author  : Li Qingshui
# @File    : ds1232.py       
# @Description : External DS1232 watchdog module driver

# ======================================== Import Modules =========================================

# Import hardware-related modules
from machine import Pin, Timer

# ======================================== Global Variables ============================================

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

class DS1232:
    """
    This class controls the external DS1232 watchdog module, feeding the watchdog by periodically toggling the WDI pin to prevent the MCU from being reset.

    Attributes:
        wdi (Pin): machine.Pin instance used to output the feed pulse.
        state (int): Current WDI pin output state, 0 or 1.
        timer (Timer): machine.Timer instance used for periodic feeding.

    Methods:
        __init__(wdi_pin: int, feed_interval: int = 1000) -> None: Initialize the watchdog and start timed feeding.
        stop() -> None: Stop automatic feeding and set the WDI pin low.
        kick() -> None: Feed manually, toggling the WDI pin once immediately.

    Notes:
        - A Timer object is created during initialization to toggle WDI periodically.
        - _feed is an internal callback method and should not be called directly.
        - Most methods of this class are not ISR-safe; the Timer callback _feed is ISR-safe.
        - After stop(), the WDI pin stays low, and the DS1232 will reset the MCU after the timeout.

    ==========================================

    DS1232_Watchdog driver for controlling an external DS1232 watchdog module.
    Periodically toggles WDI pin to prevent MCU reset.

    Attributes:
        wdi (Pin): machine.Pin instance for feeding pulses.
        state (int): Current WDI output state, 0 or 1.
        timer (Timer): machine.Timer instance for periodic feeding.

    Methods:
        __init__(wdi_pin: int, feed_interval: int = 1000) -> None: Initialize the watchdog and start automatic feeding.
        stop() -> None: Stop automatic feeding and set WDI low.
        kick() -> None: Manually feed the watchdog by toggling WDI once.

    Notes:
        - Initializes a Timer to periodically toggle WDI.
        - _feed is an internal callback method, not recommended for direct user call.
        - Most methods are not ISR-safe; _feed callback is ISR-safe.
        - After stop(), WDI remains low; DS1232 will reset MCU on timeout.
    """

    def __init__(self, wdi_pin: int, feed_interval: int = 1000) -> None:
        """
        Initialize the DS1232 watchdog.

        Args:
            wdi_pin (int): WDI pin number.
            feed_interval (int): Feed interval in ms. Default is 1000ms.

        Returns:
            None

        Raises:
            ValueError: When wdi_pin is not an integer or feed_interval > 1000.
            RuntimeError: When Timer initialization fails.

        Notes:
            Timed feeding starts immediately after the object is created.
            The call involves timer resources and is not ISR-safe.

        ==========================================

        Initialize DS1232 watchdog.

        Args:
            wdi_pin (int): WDI pin number.
            feed_interval (int): Feeding interval in ms. Default is 1000ms.

        Returns:
            None

        Raises:
            ValueError: If wdi_pin is not an integer or feed_interval > 1000 ms.
            RuntimeError: If Timer initialization fails.

        Notes:
            Feeding starts immediately after object creation.
            Uses Timer resource, not ISR-safe.
        """
        # Parameter check
        if not isinstance(wdi_pin, int):
            raise ValueError("wdi pin must be an integer")
        if feed_interval > 1000:
            raise ValueError("feed_interval must be less than 1000ms")

        self.wdi = Pin(wdi_pin, Pin.OUT)
        # Current output state
        self.state = 0
        self.timer = Timer(-1)

        # Start the timer to feed periodically
        self.timer.init(period=feed_interval, mode=Timer.PERIODIC, callback=self._feed)

    def _feed(self, t: Timer) -> None:
        """
        Timer callback function: periodically toggles the WDI pin.

        Args:
            t (Timer): The timer object that triggered this callback.

        Returns:
            None

        Raises:
            None

        Notes:
            Internal method; users should not call it directly.
            Runs in interrupt context; ISR-safe.

        ==========================================

        Timer callback: toggle WDI pin periodically.

        Args:
            t (Timer): Timer instance triggering this callback.

        Returns:
            None

        Raises:
            None

        Notes:
            Internal method, not recommended for direct user call.
            Runs in interrupt context, ISR-safe.
        """
        # Toggle 0/1
        self.state ^= 1
        self.wdi.value(self.state)

    def stop(self) -> None:
        """
        Stop automatic feeding.

        Args:
            None

        Returns:
            None

        Raises:
            RuntimeError: When releasing the timer fails.

        Notes:
            After stopping, the WDI pin stays low, and the DS1232 will reset the MCU after the timeout.

        ==========================================

        Stop automatic feeding.

        Args:
            None

        Returns:
            None

        Raises:
            RuntimeError: If timer deinitialization fails.

        Notes:
            WDI pin is held low after stopping, DS1232 will reset MCU on timeout.
        """
        self.timer.deinit()
        self.wdi.value(0)

    def kick(self) -> None:
        """
        Manual feed: toggle the WDI pin once immediately.

        Args:
            None

        Returns:
            None

        Raises:
            RuntimeError: When the pin write fails.

        Notes:
            Usually used for a temporary feed, or to maintain feeding manually after automatic feeding is stopped.

        ==========================================

        Manually feed watchdog by toggling WDI once.

        Args:
            None

        Returns:
            None

        Raises:
            RuntimeError: If pin write fails.

        Notes:
            Useful for temporary feeding or manual feeding after stopping auto mode.
        """
        self.state ^= 1
        self.wdi.value(self.state)

# ======================================== Initialization ==========================================

# ========================================  Main Program  ===========================================

In terms of initialization, we pass the WDI pin number and the watchdog feeding interval, and the DS1232 class will automatically create a GPIO pin object and start a timer to implement periodic watchdog feeding, ensuring that the MCU will not be reset during normal operation.

The DS1232 class has the following methods:_feed is an internal Timer callback used to automatically toggle WDI, kick can be used to manually feed the watchdog, stop can stop automatic watchdog feeding and make the DS1232 reset the MCU after timeout.

When in use, we only need to create a DS1232 object, and then:

  1. Timer starts, and feed_interval ms after each interval, _feed is called.
  2. _feed Toggle WDI → The DS1232 watchdog timer is reset.
  3. Normal operation of the MCU → Manual watchdog feeding can be performed via kick.
  4. Test or reset required → Call stop ()→ WDI pulled low → DS1232 timeout → MCU reset.

3.4.2 Application Experiment

In the code below, we initialize the DS1232 watchdog timer, perform periodic watchdog feeding, detect reset signals, and observe the process of the MCU being reset when a simulated timeout occurs or watchdog feeding is manually stopped.

Here, we first insert the Fengya No.1 board-Grove interface expansion board into the Fengya No.1 board-universal compatible expansion board , and then use the HY2.0-4P cable to connect the GraftSense-DS1232 watchdog module to the Fengya No.1 board-Grove interface expansion board 's UART1 interface, as shown in the figure below:

LED1 GraftSense-DS1232 HY2.0-4P

The wiring conditions are shown in the following table:

DS1232 module pinMCU GPIO / PowerFunction description
VCC5VModule power positive, a stable 5V supply is recommended
GNDGNDModule power negative, common ground with the MCU
WDIGPIO4Watchdog Input; the MCU toggles this pin periodically to feed the watchdog
RSTGPIO5Watchdog Reset Output; the MCU can detect the reset signal through an interrupt

Here, the GraftSense-DS1232 watchdog module has the short-circuit points on its back side for TD and TOL both soldered to VCC.

GraftSense-DS1232 DS1232 v1.0

The following code can be found in the material package we provide elegance-devkit v1\Demo\75 WDG_EXT folder.

Examples are shown as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2025/8/25 6:46 PM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : External DS1232 watchdog module test program

# ======================================== Import Modules =========================================

# Import hardware-related modules
from machine import Pin, Timer
# Import time-related modules
import time

# Import the DS1232 watchdog module
from ds1232 import DS1232

# ======================================== Global Variables ============================================

# GPIO connected to the DS1232 WDI pin
WDI_PIN = 4
# GPIO connected to the DS1232 RST pin
RST_PIN = 5
# Feed interval, in ms
FEED_INTERVAL = 300
# Delay before stopping feeding, in ms
STOP_FEED_DELAY = 10000

# Define global variables
wdg = None
stop_feed_timer = None
# Global flag: detects whether RST was triggered
system_reset_flag = False

# ======================================== Functions ============================================

def rst_callback(pin: Pin) -> None:
    """
    DS1232 RST pin trigger callback function.

    Args:
        pin (Pin): The GPIO pin that triggered this callback.

    Returns:
        None
    """
    # Declare global variables
    global system_reset_flag

    # Set the flag; the main loop breaks out after detecting it
    system_reset_flag = True
    print("DS1232 RST pin triggered.")

def stop_feed_callback(t: Timer) -> None:
    """
    Timer callback: stop automatic feeding, simulating a feed failure to trigger a reset.

    Args:
        t (Timer): Timer object

    Returns:
        None
    """
    # Declare global variables
    global wdg, stop_feed_timer

    print("Stop feeding watchdog.")
    # Stop feeding
    wdg.stop()
    # Stop this timer so it runs only once
    stop_feed_timer.deinit()

# ======================================== Custom Classes ============================================

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information
print("FreakStudio:: DS1232 Watchdog Test Program.")

# Initialize the DS1232 watchdog
wdg = DS1232(wdi_pin=WDI_PIN, feed_interval=FEED_INTERVAL)
# Feed manually immediately
wdg.kick()

# Configure the RST pin as input with pull-up, triggering the callback
rst_pin = Pin(RST_PIN, Pin.IN, Pin.PULL_UP)
rst_pin.irq(trigger=Pin.IRQ_FALLING, handler=rst_callback)

# Define a timer to delay stopping feeding
stop_feed_timer = Timer()
stop_feed_timer.init(period=STOP_FEED_DELAY, mode=Timer.ONE_SHOT, callback=stop_feed_callback)

# ========================================  Main Program  ===========================================

# Start feeding
print("Start feeding watchdog.")

try:
    # Infinite loop
    while True:
        # Print a log with timestamp
        current_time = time.ticks_ms()
        print(f"System running... Time: {current_time} ms")

        # Check the RST trigger flag
        if system_reset_flag:
            print("System starting reset...")
            # Break out of the while loop
            break

        time.sleep(1)
except KeyboardInterrupt:
    print("Program interrupted.")
finally:
    # Stop feeding
    wdg.stop()
    # Stop the timer
    stop_feed_timer.deinit()

Here, first of all, after the MCU is powered on, we delay for 3 seconds to complete stable startup, then print debug information, and create a DS1232 object to initialize the WDI pin and Timer, so as to implement automatic periodic dog feeding; meanwhile, we immediately call kick () to manually toggle the WDI once to ensure that the watchdog starts counting; next, configure the RST pin as input pull-up and bind an interrupt callback to detect the DS1232 timeout reset signal; then start a one-shot timer to delay stopping the automatic dog feeding, so as to simulate a reset triggered by failed dog feeding. The program then enters the main loop:

  1. Print the system running time (in milliseconds) every second.
  2. Check the system_reset_flag flag; if the RST pin is triggered, print the reset information and exit the loop.
  3. Catch KeyboardInterrupt to allow users to manually interrupt the program.

After the loop ends, stop the automatic watchdog feeding of DS1232 in the finally block and release the timer resources to ensure the status safety of the MCU and Timer, thus completing the entire watchdog test process.

Burn the code, open the terminal, and the running result is shown as follows:

DS1232

3.4.2 Application Experiment (1).mp4 1.4 MB

It can be seen that the program runs normally, and the overall process is as follows:

DS1232 1

After a reboot, before we stop watchdog feeding, while the MCU is normally sending pulses to the watchdog, press the RST button on the watchdog module, and you will find that a normal reset can still be triggered. This design is intended to provide a reliable external hard reset mechanism: when the software runs away, or you need to manually restart the entire board, manual reset should have the highest priority.

COM50 DS1232

References

https://www.cnblogs.com/Alfred-HOO/articles/15957581.html

https://blog.csdn.net/weixin_40407893/article/details/117956750

https://blog.csdn.net/fg247778718/article/details/138580080

https://blog.csdn.net/weixin_44216065/article/details/90646531

https://www.embedded.com/introduction-to-watchdog-timers/

https://www.ti.com/document-viewer/ja-jp/lit/html/SSZTAH7

https://www.ablic.com/en/semicon/products/automotive/automotive-watchdog-timer/intro/

https://www.ebyte.com/new-view-info.aspx?id=2551

https://www.cnblogs.com/rayoli/p/14825231.html

https://www.taterli.com/7559

https://vanhunteradams.com/Pico/Bootloader/Boot_sequence.html

https://mc.dfrobot.com.cn/thread-313092-1-1.html

https://forums.raspberrypi.com/viewtopic.php?f=146&t=305432

https://forums.raspberrypi.com/viewtopic.php?t=365927

https://www.xpstem.com/article/10586#

https://blog.csdn.net/weixin_40407893/article/details/117956750

Appendix

What should I do if the main.py file in MicroPython keeps running and restarting repeatedly?

When the main.py file on the Raspberry Pi Pico causes abnormal or "out-of-control" device behavior, making the device fail to boot properly or enter REPL mode — for example, when the watchdog timer is set too short and a timely watchdog feed operation cannot be performed — we will be unable to connect via the mpremote tool or remove all user files (i. e., files with the. py suffix) via PyCharm. In this case, there are two solutions available.

The solution is shown in the following link: https://forums.raspberrypi.com/viewtopic.php? t= 365927

uf2 2024 2 18 5 17 33 flash_nuke.uf2 UF2

This firmware is also available in the given reference folder: elegance-devkit v1\Reference Materials\Official Materials\Official Firmware

v1 UF2 flash_nuke.uf2 2024 8 15 23 49 47

The solution is shown in the following link: https://forums.raspberrypi.com/viewtopic.php? f= 146&t= 305432

2021 2 26 14 05 MicroPython_RenameMainDotPy.uf2 main-1.py

This firmware can also be found in the reference folder we provided: elegance-devkit v1\Reference Materials\Official Materials\Official Firmware

v1 RenameMainDotPy.uf2 2021/2/26 15 49 UF2 488 MicroPython_RenameMainDotPy.uf2

It should be noted that neither of the two firmware versions can clear the boot.py file.

Version Record

Version Number

Modifier

Time

Content

v1.0.0

Li Zisheng

2025/09/18

Initialize the document, based on MicroPython version v1.23.0.

v1.1.0

Li Zisheng

2026/01/24

Modified the wiring description table of the watchdog module.