A watchdog task helps keep your system safe by checking if other tasks are working properly. If something goes wrong, it can restart or fix the problem.
Watchdog task pattern in FreeRTOS
void WatchdogTask(void *pvParameters) {
for (;;) {
// Check other tasks' status
if (tasksAreHealthy()) {
// Reset watchdog timer
ResetWatchdogTimer();
} else {
// Take recovery action
HandleError();
}
vTaskDelay(pdMS_TO_TICKS(1000));
}
}The watchdog task runs in an infinite loop to continuously monitor other tasks.
Use vTaskDelay() to wait between checks without blocking the system.
void WatchdogTask(void *pvParameters) {
for (;;) {
if (AllTasksResponding()) {
ResetWatchdogTimer();
} else {
RestartSystem();
}
vTaskDelay(pdMS_TO_TICKS(500));
}
}void WatchdogTask(void *pvParameters) {
for (;;) {
if (CheckTaskStatus()) {
ResetWatchdogTimer();
} else {
LogError();
AttemptRecovery();
}
vTaskDelay(pdMS_TO_TICKS(2000));
}
}This program simulates a watchdog task checking other tasks. It prints a message when resetting the watchdog timer or when an error is detected. The main function runs the check 7 times to show both normal and error cases.
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> // Simulated function to check if tasks are healthy int tasksAreHealthy() { static int count = 0; count++; // Simulate a failure every 5 checks return (count % 5) != 0; } void ResetWatchdogTimer() { printf("Watchdog timer reset.\n"); } void HandleError() { printf("Error detected! Taking recovery action.\n"); } void WatchdogTask(void *pvParameters) { for (;;) { if (tasksAreHealthy()) { ResetWatchdogTimer(); } else { HandleError(); } vTaskDelay(pdMS_TO_TICKS(1000)); } } int main() { // Normally FreeRTOS scheduler would be started here // For demonstration, run WatchdogTask loop 7 times manually for (int i = 0; i < 7; i++) { if (tasksAreHealthy()) { ResetWatchdogTimer(); } else { HandleError(); } } return 0; }
Make sure the watchdog task runs with enough priority to check other tasks regularly.
Use simple and fast checks inside the watchdog task to avoid delays.
Resetting the watchdog timer usually prevents the system from resetting.
The watchdog task pattern helps keep your system running smoothly by monitoring other tasks.
It runs in a loop, checking tasks and resetting a timer or taking action if something is wrong.
This pattern improves system reliability and helps recover from errors automatically.