attachInterrupt CHANGE question

volatile int count = 0;

void setup()
{
  Serial.begin(9600);
  attachInterrupt(0, counter, CHANGE);
}

void loop()
{
 Serial.println(count);
}

void counter()
{
  count++;
}

I tried implementing this code to try count each time the pin would change from 0 to 1 and from 1 to 0. The problem is that whenever its on changes to 0, it wont count, and whenever it changes to 1 it does count but, if it stays in 1 the counter will keep counting while its on 1. The idea is to increment the counter ONCE whenever it changes from 0 to 1 and ONCE whenever it changes from 1 to 0. Do i need some sort of validation to make this work? i was thinking that with CHANGE edge it would make this possible.

What is connected to the interrupt pin? How are you preventing the pin from floating? You certainly are not using the internal pullup resistor which would do that.

Its just a simple 2 legged pushbutton connected to my arduino uno pin 2

Its just a simple 2 legged pushbutton connected to my arduino uno pin 2

Both legs?

No of course not. Its connected from the 5v to the button and to pin 2.

Pulldown resistor on the other side from ground to the pin that connects to the input?

If not, that's your problem. A floating input. When the switch isn't pressed, the pin isn't connected to anything and can read any value as it picks up random interference from the environment.

An easier solution is to enable the internal pull-up resistors, connect your switch between the pin and ground instead of between the pin and 5V and invert your logic so LOW is a pressed button and HIGH is unpressed.

Its connected from the 5v to the button and to pin 2.

So, when the switch is pressed, there are 5V on the pin. When the switch is not pressed, how many volts are on the pin? Without a pullup or pulldown resistor, the answer is that you do NOT know. That is NOT a situation that leads to stable code.

You MUST use a pullup or pulldown resistor.

What about switch bounce? You're going to get that even with a perfect pullup circuit. So you may not get the count that you expect.