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:
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?