Electronic – arduino – (Bad) counting digital pulses with Arduino using interrupts and a 4 pin switch

arduinointerruptsswitches

I have to write an Arduino sketch to accomplish some tasks with the number of digital pulses detected by a pin. For this purpose I chose to use interrupts in order not to miss any pulse and perform the rest of the algorithm virtually at the same time.

In order to make a quick test, I put on this circuit:

enter image description here

and I loaded this sketch (based on the example in the attachInterrupt documentation):

volatile unsigned int pulses=0;

void setup() {
  attachInterrupt(0, countpulses, FALLING); // interrupt 0 = pin 2      
  Serial.begin(9600);
}

void loop() {
  Serial.println(pulses);
  delay(500);
}

void countpulses() {
  pulses++;
}

What I expected here is that whenever I press and release the switch (and the red led turns on and off), it should read one pulse. The weird thing is that it counts two pulses instead, that is, it counts a pulse for each state change instead of just for the "falling" one.

Is this a matter of code or it's due to the switch? Will I have the same issue handling direct digital signals on pin 2?

Best Answer

Mechanical switches experience "contact bounce", which means that one press (or release) of the switch might cause the electical contact to make/break contact several times in rapid succession. This is what you are seeing with your code as it stands currently. The Arduino is fast enough to respond to each of the interrupts caused by this bouncing, even though you can't see it on the LED.