Watchdog timer in Arduino


A watchdog timer is an essential part of any microcontroller. It resets the program if the program gets stuck anywhere. Very briefly, this is how the watchdog timer works −

  • The timer keeps incrementing.

  • The program has to ensure that it keeps resetting the timer, i.e. does not allow it to overflow.

  • If the timer overflows, it means that the program was stuck somewhere and therefore was unable to reset the timer. An interrupt is generated on timer overflow which resets the microcontroller.

To implement watchdog timer in Arduino, we use the avr wdt library.

The code is given below −

#include<avr/wdt.h>
void setup() {
   Serial.begin(9600);
   wdt_disable(); //Disable WDT
   delay(3000);
   wdt_enable(WDTO_2S); //Enable WDT with a timeout of 2 seconds
   Serial.println("WDT Enabled");
}
void loop() {
   for(int i = 0; i<5; i++)
   {
      Serial.println("Looping");
      delay(1000);
      wdt_reset(); //Reset the watchdog
   }
   while(1); //Watchdog timer should get triggered here
}

As you can see, we initialize Serial and first disable watchdog timer. Then a delay of 3 seconds is introduced. The program won't reset here, because the watchdog is disabled. Now, the watchdog timer with a timeout of 2 seconds is enabled. It means, if the program doesn't reset this timer within every 2 seconds, then the watchdog will get triggered and restart the microcontroller.

Within the loop, we first print to the Serial for 5 seconds, making sure to reset the watchdog every second. The program works fine so far. Then, we enter into an infinite while loop. Over here, since we are not resetting the wdt, it will get triggered and restart the Arduino.

Note that the preset watchdog timeout values are available from 15 ms to 8 s.

Updated on: 24-Jul-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements