#include <avr/wdt.h>
#include <avr/sleep.h>
#include <avr/power.h>

#define LED_PIN (13)

volatile int f_wdt=1;
int adc;
ISR(WDT_vect)
{
  if(f_wdt == 0)
  {
    f_wdt=1;
  }
  else
  {
    Serial.println("WDT Overrun!!!");
  }
}

void enterSleep(void)
{
  set_sleep_mode(SLEEP_MODE_PWR_SAVE);
  
  sleep_enable();

  sleep_mode();
  
  sleep_disable();
  adc = analogRead(A0);
  delay(5000);
  Serial.println(adc);
  power_all_enable();
}

void setup() {
  Serial.begin(9600);
  Serial.println("Initialising...");
  delay(100);
  pinMode(LED_PIN,OUTPUT);


  MCUSR &= ~(1<<WDRF);



  WDTCSR |= (1<<WDCE) | (1<<WDE);

  WDTCSR = 1<<WDP0 | 1<<WDP3;

  WDTCSR |= _BV(WDIE);
  Serial.println("Initialisation complete.");
  delay(100);
 
}

void loop() {
  if(f_wdt == 1)
  {

    digitalWrite (LED_PIN, !digitalRead(LED_PIN));

    f_wdt = 0;

    enterSleep();
  }
  else
  {

  }
}