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
- DFRduino UNO R3 (SKU: DFR0216) × 1
- Gravity: IO Expansion Shield for Arduino V7.1 (SKU: DFR0216) × 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
- USB Cable × 1
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
Set I2C address and then connect the button module to the I2C interface of the UNO mainboard.

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.

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.

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?
