counter incrementing by 2

I am trying to get a counter to increment by 1 every time but instead it keeps incrementing by 2? Does anyone know why this might be the case?
I have a switch connected to pin 7 and every time i press it i want the counter to increment by 1.

Here is my code I've written so far....

const int buttonPin = 7; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to

int buttonState = 1; // current state of the button
int lastButtonState = 1; // previous state of the button
int ledState = 0; // remember current led state
int counter = 0;

void setup() {
pinMode(buttonPin, INPUT); // initialize the button pin as a input
pinMode(ledPin, OUTPUT); // initialize the button pin as a output
Serial.begin(57600);
}

void loop(){
buttonState = digitalRead(buttonPin);
// Serial.println(buttonState);
if(buttonState < lastButtonState)
{
// detected positive edge
lastButtonState = buttonState;
counter++;
Serial.println(counter);
if(counter > 4)
{
counter = 0;
}
}
else
{
lastButtonState = buttonState;
}
}

If anyone could help that would be great. I can't figure it out!
Thanks :slight_smile:

It might be because you dont have a delay, and your code has time to run the counter twice before you remove your finger. Try using this loop.

void loop(){
buttonState = digitalRead(buttonPin);
// Serial.println(buttonState);
if(buttonState < lastButtonState)
{
// detected positive edge
lastButtonState = buttonState;
counter++;
Serial.println(counter);
if(counter > 4)
{
counter = 0;
}
delay(300);
}
else
{
lastButtonState = buttonState;
}
}

that fixed it thanks so much.
such a small thing dont know how i missed it! :slight_smile:

Similar problems will arise if switches aren't "de-bounced"....

See....

There isn't "one right answer" to the problem of bounce. You have to decide whether "blocking" behavior matters to you. ("Blocking": The Arduino does nothing further until you release the button.) If not, solving the bounce problem is easy. If it does, you have to get more clever.