Example Code for Arduino-Read Button Status

Last revision 2025/12/18

This article offers a comprehensive guide on reading button status with Arduino, including hardware and software setup, wiring instructions, and sample code for detecting button actions using an RGB LED.

Hardware Preparation

Software Preparation

Wiring Diagram

Set I2C address and then connect the button module to the I2C interface of the UNO mainboard.

DFR0991-wiring diagram

Other Preparation Work

First, set the I2C address of the button module by toggling the 3-bit DIP switch A2, A1 and A0 with tweezers.

DFR0991-3-bit DIP switch

Note: The default I2C address of the button is 0x2A. The DIP switch can be set according to the address table at the bottom of the module as shown in the figure below.

DFR0991-I2C address table

Sample Code

Detect RGB button status, red on press, off on release

#include <DFRobot_RGBButton.h>
DFRobot_RGBButton RGBButton(&Wire, /*I2CAddr*/ 0x2A);//set I2C address of the button module
void setup(void)
{
  Serial.begin(115200);
  while( ! RGBButton.begin() ){        //init
    Serial.println("Communication with device failed, please check connection!!!");
    delay(3000);
  }
  Serial.println("Begin ok!\n");
}
uint8_t flag = 0;
void loop()
{
  if( RGBButton.getButtonStatus() ) {
    flag = 1;
    RGBButton.setRGBColor(RGBButton.eRed);   // LED shows red light when the button is pressed
    delay(50);
  } else if( 1 == flag ) {
    flag = 0;
    RGBButton.setRGBColor(RGBButton.eBlack);   // LED goes out when the button is released
  }
}

Result

After uploading the codes, the button RGB LED shows red when the button is pressed and goes out when released.

Was this article helpful?

TOP