const uint8_t led_pin = LED_BUILTIN;
const uint8_t pir_pin = 5;
uint32_t PIR_changed_LOWtoHIGH;
const uint32_t lightsOnPeriod = 2500;
uint8_t pir_state;
uint8_t lastPir_state;
boolean lightsAreOn = false;
void setup() {
Serial.begin( 115200 );
Serial.println("Setup-Start");
pinMode( led_pin, OUTPUT );
pinMode( pir_pin, INPUT );
}
void loop() {
// read in actual state of PIR-pin
pir_state = digitalRead( pir_pin );
// check if PIR-pin changes from low to high
if ( lastPir_state == LOW && pir_state == HIGH ) {
// when value of variable with name "lastPir_state" is LOW
// and variable with name "pir_state" is HIGH
// the moment the PIR-sensor switched ON is detected
Serial.println( F( "PIR state-CHANGE LOW to HIGH detected" ) );
PIR_changed_LOWtoHIGH = millis(); // store snapshot of time
digitalWrite(led_pin,HIGH); // switch lights on
lightsAreOn = true; // set flag lightsAreOn
Serial.println( F( "lights switched ON" ) );
}
// check if lights are switched on
if (lightsAreOn == true) {
// in case variable "lightsAreOn" HAS value true
// == lights ARE switched on
// check if time the lights shall stay on is over
if (millis() - PIR_changed_LOWtoHIGH >= lightsOnPeriod) {
// when more milliseconds have passed by than stored in
// variable lightsOnPeriod
digitalWrite(led_pin,LOW); // switch off lights
Serial.println( F( "lights switched off" ) );
Serial.println();
lightsAreOn = false; // set flag-variable back to false
}
}
lastPir_state = pir_state; // update variable lastPir_state
}