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

Software Preparation

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.

DFR0991-Interrupt wiring diagram

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?

TOP