// One method of interrupt - Detect FALLING
// This does not allow for LONG PRESS. It generates TWO interrupts when held longer than debounce
volatile bool buttonPressed; // use "volatile" for variable INSIDE interrupt service routeine (ISR)
int buttonPin = 2; // interrupt pin INT0... also available is INT1, pin 3
int ledPin3 = 3; // red LED
int ledPin5 = 5; // white LED
int count; // a counter
void setup() {
Serial.begin(9600); // start the serial monitor for text (for this demonstration)
pinMode(ledPin3, OUTPUT);
pinMode(ledPin5, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // button is wired to ground and signal pin, pulled HIGH internally
attachInterrupt(digitalPinToInterrupt(buttonPin), buttonISR, FALLING); // PIN#, ISR, TRIGGER
// digitalPinToInterrupt(buttonPin) - use the Arduino pin number, not the ATMega328 pin number
// buttonISR - the function (also Interrupt Service Routine/Interrupt Handler) to be called
// TRIGGER - run the ISR when the pin senses RISING, FALLING, ONCHANGE
welcome(); // Send an introduction to the Serial Monitor (for this demonstration)
}
void loop() {
// calling functions
blockingCode(); // blink LED and delay
checkButton();
}
int buttonISR() { // Interrupt Service Routine called on a button press
noInterrupts(); // disable interrupts while in the ISR
buttonPressed = true; // set the flag that the button was pressed
interrupts(); // enable interrupts when leaving the ISR
}
void blockingCode() { // set both LEDs ON
digitalWrite(ledPin5, !(digitalRead(ledPin5))); // read and toggle LED pin
delay(250); // wait
}
void checkButton() {
if (buttonPressed) { // check the buttonPressed flag always
delay(150); // debounce the button press noise if the buttonPressed flag was set
buttonPressed = false; // reset buttonPressed flag to prepare for the next interrupt
digitalWrite(ledPin3, !(digitalRead(ledPin3))); // toggle LED pin
count++; // increment the counter...
Serial.print(" "); Serial.print(count); // ... show the number of button presses
}
}
void welcome() {
// a place to display instructions
Serial.print("Button Press count: 0");
}
button press toggle
continuous/blocking code