How Does a Watchdog Timer Work? Principle, Calculation and Applications

A watchdog timer is a hardware-based monitoring mechanism used in embedded systems, industrial controllers, routers, and IoT devices. By continuously monitoring system activity, it can detect software failures such as system hangs or infinite loops and automatically trigger a reset, ensuring reliable operation for industrial equipment, DTUs, and network devices.

Что такое сторожевой пес?

A watchdog timer, sometimes implemented as a dedicated watchdog chip, is a hardware component used to monitor the operation of a microcontroller or embedded system. If the system becomes unresponsive or enters an infinite execution loop, the watchdog timer generates a reset signal to recover the system. A watchdog is a safety mechanism in embedded systems that makes your system reliable, but it depends on how the watchdog timer is used.

Как работает сторожевая защита

How does watchdog protection work?

A watchdog is basically a counter that starts counting from zero and reaches a certain value. If the counter reaches a certain value, the watchdog hardware will generate a watchdog reset.

To prevent an unnecessary system reset, the software must periodically reset the watchdog counter, a process commonly known as “feeding” or “kicking” the watchdog. In case the software gets stuck in an endless loop, the system will not be able to kick the watchdog, so the counter reaches a certain value and resets the system.

Сторожевая защита изначально загружена определенными значениями. Это значение вычисляется на основе тайм-аута сторожевого таймера (дополнительные инструкции по вычислению значения счетчика на основе значения тайм-аута приведены). Перед завершением тайм-аута система должна сбросить счетчик.

For example, if your system executes 3 tasks regularly, and it takes 500 milliseconds to execute 3 tasks. Then consider the timeout as 600 ms (considering the worst-case scenario), calculate the counter value for 600 ms, and load it into the watchdog.

Watchdog Timer Calculation Example

Consider the system in the Watchdog is operating with a 4 kHz clock. The system completes the work in 450 milliseconds, and in the worst case, it takes 500 milliseconds to complete the work. Let’s use 500 milliseconds as the timeout.

1/4 кГц = 0,25 миллисекунды

1 такт = 0,25 миллисекунды.

500 миллисекунд = 2000 тиков.

When the clock reaches 2000 ticks, the watchdog timeout period reaches 500 milliseconds. The technical value associated with the timeout is 2000.

Если счетчик сторожевого таймера достигает 2000, он генерирует сигнал сброса. Системе необходимо сбросить счетчик в 0 до достижения 2000.

Как работает сторожевая защита

How to Configure a Watchdog Timer in Embedded and Industrial Systems?

Configuring a watchdog timer correctly is essential for improving system reliability. An improperly configured watchdog may cause unnecessary resets or fail to recover the system when a fault occurs.

1. Check the Device Manual

The watchdog function of PLCs, inverters, and other industrial devices can usually be enabled through configuration parameters (such as the “watchdog timer” parameter in Siemens PLCs). Always refer to the device manual for proper configuration.

2. Set an Appropriate Timeout Period

The watchdog timeout is generally set to 1.5–2 times the normal operating cycle of the system. For example, if the normal system response time is 300 ms, the timeout can be configured to 500 ms.

3. Enable Fault Logging

When enabling watchdog protection, it is recommended to enable device fault logging at the same time. This helps engineers analyze why the watchdog was triggered, such as whether the cause was electromagnetic interference, software issues, or other system failures.

Расширенные возможности использования сторожевых таймеров

In multitasking operating systems, watchdog timers can monitor not only the overall system status but also the execution of individual tasks. Each task can periodically report its status to the watchdog monitor. If a task stops responding or fails to complete within the expected time, the watchdog can trigger a system reset.

In the case of online supervision, each task has a flag set to indicate that the task is online, that is, executed. The watchdog monitor function will check whether each task has reported an active indication. If the task is not set to activate an indication, the watchdog monitor function will never kick the watchdog, and eventually, the watchdog will reset the system.

Области применения сторожевой защиты

1. Watchdog Protection in Industrial IoT Gateways

Промышленные IoT-шлюзы are usually installed in remote or unattended locations where manual maintenance is difficult. In these environments, system stability is critical because any unexpected software failure or communication interruption may affect data transmission and remote monitoring.

A built-in watchdog timer can automatically detect abnormal conditions and restart the system when necessary, allowing the gateway to automatically recover from software crashes, system freezes, or unexpected operating conditions without manual intervention. This ensures reliable communication between field devices and cloud platforms.

2. Embedded Systems

Во встраиваемых системах для контроля работы микроконтроллеров используется защита watchdog. Поскольку встраиваемые устройства часто работают без присмотра, любой программный сбой или аппаратная ошибка могут привести к сбою системы. Сторожевой таймер регулярно проверяет реакцию системы, чтобы убедиться, что устройство работает нормально. Если устройство не сможет вовремя отправить сигнал, сторожевой таймер перезагрузит систему, чтобы восстановить работоспособность.

3. Industrial Automation

На сайте промышленная автоматизация, Надежность оборудования имеет решающее значение, поскольку простои могут привести к значительным финансовым потерям. Сторожевая защита обеспечивает быстрое восстановление устройств на производственной линии после сбоев. Например, в роботах и системах управления при сбоях в программном обеспечении сторожевой таймер может оперативно перезапустить систему, поддерживая эффективность производства и минимизируя задержки.

4. Telecommunications

In telecommunications networks, routers and switches need to operate continuously to ensure stable data flow. Watchdog protection can monitor the status of these devices and address potential failures promptly. By resetting unresponsive devices, network administrators can reduce the risk of service interruptions and ensure high-quality connections for customers and overall network reliability.

5. Automotive Systems

Современные автомобили оснащены многочисленными электронными блоками управления (ECU), отвечающими за такие важные функции, как торможение, рулевое управление и системы питания. В этих системах очень важна защита сторожевого таймера, обеспечивающая правильную работу критически важных функций при любых обстоятельствах. Например, при сбое в работе управляющего программного обеспечения тормозной системы сторожевой таймер немедленно перезагрузит блок управления, обеспечив безопасную эксплуатацию автомобиля.

ЧАСТО ЗАДАВАЕМЫЕ ВОПРОСЫ

Q1: What is a watchdog timer?

A1: A watchdog timer is a hardware feature that monitors system activity and automatically resets the device if it becomes unresponsive or enters an infinite loop.

Q2: How is a watchdog timer calculated?

A2: The timer value is set based on the system’s execution time. If the system doesn’t reset the counter before the timeout, the watchdog triggers a system reset.

Q3: Can 4G DTU/RTU devices use watchdog protection?

A3: Yes. 4G DTU/RTU and other industrial routers often include watchdog timers to maintain reliable operation and prevent downtime in IoT and industrial networks.

Q4: What happens when a watchdog timer expires?

A4: When the watchdog timer expires, the hardware generates a reset signal, and the system restarts to recover from the fault condition.

Q5: Why is watchdog protection important for industrial devices?

A5: Watchdog protection improves system reliability by allowing embedded devices, industrial gateways, and remote controllers to automatically recover from software failures without manual maintenance.

Резюме

Сторожевая защита демонстрирует свою важность в различных отраслях промышленности, повышая надежность и безопасность систем. Оперативно отслеживая и устраняя неисправности, она обеспечивает надежную поддержку многих промышленных устройств и автомобильных систем.