int ldr = A2;    
int led = 2;
int threshold=1023, value, t, state=false, run=false;
unsigned long startT;

void setup() {
  Serial.begin(9600);
  Serial.write(27); 
  Serial.print("[3;10H");
  Serial.print("---===[ Energy Monitor ]===--- ");
  Serial.write(27); 
  Serial.print("[10;10H");
  Serial.print("Running ");
  Serial.write(27); 
  Serial.print("[7;10H");
  Serial.print("Current energy consumption ");
  pinMode(led, OUTPUT);  
  startT=millis();  
}

void loop() {
  // measure light level
  value = analogRead(ldr); 
  
  // record flash
  if (value>threshold+20){
    digitalWrite(led, HIGH);
    if (state==false){
      t++;  
      state=true;
    }
  }
  if (value<threshold-20){
    digitalWrite(led, LOW);  
    state=false;
  }
  threshold=value;
  delay(100);     
  
  // indicate that the program is still running
  Serial.write(27); 
  Serial.print("[10;18H");
  if (run==true){
    Serial.print("o");
    run=false;
  }
  else{
    Serial.print("x");
    run=true;
  }


  // see if 1 minute has elapsed 60000 millisec
  if (millis()>startT+60000){
    // send data to PC
    Serial.write(27); 
    Serial.print("[7;38H");
    //Serial.print("Current energy consumption: ");
    Serial.print(t*60);
    Serial.print(" W        ");
    // restart the timer 
    startT = millis();
    t = 0;
  }
  // check for overflow, start again
  if (millis()<startT){
    startT = millis();
    t = 0;
  }
}

