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:

tartang,

You might want to search for "debouncing" on this site. The problem is that because of the way that mechanical switches work, the switch sends two (or more) pulses every time you press it. The easiest way to compensate for this is to debounce it in your program.

Regards,

-Mike