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

Hi, i am new with the programming, i am trying with the program below however the LED light cannot hold even PIR continue active. It still turn on and off follow the delay timer. The desire result is LED should be continue on as long as motion is still actively detected by PIR. Appreciate your help, thanks

int LED = 13;
int PIR =2;
bool IN = LOW;

void setup() {
pinMode (LED, OUTPUT);
pinMode (PIR, OUTPUT);
Serial.begin(9600);
}

void loop()
{
PIR_F ();
LED_F ();
}

void PIR_F () {
IN = digitalRead(PIR);
}

void LED_F (){
if (IN == HIGH)
{
digitalWrite(LED, HIGH);
Serial.printIn("Intruder detected!");
delay(100);

}
else
{
digitalWrite(LED, LOW);
Serial.printIn("Intruder gone!");
delay(200);
}
}

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

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.