Counting events, getting weird results from ++ ?

Hi!

I'm working on a project that is using a PIR sensor, lights a led and then counts the number of events. After reaching a number something is going to happen (though that's not in the code now).
However I'm getting some really weird numbers. Instead of increasing by one, as I expected it too, it is increasing, but in intervals that I don't really understand the pattern of. Could someone please point me in the right direction..?

int ledPin = 13;                // pin for the LED
int inputPin = 8;               // input pin for the PIR sensor
int pirState = LOW;             // no motion detected to start with
int val = 0;                    // var for reading the pin status
int counter = 0;                // count the events


void setup() {
  pinMode(ledPin, OUTPUT);      // LED as output
  pinMode(inputPin, INPUT);     // sensor as input
  Serial.begin(9600);
}

void loop(){
  
  val = digitalRead(inputPin);   // read input value
  if (val == HIGH) {                // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    counter++;
    delay(150);
    
    if (pirState == LOW) {                
      Serial.println("Motion!");  // We only want to print on the output change, not state
      pirState = HIGH;
      Serial.println(counter);
    }
    
  } else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      delay(300);    
      if (pirState == HIGH){
      // we have just turned of
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }

}

How is the PIR wired ? Is the input pin floating at an unknown voltage or have you got a pulldown resistor in the circuit ?

You increment counter if digitalRead(inputPin) is HIGH.
You only Serial.print it though if pirState is LOW.

So some of the incremented values of counter will not be shown.

You want to move:

counter++;

to just before:

Serial.println(counter);
    if (pirState == LOW) {                
      Serial.println("Motion!");  // We only want to print on the output change, not state
      pirState = HIGH;

What, exactly, is PIR state? That name is something I'd use to hold the state I read from a PIR sensor. Clearly, you have some completely different idea that you have not explained. You can't set the state of a PIR sensor.

PaulS:

    if (pirState == LOW) {                

Serial.println("Motion!");  // We only want to print on the output change, not state
     pirState = HIGH;



What, exactly, is PIR state? That name is something I'd use to hold the state I read from a PIR sensor. Clearly, you have some completely different idea that you have not explained. You can't set the state of a PIR sensor.

From the context it appears he is using it to hold the previousPIRState (which would have been a better name).