How to enable hardware WDT on ESP32 using Arduino IDE



Watchdog timer (WDT) is an important feature for hardware devices like ESP32 or Arduino that need to auto recover from all kind of unexpected failures. On a previous post I wrote about how WDT works and how to set WDT on a Raspberry Pi, to make sure it stays up and running 24/7.

If we look at the esp-idf documentation about ESP32 WDT we can see that ESP32 comes with an interrupt watchdog and a task watchdog timer api. What many people are looking for is the task watchdog timer and I will show you in this article how to implement it using Arduino IDE.

Implementing ESP32 hardware watchdog timer using Arduino IDE

On ESP32, many people implement manually some sort of watchdog timer using flags and loops. This is NOT how it should be done, especially since ESP32 comes with a hardware watchdog timer.
#include <esp_task_wdt.h>

//3 seconds WDT
#define WDT_TIMEOUT 3

void setup() {
Serial.begin(115200);
Serial.println("Configuring WDT...");
esp_task_wdt_init(WDT_TIMEOUT, true); //enable panic so ESP32 restarts
esp_task_wdt_add(NULL); //add current thread to WDT watch

}

int i = 0;
int last = millis();

void loop() {
// resetting WDT every 2s, 5 times only
if (millis() - last >= 2000 && i < 5) {
Serial.println("Resetting WDT...");
esp_task_wdt_reset();
last = millis();
i++;
if (i == 5) {
Serial.println("Stopping WDT reset. CPU should reboot in 3s");
}
}
}

Now let’s look at the code. First of all you need to include the esp_task_wdt.h header. This should be available if you have properly installed arduino-esp32.

In the setup block we need to call two functions: 

esp_task_wdt_init(uint32_t timeoutSeconds, bool panic)
 and 
esp_task_wdt_add(TaskHandle_t handle)
.

  • esp_task_wdt_init is used to initialise WDT with a timeout of timeoutSeconds and with a panic mode set. If panic is set to true, when WDT times out, it will throw a hardware panic and reboot.
  • esp_task_wdt_add is used to add a task to WDT. If handle is NULL, the current task is used. 

Now, the watchdog timer need to be reset BEFORE it times out! This is done with 

esp_task_wdt_reset()
 executed in the current task. 

You can see that in this example I am initialising the WDT with a timeout of 3 seconds and then inn the main loop I am resetting it every 2 seconds. After five resets, I stop the reset call and let it timeout. As expected, it reboots my ESP32 after 3 seconds.  

No comments:

Post a Comment