detect movement via PIR then flash for 5 seconds then stop

Hi,

I am just getting my head around using my arduino pro mini and would appreciate some guidance. Basically I am trying to detect movement via the PIR, then flash for 5 seconds, and then stop. Sounds simple, but my problem is that during that flashing 5 seconds after initial detection, if another movement is detected, it will continue for another 5 seconds. I only want it to do this once and then begin detection after 5 seconds.

Here is my code

int LED=13;                         // build in led
int PIR = 2;                        // pir is on d2
bool alreadyDetected=false;         // detect if already detected (true) or not (false)
long unsigned int detectedTime=0;   // time when detected
bool ledon=false;                   // led state
long unsigned int lastLEDflashed=0; // time when led was switched on/off


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

void loop() {
  // read state of PIR
  int pirRead = digitalRead(PIR);
  
  if (alreadyDetected==false and pirRead==HIGH ) {
    // If not already deteched and PIR detected something, then set various flags
    detected();
  } else if (alreadyDetected) {
    // already in detected stage.  flash led or end detection
    if (millis() - detectedTime < 5000) {
      // do something for 5 seconds when detected - ie flash led
      flashLED();
    } else {
      // 5 seconds has passed since initial detected.  set various flags to end detection
      endDetect();
    }
  } 

  // tried to clear buffer but made no odds
  digitalRead(PIR);
}

void flashLED() {
   // FLASH EVERY SEC
  if (millis() - lastLEDflashed > 1000) {
    lastLEDflashed=millis();
    ledon=!ledon;
    digitalWrite(LED, ledon);
    Serial.print("flash");      //output
  }
  delay(50);
}

 void endDetect() {
    // end detection (ie after 5 seconds).  set various flags and turn off led
    detectedTime=0;
    alreadyDetected=false;
    ledon=false;
    lastLEDflashed = 0;
    digitalWrite(LED, LOW);
    Serial.print("motion ended");      //output
    delay(50);
}

void detected() {
    // movement detected.  set various flags and light up the led
    detectedTime = millis();

    ledon=true;
    lastLEDflashed = millis();
    digitalWrite(LED, HIGH);
    alreadyDetected=true;
    Serial.print("motion detected");      //output
    delay(50);
}

can anyone see the problem?

The problem is probably at least in part that your PIR pin remains high for some time.

So while flashing motion is detected, pin goes high, motion stops, pin is still high, and flashing is retriggered.

Solution: state change detection. Start your flashing when the pin goes high, not when it is high: remember the old state of the pin (as in: previous read), then if old is LOW and new is HIGH you had a state change.