if(digitalRead(sensor_pin) == HIGH){ //the sensor has detected motion
//enclose the code here so it only executes once when motion is detected
if(detected == false){
Serial.println("Motion detected!");
detected = true;
digitalWrite(led_pin, HIGH); //turn led on
digitalWrite(relay_pin, HIGH); //switch the relay on
}
}else{ //the sensor has stopped detecting motion
if(detected == true){ //execute this only once when motion stops
Serial.println("Motion stopped!");
detected = false;
digitalWrite(led_pin, LOW); //turn the led off
motion_stopped_time = millis(); //remember the current time
stop_relay = true;
}else{
if(stop_relay == true){ // ensures that this block will only execute once after the delay timer logic below
//the current millis() time is 60sec more than the remembered time when the motion stopped
if(millis() - motion_stopped_time >= 60000){
digitalWrite(relay_pin, LOW); //switch the relay off
stop_relay = false;
}