#include <TimerOne.h>

#define PIN_LIGHT_ON 9 // Actif à l'état haut
#define PIN_POWER_ON 12 // Actif à l'état haut
#define PIN_BP_MA 2

volatile unsigned long elapsedTime = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(PIN_POWER_ON, OUTPUT);
  pinMode(PIN_LIGHT_ON, OUTPUT);
  Timer1.attachInterrupt(lightOff);
  digitalWrite(PIN_POWER_ON, HIGH);
  digitalWrite(PIN_LIGHT_ON, HIGH);
  //  /*********************************************************/
  //  /************* Pour débogage seulement *******************/
  //  /*********************************************************/
  //  Serial.begin(38400);
  //  Serial.println("Power on");
  //  /*********************************************************/
  Timer1.stop();
  attachInterrupt(0, buttonActionned, CHANGE);
}

void loop() {
  // put your main code here, to run repeatedly:
}

/***************************************************************/
/*  ISR appelée lors d'un appui sur le bouton Marche / arrêt   */
/***************************************************************/
void buttonActionned() {
  boolean state;
  state = digitalRead(PIN_BP_MA);
  if (state) {
    elapsedTime = millis();
    digitalWrite(PIN_LIGHT_ON, HIGH);
    // Tempo d'appui long pour désalimenter
    Timer1.initialize(2000000);
    Timer1.resume();
    //    _delay_us(100);
    //    TIFR1 = 1 << TOV1;
  }
}

/*********************************************************/
/*  ISR appelée à la fin de la temporisation de 2 s      */
/*********************************************************/
void lightOff() {
  boolean state;
  static boolean flag = false;
  state = digitalRead(PIN_BP_MA);
  if (state)
    digitalWrite(PIN_POWER_ON, LOW);
  else {
    if (!flag) {
      // Tempo d'allumage du rétro-éclairage qui s'ajoute aux 2 s
      Timer1.initialize(3000000);
      Timer1.resume();
      //      _delay_us(100);
      //      TIFR1 = 1 << TOV1;
      flag = true;
    }
    else {
      digitalWrite(PIN_LIGHT_ON, LOW);
      flag = false;
    }
  }
}

