Example Code for Arduino-Interrupt
Last revision 2026/02/05
This article showcases example code for using interrupts with Arduino, specifically focusing on the FireBeetle 2 ESP32-E board, including hardware setup and interrupt mode explanations.
Hardware Preparation
- FireBeetle 2 ESP32-E (SKU: DFR0654) ×1
- USB Data Cable ×1
Other Preparation Work
All GPIO pins broken out from the FireBeetle 2 ESP32-E development board, except those that are already occupied or have specific functions, can be used as external interrupt pins.
Enable external interrupt(attachInterrupt(pin,function,mode)), the parameters are as follows:
-
pin: the external interrupt pin;
-
function: the callback function for the external interrupt;
-
mode: 5 external interrupt modes.
-
As shown in the table below:
| Interrupt Trigger Mode | Description |
|---|---|
| RISING | Trigger on rising edge |
| FALLING | Trigger on falling edge |
| CHANGE | Trigger on any level change |
| ONLOW | Trigger on low |
| ONHIGH | Trigger on high |
Disable pin interrupt detchInterrupt(pin), no value is returned.
Sample Code
Program function: when the button is pressed, the interrupt is triggered and the serial prints the number of times the button has been pressed.
#include <Arduino.h>
struct Button { //Define the button struct
const uint8_t PIN; //Define button pin
uint32_t numberKeyPresses; //Define the number of times the button is pressed.
bool pressed; //Determine if the button is pressed, return true if it's pressed
};
Button button = {27, 0, false}; //Instantiated a button, and use the on-board button.
void ARDUINO_ISR_ATTR isr() { //Interrupt processing function
button.pressed = true;
}
void setup() {
Serial.begin(115200);
pinMode(button.PIN, INPUT_PULLUP);
attachInterrupt(button.PIN, isr, FALLING); //Register the interrupt function, and set the trigger mode to FALLING
}
void loop() {
if (button.pressed) {
button.pressed = false;
delay(50);
if(digitalRead(button.PIN)==LOW){
button.numberKeyPresses += 1;
Serial.printf("Button has been pressed %u times\n", button.numberKeyPresses); //Press the button, and print the total number of times the button has been pressed.
}
}
}
Result
When the program is successfully uploaded, press the on-board button once, the serial port will print a message. The number accumulates every time your press the button, as shown in the figure below.

Was this article helpful?
