/*
* Using the watchdog timer as a timed interrupt 
 *
 */

#include <avr/wdt.h>
int delayval = 11738;  // microseconds-Brain LED 40hz half cycle not specific
bool system_on = true;
int iterationcnt = 3;// the wd cycle is set for 4 seconds then multiply by this.

void setup() {
  //#### SETUP ####
  wdt_reset();
  // initialize the digital pin as an output.
  //pinMode(0, OUTPUT);  //LED on Model B
  pinMode(1, OUTPUT);  //LED on Model A  or Pro
  pinMode(2, OUTPUT);  //LED on Model A  or Pro
                       // Disable all interrupts
  cli();

  // Clear MCU Status Register
  // Not really needed here as we don't need to know why the MCU got reset. P.44
  MCUSR = 0;

  // Disable and clear all Watchdog settings P.46
  // Not really sure this is needed as we never set the WDE, but nice to be thorough
  WDTCR = bit(WDCE) | bit(WDE) | bit(WDIF);   // allow changes, disable reset, clear existing interrupt
  WDTCR = bit(WDIE) | bit(WDP3) | bit(WDP3);  // set WDIE ( Interrupt only, no Reset ) and 4s TimeOut
  wdt_reset();                                // reset WDog to parameters

  // Enable all interrupts.
  sei();

  //#### END OF SETUP ####
}
// Do the timing.
void loop() {

  if (system_on) {
    //digitalWrite(0, HIGH);  // turn the LED on (HIGH is the voltage level)
    digitalWrite(1, HIGH);
    //digitalWrite(2, HIGH);
    delayMicroseconds(delayval);  // wait for 25 milliseconds for 40 hz, 12 - 43.1khz, 13 - 39.8khz
  }
  //digitalWrite(0, LOW);  // turn the LED off by making the voltage LOW
  digitalWrite(1, LOW);
  //digitalWrite(2, LOW);
  delayMicroseconds(delayval);  // wait for 25 milliseconds for 40 hz, 12 - 43.1khz, 13 - 39.8khz
}

ISR(WDT_vect) {
  cli();
  //wdt_disable();
  wdt_reset();
  sei();
  if (iterationcnt > 1) {
    iterationcnt--;
  } else {
    wdt_disable();
    system_on = false;
  }
}
