PIR Sensor and Arduino Counter

Hello, I'm having trouble with the output of my simulation. I am making a PIR sensor and Arduino simulation but instead of using motion detected or stopped, I decided to make it by counting how many motions detected. My problem here is when my pir sensor detects, it just keeps on increasing. Here is my code.

int inputPin = 13; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
int counter = 0;
int currentState = 0;
int previousState = 0;
void setup() {
pinMode(inputPin, INPUT); // declare sensor as input
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
if (pirState == LOW) {
// we have just turned on
currentState = 1;
// We only want to print on the output change, not state
pirState = HIGH;
delay(1000);
}
} else {
if (pirState == HIGH){
// we have just turned of
currentState = 0;
// We only want to print on the output change, not state
pirState = LOW;
}
}
if(currentState != previousState){
if(currentState == 1){
counter = counter + 1;
Serial.println(counter);
}
}
}

Try this simple code.......

int inputPin = 13; // choose the input pin (for PIR sensor)
int counter = 0;
bool flag = true;
void setup() {
  pinMode(inputPin, INPUT); // declare sensor as input
  Serial.begin(9600);
}
void loop() {
  if (digitalRead(inputPin) == HIGH) {    // check if the input is HIGH
    delay(30);                            // debouncing ....... May be not necessary
    if (digitalRead(inputPin) == HIGH) {
      if (flag == true)
      {
        counter++;
        flag = false;                         // Count 1 time only
        Serial.println(counter);
      }
    }
    else
    flag = true;
  }
}

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