Millis time calculation logic

Dear friends, I am doing PIR motion sensor. The outputs is COUNT (if there is any motion) till 30 seconds after that COUNT will be RESET. If no motion for 60 seconds, I wish to output 0. (as shown in below code). But this part is not working. Guess, i make some(stupid) mistake on on second loop. I can not think the correct logic/ (trying more than hour :| ). Any thoughts useful !

 int pirPin = 2; //digital 2
 const int ledPin = 13;  
 int  count=0;

unsigned long previousMillis = 0;
unsigned long interval2 = 60000;   
unsigned long interval1 = 30000;


void setup(){
 Serial.begin(9600); 
 pinMode(pirPin, INPUT);
 pinMode(ledPin, OUTPUT);
}


void loop(){
  unsigned long currentMillis = millis();
  int pirVal = digitalRead(pirPin);
      delay(900);
    if(pirVal==LOW) {
      
    Serial.print("Motion Sensor count");
    //delay(100); 
    count++;
   // Serial.print("Count = ");
       
    Serial.println(count);
    digitalWrite(ledPin, HIGH);  // turn LED ON   
    delay(1800); 
     
    digitalWrite(ledPin, LOW);  // turn LED ON 
    delay(100);
    
    }
   if(currentMillis - previousMillis > interval1)
    { 
      previousMillis = currentMillis;
      count = 0;
      
     } 
    
       if(currentMillis - previousMillis > interval2) 
  {
  
   Serial.println(" Sensor output   0"); 
    previousMillis = currentMillis; 
  }

}

Could it be something to do with the fact that you've only got one "previousMillis" variable?

      delay(900);

Why?

A motion sensor outputs one value when there is motion and another when there is no motion. Counting while the value is one thing makes no sense. You need to count the changes from no motion to motion or from motion to no motion. Look at the state change detection example.

Get rid of ALL of the delay()s.

    digitalWrite(ledPin, HIGH);  // turn LED ON   
    delay(1800); 
     
    digitalWrite(ledPin, LOW);  // turn LED ON

Do you mean "turn LED OFF" in the second digitalWrite?

You are not using your time-outs to affect the LED pin at all, perhaps you meant to turn the LED pin off with the timeouts?

@ AWOL: correct. Not sure how to use “previousMillis” variable" correctly when i use multiple times. Any logic ?

@PaulS: Using Zilog ePIR sensor, it is very sensitive. It counts each move as motion. After 4 seconds delay only it counts as i expected. I add the if(pirVal==LOW) in above code and reduce the delay between LED on /off .

Mark - Second line is actually it was LED off.

Still, clueless :expressionless:

Cheers!
Chandra

Not sure how to use "previousMillis" variable" correctly when i use multiple times. Any logic ?

Have a similarly-named variable for each instance, or an array, or a variable with a name more closely related to the action being performed. You normally only need one "now" though.