[Diao Ye Learns Programming] MicroPython Manual WiPy Watchdog Timer (WDT)

Insert image description here
MicroPython is a lightweight version of the interpreter designed for running the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most of Python's core syntax.
2. Directly access and control hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. Powerful module system, providing file system, network, graphical interface and other functions.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small and the memory usage is small. It is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

MicroPython application scenarios include:
1. Rapidly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Things to note when using MicroPython:
1. Memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.
Insert image description here
WiPy is a MicroPython-based wireless microcontroller module that provides a complete hardware and software solution designed to simplify the development and deployment of Internet of Things (IoT) devices.

1. Microcontroller module: WiPy is a microcomputer module that integrates a processor, memory, wireless communication module and other necessary components. It is designed to provide a compact, low-power hardware platform capable of running high-level programming languages ​​​​such as MicroPython and having the ability to connect to the Internet and other devices.
2. MicroPython: MicroPython is a streamlined version of the Python programming language, specially developed for embedded systems and microcontroller design. It provides the core functions and syntax of the Python language, allowing developers to use familiar Python syntax for hardware control and IoT application development. As the operating environment of MicroPython, WiPy can directly interpret and execute MicroPython code.
3. Internet of Things (IoT): The Internet of Things refers to a network that connects various physical devices (such as sensors, actuators, embedded systems, etc.) through the Internet to achieve intelligence and interconnection. As a wireless microcontroller module, WiPy has wireless communication capabilities and can be connected to other devices and cloud platforms in the Internet of Things to achieve remote control and data exchange.
4. Wireless communication module: WiPy has one or more built-in wireless communication modules, common ones including Wi-Fi, Bluetooth, LoRa, etc. These wireless communication modules enable WiPy to communicate with other devices through wireless networks to achieve data transmission, remote control, cloud connection and other functions. Developers can choose appropriate wireless communication modules based on specific needs.
5. Development and deployment: WiPy provides a set of convenient development tools and development environment, allowing developers to quickly develop, debug and test applications. Once developed, WiPy can be deployed directly into actual IoT devices to communicate and interact with other devices. WiPy's compact design and low power consumption make it ideal for deployment in embedded systems and IoT devices.

Insert image description here
MicroPython's WiPy Watchdog Timer (WDT) is a timer used to monitor the operating status of the system and trigger a system restart in the event of a failure.

main feature:

System monitoring: WiPy WDT is used to monitor the running status of the system. It will count periodically. If the system does not reset the WDT counter within the specified time, that is, it does not kick the dog (kick the dog), it will be triggered by WDT and the system will be restarted.
Fault detection and recovery: WiPy WDT can detect system faults, such as deadlocks, infinite loops, or other abnormal states. Once a fault is detected, WDT will trigger a system restart to restore the system to normal working conditions.
Hardware implementation: WiPy WDT is a hardware-based timer, and its work is not affected by software. Even if the system crashes or stops working, WDT can still operate normally, ensuring system reliability and stability.

Application scenarios:

Embedded systems: WiPy WDT is suitable for various embedded systems, such as IoT devices, embedded controllers, etc. It can monitor the operating status of the system and automatically restart when the system fails, improving the reliability and stability of the system.
Mission-critical applications: For applications that perform mission-critical tasks, such as industrial automation, medical equipment, etc., WiPy WDT can be used as a security mechanism to monitor system operating conditions to ensure timely completion of tasks and integrity of data.
Long-running applications: In long-running applications, WiPy WDT can prevent the system from stopping due to software errors or other abnormal conditions. It can regularly detect the system status and restart the system when necessary to ensure the continuous and stable operation of the system.

Precautions:

Timer settings: When using WiPy WDT, you need to set the appropriate timer value according to specific application requirements. The setting of the timer should consider the time requirements of the system operation and the sensitivity of fault detection. A timer value that is too long or too short may cause the system to run abnormally or trigger a restart by mistake.
Dog-feeding operation: WiPy WDT requires regular dog-feeding operations, that is, resetting the WDT counter. This can be accomplished by inserting dog-feeding instructions into your code at regular intervals. The dog feeding operation should be completed within the specified time to avoid WDT triggering a system restart.
Exception handling: When WiPy WDT triggers a system restart, appropriate exception handling is required. After restarting, the system should be able to properly initialize and return to normal operating status to avoid falling into a cycle of continuous restarts.

To sum up, MicroPython's WiPy Watchdog Timer (WDT) is a timer used to monitor the operating status of the system and trigger a system restart in the event of a failure. It has the characteristics of system monitoring, fault detection and recovery, and hardware implementation. WiPy WDT is suitable for scenarios such as embedded systems, mission-critical applications, and long-running applications. When using WiPy WDT, you need to pay attention to timer settings, dog feeding operations, exception handling and other matters to ensure the reliability and stability of the system.

