I would not recommend to use interrupts for detecting button presses, but that may just be me. When you press a button, the contact in it will cause som "bouncing" where the signal switches up and down a few times until a stable connection is made in the switch. When you debounce a button you either delay for some milliseconds (bad sollution), or you use timing with millis() to make sure that at least some milliseconds passes between each press. You cannot use delay() in an interrupt handler.
#define BUTTON_DEBOUNCE 50
unsigned long lastPress = 0;
if (millis() - lastPress > BUTTON_DEBOUNCE)
{
lastPress = millis();
//Handle button press
}
You could also use a button handler like TButton from TDuino. Then you can use code like this:
#include <TDuino.h>
#define BUTTON_PIN_1 2
#define BUTTON_PIN_2 3
#define BUTTON_DEBOUNCE 50
TButton btn1(BUTTON_PIN_1), btn2(BUTTON_PIN_2);
void buttonPress(byte pin, int state)
{
if (pin == BUTTON_PIN_1)
{
//Handle button 1
}
else
{
//Handle button 2
}
}
void setup()
{
btn1.setup();
btn1.setDebounce(BUTTON_DEBOUNCE);
btn1.onPress(buttonPress);
btn2.setup();
btn2.setDebounce(BUTTON_DEBOUNCE);
btn2.onPress(buttonPress);
}
void loop()
{
btn1.loop();
btn2.loop();
//Other non-blocking loop code here..
}
The above code would require that you do not use blocking code elsewhere in the sketch.