Example Code for Arduino-Interrupt Function
Last revision 2025/12/18
The article provides example code for utilizing Arduino's interrupt function with a button module as an I2C slave, focusing on the interactive communication mode enabled by the INT pin.
Hardware Preparation
- DFRduino UNO R3 (SKU: DFR0216) × 1
- Gravity: IO Expansion Shield for Arduino V7.1 (SKU: DFR0216) × 1
- Gravity: Digital Blue LED Light Module (SKU: DFR0021-B) × 1
- Gravity: I2C RGB LED Button Module (SKU: DFR0991) × 1
- Gravity-4P I2C/UART Sensor Cable(DFR0991 is equipped with one of these lines) × 1
- Gravity-3P Cable × 1
- USB Cable × 1
- Dupont Wires
Software Preparation
- Download Arduino IDE: Click to download Arduino IDE
- Download and install the DFRobot_RGBButton-main Library
- For Arduino IDE V1.8.19 (or earlier), install the library manually: How to Add a Library ?
- For Arduino IDE V2.0.0 (or later), directly search for the "DFRobot_RGBButton-main Library" in the Library Manager and install it.
Wiring Diagram
Interrupt 0 of the UNO mainboard is used in this sample. Connect the INT pin of the button module to the digital pin 2 of the UNO board, the LED to digital pin 8, and the button to the I2C interface.

Sample Code
External interrupt controls RGB button LED: press blue/on, release green/off
#include <DFRobot_RGBButton.h>
DFRobot_RGBButton RGBButton(&Wire, /*I2CAddr*/ 0x2A);
int LEDPin = 8;
volatile uint8_t flag = 0, temp = 0;
void interrupt()
{ if(3 != flag){
temp = flag;
flag = 3;
}else{
flag = temp;
temp = 4; }}
void setup(void)
{ Serial.begin(115200);
while( ! RGBButton.begin() ){
Serial.println("Communication with device failed, please check connection!");
delay(3000); }
Serial.println("Begin ok!\n");
attachInterrupt(/*Interrupt No*/0, interrupt, CHANGE); // Open the external interrupt 0, connect INT to the digital pin of the main control:
RGBButton.setRGBColor(RGBButton.eGreen);
pinMode(LEDPin, OUTPUT); }
void loop()
{ if (3 == flag) { // When the button is pressed, an interrupt occurs, set RGB LED to blue
RGBButton.setRGBColor(RGBButton.eBlue);
digitalWrite(LEDPin,HIGH); }
if (4 == temp) { // When the button is released, an interrupt occurs, change back to the color before it was pressed
temp = 0;
RGBButton.setRGBColor(RGBButton.eGreen);
digitalWrite(LEDPin,LOW); }
}
Result
After uploading the codes, the RGB LED on the button module turns on in green by default. When the button is pressed, it changes to blue and an interrupt occurs, and this time the external blue LED lights up. When the button released, the button RGB LED turns back to green, and the blue LED goes off.
Was this article helpful?