Insert image description here
Case 1: Set watchdog timer using MicroPython

from machine import WDT
import time

wdt = WDT(timeout=5000)  # 设置看门狗定时器超时时间为5秒

while True:
    # 执行任务
    pass
    time.sleep(1)  # 延时1秒

Case 2: Clear the watchdog timer using MicroPython

from machine import WDT
import time

wdt = WDT()

while True:
    # 执行任务
    pass
    time.sleep(1)  # 延时1秒
    # 清除看门狗定时器
    wdt.feed()

Case 3: Use MicroPython to check whether the watchdog timer has timed out

from machine import WDT
import time

wdt = WDT()

while True:
    # 执行任务
    pass
    time.sleep(1)  # 延时1秒
    if wdt.feeded():
        print("WDT expired!")
    else:
        print("WDT is still running.")

Case 4: Basic use

import machine  
import utime  
  
# 设置看门狗定时器参数  
WDT = machine.WatchDog(10000)  # 10秒,这是WiPy的默认值  
WDT.start()  
  
while True:  
    print("主程序运行中...")  
    utime.sleep(1)  # 模拟主程序运行

Case 5: Use WDT to handle exceptions

import machine  
import utime  
  
# 设置看门狗定时器参数  
WDT = machine.WatchDog(10000)  # 10秒,这是WiPy的默认值  
WDT.start()  
  
try:  
    while True:  
        print("主程序运行中...")  
        utime.sleep(1)  # 模拟主程序运行  
except Exception as e:  
    print("主程序出现异常:", e)  
    WDT.feed()  # 手动触发看门狗重启

Case 6: Using WDT to handle blocking

import machine  
import utime  
import network  
  
# 设置看门狗定时器参数  
WDT = machine.WatchDog(10000)  # 10秒,这是WiPy的默认值  
WDT.start()  
  
while True:  
    print("主程序运行中...")  
    utime.sleep(1)  # 模拟主程序运行  
    try:  
        network.WLAN(network.STA_IF).active(True)  # 尝试连接网络,可能会阻塞  
    except Exception as e:  
        print("连接网络时出现异常:", e)  
        WDT.feed()  # 手动触发看门狗重启

The above code is for reference only and needs to be adjusted according to specific application scenarios and needs during actual use. Note that although using WDT can improve the robustness of the program to a certain extent, over-reliance on WDT may conceal real problems in the program, so when designing and writing code, exceptions and blocking should be avoided as much as possible.

Case 7: Basic application

import machine
import time

wdt = machine.WDT(timeout=5000)  # 设置定时器超时时间为5秒

while True:
    # 执行任务代码
    # ...

    wdt.feed()  # 喂狗操作,重置WDT计数器
    time.sleep(1)  # 延时等待1秒

Case 8: Mission-critical application

import machine
import time

wdt = machine.WDT(timeout=10000)  # 设置定时器超时时间为10秒

def critical_task():
    # 执行关键任务代码
    # ...

while True:
    try:
        critical_task()
    except Exception as e:
        # 发生异常,进行异常处理
        # ...

    wdt.feed()  # 喂狗操作,重置WDT计数器
    time.sleep(1)  # 延时等待1秒

Case 9: Long-running application

import machine
import time

wdt = machine.WDT(timeout=60000)  # 设置定时器超时时间为60秒

while True:
    # 执行长时间运行的代码
    # ...

    wdt.feed()  # 喂狗操作,重置WDT计数器
    time.sleep(10)  # 延时等待10秒

These code cases demonstrate different application scenarios of WiPy WDT. In each case, a WDT object is first created through machine.WDT(timeout) and the timer timeout is set. Then, execute the corresponding task code in the main loop, and use wdt.feed() to feed the dog and reset the WDT counter. Finally, control the frequency of task execution through appropriate delay operations. These codes are only reference examples and need to be appropriately modified and adjusted according to specific needs in actual applications. At the same time, in order to ensure the stability and reliability of the system, it is recommended to handle exceptions in the code and perform appropriate exception handling operations.

Please note that the above cases are only for expanding ideas and may contain errors or inapplicability. Different hardware platforms, usage scenarios and MicroPython versions may lead to different usage methods. In actual programming, you need to adjust it according to your hardware configuration and specific needs, and conduct multiple actual tests. It is important to ensure that the hardware is connected correctly and to understand the specifications and characteristics of the sensors and devices used.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/133412717