What is Watchdog Timer ?

What is the situation while your micro-controller is confused in an infinite loop😖. What are the normal troubleshooting methods? Reset Button, Right? Is it practically possible to press on a button all time?😕. So, How about a device to perform this task? sounds good . Cool... !🙂.

Now we are discussing about such device which already inside on a micro-controller. That is Watchdog timer.

Watchdog Timer.

"A watchdog timer (WDT) is a hardware timer that automatically generates a  system reset if the main program neglects to periodically service it.  It is often used to automatically reset an embedded device that hangs  because of a software or hardware fault." (os.mbed.com/cookbook/WatchDog-Timer).

Feed the Dog !

If you have a dog in your home. You need to feed that dog on a regular interval. if you can't feed one day , it will bite you! Like this watchdog timer works.

We have a main part in program which runs over and over(loop). We are enabling watchdog timer is loaded with an initial value greater than the total delay in main program. Each time main program reset this timer. If any case the main program does not get back to reset the  timer before it counts down to zero,an interrupt is generated to reset the processor. Likewise watchdog timer protect micro-controller from hang case.

So, let's try watchdog timer in Arduino  ;)

In Arduino UNO uses ATMEGA328P micro-controller.

ATMEGA328P Watchdog timer 

Watchdog timer library

#include <avr/wdt.h>

Library is needed to use watchdog timer in Arduino

Enable Watchdog timer :

wdt_enable(WDT Reset Timer);

To enable watchdog timer, WDT RESET TIMER varies from 15ms - 8s

Constant Name Time delay
WDTO_15MS 15ms
WDTO_30MS 30ms
WDTO_60MS 60ms
WDTO_120MS 120ms
WDTO_250MS 250ms
WDTO_500MS 500ms
WDTO_1S 1s
WDTO_2S 2s
WDTO_4S 4s
WDTO_8S 8s

Eg: wdt_enable(WDT0_8S); --Enabled watchdog timer for 8Seconds

Reset watchdog timer

wdt_reset();

This function is used for resetting the watchdog timer. Reset function uses inside loop(). If your program uses a larger delay() which greater than threshold delay of watchdog timer, add reset function before that delay too. Else, It will reset Micro-controller before completing that task.

Disabling Watchdog timer

wdt_disable();

Example code :

#include <avr/wdt.h>

void setup(){
  Serial.begin(9600);
  Serial.println("Setup started :");
  // make a delay before enable WDT 
  // this delay help to complete all initial tasks
  delay(2000);
  wdt_enable(WDTO_4S);
}

void loop(){
  Serial.println("LOOP started ! ");
  for(int i=0; i<=5; i++){
    Serial.print("Loop : ");
    Serial.print(i);
    Serial.println();
    delay(1000);
    wdt_reset();
  }
  //infinity loop to hang MCU
  while(1){}
}

Output

Still confused about watchdog timer :(  Shoot your question in Makergram community section. : https://makergram.com/community/topic/152/what-is-watchdog-timer