int flag=0;
int t1=0;
int t2=0;
const int buzzerPin = 7;  
//buzzer pin in D7
void setup() 
{
  Serial.begin(115200);
  pinMode(5,OUTPUT); 
  //Ir sensor output
  pinMode(11, OUTPUT);  
  //LED pin output
  pinMode(buzzerPin, OUTPUT);  
  //Buzzer output
  

}
void loop() 
{
  int x=analogRead(A0);
  //Serial.println(x);

    if(x<500 && flag==0)
  {
    flag=1;
    t1=micros();  
    // time in micros
  }
  else if(x>500 && flag==1) 
   //if condition to read value
  {
    flag=0;
    t2=micros();    
    // T2 in micros
    Serial.println(t2-t1);
    if((t2-t1)>5000)   
    // sleep detection on lower value
    {
      digitalWrite(5,HIGH); 
      // IR pin HIGH
      digitalWrite(11,HIGH);  
      //LED pin HIGH
      tone(buzzerPin, 1000);  
      // buzzer will ring when LED turn ON
      Serial.println("ALERT : WAKE UP");    
      // Alert to get up
      delay(6000);  
      // delay of 6 sec
      digitalWrite(5,LOW);
      // IR pin LOW
      digitalWrite(11,LOW);
      // LED LOW
      noTone(buzzerPin);  
      // no tone in buzzer 
      
    }
       
      }
    }