counting Magnetic door Sensor

Hello!

I've been working on a small project just to get more into Arduino. Now I've got a problem which I don't know how to solve it anymore.

Background info: Im using a 16x2 LCD and a magnetic door sensor (same as this one: http://www.instructables.com/id/Magnetic-Door-Sensor-and-Arduino/ ). I want it to count each time de door opens.

Problem: Each time the door is open (magnetic doorsensor == HIGH) it keeps counting until the door closes again.

What I want: each time the door opens (HIGH) it counts with +1.

The Sketch:

#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //instellen lcd pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

int doorsensor =7;
int state; //0 close - 1 open - current state of the button
int buttonPushCounter = 0;   // counter for the number of button presses
int lastButtonState = 0;
boolean currentState = LOW;

void setup() {
  // put your setup code here, to run once:
pinMode(doorsensor, INPUT_PULLUP);
}

void loop() {
 
  // bepalen hoe lang de deur openstaat
state = digitalRead(doorsensor);

 // compare the buttonState to its previous state
  if (state != lastButtonState) {
    // if the state has changed, increment the counter
    if (state == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      lcd.setCursor(10,0);
    
      }
     
      }
lcd.setCursor(10, 1);
lcd.print(buttonPushCounter);

Can someone help me out?

Thanks in advance!

Somewhere, you need to set lastButtonState to state.

ah man. you're my hero. thanks so much :slight_smile: