Example Code for Arduino-Control RGB LED Brightness
In this sample, we will learn how to control the brightness of RGB LED and the hardware connection remains. The LED color is set to blue so that we can focus on brightness changes.
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.

Sample Code
RGB button module cycles blue brightness gradient display
#include <DFRobot_RGBButton.h>
DFRobot_RGBButton RGBButton(&Wire, /*I2CAddr*/ 0x2A);
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");
RGBButton.setRGBColor(/*r=*/0, /*g=*/0, /*b=*/0);
}
uint8_t rValue = 0, gValue = 0, bValue;
void loop()
{
for(uint8_t t=0;t<255;t++)
{
RGBButton.setRGBColor(/*r=*/rValue, /*g=*/gValue, /*b=*/t);
delay(10);
}
for(uint8_t i=255;i>0;i--)
{
RGBButton.setRGBColor(/*r=*/rValue, /*g=*/gValue, /*b=*/i);
delay(10);
}
}
Result
After uploading the codes, RGB LED shows blue light, and repeatedly changes from dim to bright and back to dim.
Was this article helpful?
