Watchdog using timer 2

In computer science you are tought how to write code which never fails.
So much about the theory.

In reality everyone knows the world is full of procedures which never terminate.

So it's good to have somebody telling you: o.k., don't wait any longer, just give up!

Personally, I don't like dogs, but that's what you call a watchdog.
If you are not happy with software watchdogs have a look at this one.

Practically all controllers - not only the ones made by Atmel - offer a built-in watchdog.
It can be used by including <avr/wdt.h>, enabled by wdt_enable(WDTO_8S) and disabled by wdt_disable().

So, if there is an existing watchdog why create a new one?

Actually, the maximum timeout is set to 8 seconds (assumed a quartz frequency of 16 MHz). Further more, it looks like in certain cases the watchdog does not watch - or bark. So, given that timer2 will often be unused I wrote a watchdog using timer2. If timer2 is used otherwise this library should not be included.

header file cpp file>

#ifndef WATCHDOG_h
#define WATCHDOG_h

#include <inttypes.h>

class WATCHDOGClass {
  void setInterrupt();
  void controlInterrupt(int t);
  static const uint8_t mode = 7;


  WATCHDOG.cpp - WATCHDOG library

#include "Arduino.h"
#include "WATCHDOG.h"

static const uint8_t ocr2a = 255;
static const int freq = F_CPU / 1024 / ocr2a / 2;
int timeOut;

void WATCHDOGClass::setInterrupt() {
  TCNT2  = 0;
  TCCR2A = B00000010;   // Configure timer 2 for CTC mode
  TCCR2B = mode;        // Start timer at Fcpu / prescaler
  TIMSK2 = B00000000;   // Disable CTC interrupt
  OCR2A  = ocr2a;       // Set CTC compare value 
  sei();                // Enable global interrupts

void WATCHDOGClass::controlInterrupt(int t) {
  timeOut = t;
  if (t == 0) TIMSK2 = B00000000; // disable
  else TIMSK2 = B00000010; // enable

  static int8_t i = freq;
  if (i-- < 0) {
    if (timeOut-- < 0) {
      asm volatile ("jmp 0");  // restart
    i = freq;


See also: Hardware watchdog

contact: nji(at)