How to hold the LED when motion is still actively detected by PIR?

Here's a sketch that keeps a LED on for a certain time after the button has been pressed.

Keep pressing the button in time, and the LED stays on.

Read it, understand it, adapt it for your PIR "stretch".

Play with it here


Wokwi_badge UA Keep ALive!


// https://forum.arduino.cc/t/how-to-delay-using-millis/1142938
// https://wokwi.com/projects/368911815269434369

// version 4. remove anydebouncing

const byte buttonPin = 2;
const byte ledPin = 3;

const unsigned long actionDelay = 3500; // action 3.5 seconds for testing - life too short

void setup() {
  Serial.begin(115200);
  Serial.println("\nWake up!\n");

  pinMode (buttonPin, INPUT_PULLUP);
  pinMode (ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
}

void loop() {
  static unsigned long startTime; // time at action

  unsigned long now = millis();   // fancier 'currentMillis' ooh!
  int buttonState = !digitalRead(buttonPin);  // button pulled up!

// when the button is pressed, reset the timer, turn ON the LED
  if (buttonState == HIGH) {
    startTime = now;
    digitalWrite(ledPin, HIGH);
  }

// when (if!) the timer expires, turn OFF the LED
  if (now - startTime >= actionDelay) {
    digitalWrite(ledPin, LOW);
  }
}

HTH

a7