0
0
AutocadHow-ToBeginner · 4 min read

How to Use Watchdog Timer in Arduino for Reliable Code

Use the avr/wdt.h library to enable the watchdog timer in Arduino. Call wdt_enable(timeout) to start it and wdt_reset() regularly in your code to prevent reset. If the timer is not reset in time, the Arduino will automatically restart.
📐

Syntax

The watchdog timer is controlled using functions from the avr/wdt.h library. The main functions are:

  • wdt_enable(timeout): Starts the watchdog timer with a specified timeout.
  • wdt_reset(): Resets the watchdog timer to prevent it from triggering a reset.
  • wdt_disable(): Turns off the watchdog timer.

The timeout parameter sets how long the watchdog waits before resetting the Arduino if wdt_reset() is not called.

arduino
#include <avr/wdt.h>

void setup() {
  // Enable watchdog timer with 2 second timeout
  wdt_enable(WDTO_2S);
}

void loop() {
  // Reset watchdog timer regularly
  wdt_reset();
  // Your code here
}
💻

Example

This example shows how to use the watchdog timer to reset the Arduino if the loop stops calling wdt_reset(). It blinks the built-in LED and resets the watchdog each loop. If you comment out wdt_reset(), the Arduino will reset after 2 seconds.

arduino
#include <avr/wdt.h>

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  wdt_enable(WDTO_2S); // Enable watchdog with 2 seconds timeout
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);

  wdt_reset(); // Reset watchdog timer to prevent reset
}
Output
The built-in LED blinks on and off every 0.5 seconds continuously. If wdt_reset() is removed, the Arduino resets every 2 seconds.
⚠️

Common Pitfalls

Common mistakes when using the watchdog timer include:

  • Not calling wdt_reset() regularly, causing unwanted resets.
  • Forgetting to include #include <avr/wdt.h>.
  • Not disabling the watchdog before uploading new code, which can cause upload failures.
  • Using very short timeouts that reset the board too quickly.

Always test your code with the watchdog enabled to ensure it behaves as expected.

arduino
#include <avr/wdt.h>

void setup() {
  // Wrong: Not enabling watchdog
}

void loop() {
  // Wrong: Not resetting watchdog
  delay(1000);
}

// Correct way:
// wdt_enable(WDTO_2S);
// wdt_reset(); inside loop()
📊

Quick Reference

FunctionDescription
wdt_enable(timeout)Starts watchdog timer with timeout (e.g., WDTO_2S for 2 seconds)
wdt_reset()Resets watchdog timer to prevent reset
wdt_disable()Disables the watchdog timer
Timeout optionsWDTO_15MS, WDTO_30MS, WDTO_60MS, WDTO_120MS, WDTO_250MS, WDTO_500MS, WDTO_1S, WDTO_2S, WDTO_4S, WDTO_8S

Key Takeaways

Include avr/wdt.h to use the watchdog timer in Arduino.
Call wdt_enable(timeout) to start the watchdog with a timeout.
Regularly call wdt_reset() in your loop to avoid unwanted resets.
Disable the watchdog before uploading new code if needed.
Test your code carefully to ensure the watchdog behaves as expected.