Just a short note, so I don’t forget how to debounce switches attached to the hardware interrupts on the Arduino. Here is an Arduino sketch showing the problem. On my Arduino Mega 2560 I connect a normally open microswitch between ground and pin 18
#define INTERRUPT_PIN_NUMBER 18 #define INTERRUPT_NUMBER 5 volatile unsigned long counter=0; void setup() { Serial.begin(57600); pinMode(INTERRUPT_PIN_NUMBER, INPUT); digitalWrite(INTERRUPT_PIN_NUMBER, HIGH); delay(1000); attachInterrupt(INTERRUPT_NUMBER, switchISR, FALLING); } void loop() { Serial.println(counter); delay(1000); } void switchISR() { counter++; }
This code setups pin 18 (interrupt number 5) on the Mega 2560 as an input pin, and turns on the internal pull-up resistor. The function switchISR is attached to this interrupt on falling. i.e. the interrupt will fire when pin 18 is grounded, causing the variable counter to increase.
The loop() procedure just keeps outputting the value of counter so we can see it.
With no hardware debouncing , pressing the switch down once will usually cause counter to increase by about 10 or 20, due to the bouncy nature of the switch.
Debouncing switches in software is a dreadful kludge in my view. The microcontroller is still getting loaded by 20 dips into the interrupt service routine instead of just the one.
Simple hardware debouncing consists of
You turn on the Arduino and the capacitor gets charged up via the internal pull-up and the interrupt is pulled high. Press the switch and the capacitor will drain via our resistor (being much lower than the internal pullup value). Obviously the switch bouncing will cause a few delays in this draining, but generally the voltage on the input pin will fall. Any tiny rises due to bouncing on the way down will get filtered out by the Schmitt trigger built into the Arduino input.
Fiddling with the values will create different behaviour. The internal pullup resistor is between 20k and 50k which means the capacitor will take between 20 milliseconds and 50 milliseconds to recharge enough the toggle the Schmitt trigger back to high. So to be safe the component values above are only good for switching at a couple of Hz. Microswitches are usually fired in isolated instances (i.e. an end stop) and therefore these values are good.
If you are trying to count a 100kHz encoder signal… well, you should not be using an Arduino – there are far better dedicated ICs out there.
Here is a list of the interrupt pins on the Arduino Mega 2560. The pin number is the actual number printed on the header, the interrupt number is the actual number used in the attachInterrupt command parameters.
| Pin | Interrupt |
|---|---|
| 2 | 0 |
| 3 | 1 |
| 21 | 2 |
| 20 | 3 |
| 19 | 4 |
| 18 | 5 |