Button with Interrupt Counter

HI I am trying to create some code that increments the value of a variable called bmode by 1 each time a button is pressed

The problem is that it seems to increase the value by 2 some times , 3 other times and by 1 if I time it right.

I have set the button up as an interrupt so that in my program no matter when the button is pressed it should increment the value of bmode.

Code

int pbIn = 0;                  // Interrupt 0 is DIGITAL PIN 2
volatile int state = LOW;      // The input state toggle
int bmode = 0;

void setup()
{   
     Serial.begin(9600);             
  // Set up the digital pin 2 to an Interrupt

  //Attach the interrupt to the input pin and monitor for ANY Change 
  attachInterrupt(pbIn, stateChange, CHANGE);
}

void loop()                     
{  
  Serial.println(bmode);
  //This is just hear so that I can see the interrupt interrupts the program when the button is pressed
  delay(50000);   			

}

void stateChange()
{
  state = !state;
  bmode = ++bmode;
}

How every thing is connected

You’ve rediscovered switch bounce !

http://en.wikipedia.org/wiki/Switch#Contact_bounce

http://www.elexp.com/t_bounc.htm

How quickly do you expect the switch to actually be pushed ? If that time is > than the settling time of the switch, a simple wait before “believing” the next switch indication is a simple and good way to fix your problem in software. See the example in the 2’nd link above.

BTW - you’ve set up the interrupt to happen on any change in the state of the pin. Even if there were no bounce, what happens when you push and then later release the switch ? Hint : more than 1 state change per cycle.

BTW2 - It appears you’ve got a normally open (NO) switch that when pushed, makes a contact to ground. You’ve got a pullup resistor that provides 5v to the input pin when the switch is not pushed. That’s good but you can use the Arduino’s internal pullup capability and eliminate that resistor and the wiring to it. Simpler is usually better.

http://arduino.cc/en/Reference/PinMode

http://arduino.cc/en/Tutorial/InputPullupSerial

I’d not use interrupts. Poll the I/O bit. Much simpler for a beginner.

Debounce the I/O bit. there a 10 to the 9th posts on the internet on how to debounce a switch using a microprocessor.

Hint: debouncing means ensuring that the bit does not change state for x miliseconds (switch dependent). Most cheap switches need 50mSec or so.

The interrupt driven approach is similar, but you use a timer in the microprocessor. In the timer interrupt handler (not the switch interrupt), you read the switch state and either increment or decrement a counter, based on state. Once per clock tick interrupt. Switch-pushed means count > x and switch-not-pushed means count < y. Or that concept. Say the timer interrupts every 10 mSec… then from this you derive x and y.