/*Wake Up sleep dengan pin change Interrupt
Algoritma : ketika tombol tidak ditekan, arduino 
akan masuk sleep mode, tapi jika tombol ditekan arduino
akan tetap menjalankan loop utama*/

#include <avr/sleep.h>

const byte LEDLOOP = 13;
const byte BUTTON = 5;

unsigned long prev_millis = 0;
unsigned long current_millis;
long millis_interval = 10000;

volatile bool buttonPressed = false;

ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 // toggle LED
 if (digitalRead (BUTTON) == LOW) {
    buttonPressed = true;
 }
 }  

void setup () 
  {
  pinMode (LEDLOOP, OUTPUT);
  pinMode (BUTTON, INPUT);
  
  // pin change interrupt
  PCMSK2 |= bit (PCINT21);  // want pin 5
  PCIFR  |= bit (PCIF2);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE2);   // enable pin change interrupts for D0 to D7
  
  }

void loop () 
{
  if (!buttonPressed) {
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);  
  sleep_mode ();  
  
  }
  else {
  current_millis = millis();
  if(current_millis - prev_millis >= millis_interval) {
    prev_millis = current_millis;
    buttonPressed = false;
    }
  }
  digitalWrite (LEDLOOP, HIGH);
  delay (100);
  digitalWrite (LEDLOOP, LOW);
  delay (100);
  }