const uint8_t led_pin = LED_BUILTIN;
const uint8_t pir_pin = 5;
void setup()
{
Serial.begin( 115200 );
pinMode( led_pin, OUTPUT );
pinMode( pir_pin, INPUT );
}
void loop()
{
const uint32_t timestamp = millis();
const uint8_t pir_state = digitalRead( pir_pin );
static uint8_t pir_state_previous = UINT8_MAX;
static uint32_t led_timer_timestamp = 0;
static bool led_timer_state = false;
if ( pir_state_previous != pir_state )
{
pir_state_previous = pir_state;
Serial.print( F( "PIR state is " ) );
if ( pir_state == HIGH )
{
Serial.println( F( "HIGH" ) );
Serial.println( F( "LED ON for 2 seconds" ) );
digitalWrite( led_pin, HIGH );
led_timer_timestamp = timestamp;
led_timer_state = true;
}
else
{
Serial.println( F( "LOW" ) );
}
}
if ( led_timer_state == true && timestamp - led_timer_timestamp >= 2000 )
{
Serial.println( F( "LED OFF" ) );
digitalWrite( led_pin, LOW );
led_timer_state = false;
}
}