I want to have an interrupt function executed whenever a button is pressed.
The button is connected to pin 2
and the GND
. Therefore, the pin is turned to LOW
whenever the button is pressed. In addition to that, proper debouncing should be used
As a proof of concept, the interrupt function should just toggle the BUILTIN_LED
whenever the button is pressed.
I have tried many different approaches but i cannot make it work.
This is my last iteration:
bool led_status = LOW; // current state of output pin
int buttonState; // the current reading from the input pin
int lastButtonState = HIGH; //the previous reading from the input pin
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
int button_switch = 2; // external interrupt pin
bool initialisation_complete = false; // inhibit any interrupts until initialisation is complete
// ISR for handling interrupt triggers arising from associated button switch
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
void button_interrupt_handler()
{
//static long int elapse_timer;
if (initialisation_complete == true) //only able to run the ISR when arduino has finished initialization
{
// new interrupt so okay start a new button read process -
// now need to wait for button release plus debounce period to elapse
// this will be done in the button_read function
int reading = digitalRead(button_switch);
if ( reading != lastButtonState) // If the switch changed, due to noise or pressing:
{
lastDebounceTime = millis(); // reset the debouncing timer
}
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
if ( (millis() - lastDebounceTime) > debounceDelay)
{
if (reading != buttonState) // if the button state has changed:
{
buttonState = reading;
if (buttonState == HIGH) // only toggle the LED if the new button state is HIGH
{
led_status = !led_status;
}
}
}
digitalWrite(LED_BUILTIN, led_status); //set the LED
lastButtonState = reading; // save the reading. Next time through the loop, it'll be the lastButtonState:
}
} // end of button_interrupt_handler
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(button_switch, INPUT_PULLUP); //no res = change to INPUT_PULLUP
attachInterrupt(digitalPinToInterrupt(button_switch), button_interrupt_handler, FALLING); //no res = change to FALLING
digitalWrite(LED_BUILTIN, led_status);
initialisation_complete = true; // open interrupt processing for business
}
void loop()
{
//do nothing
}
I am not sure what I am doing wrong or why this does not work.
EDIT: When I press the button, nothing happens at all.