Example Code for Arduino-Control Breathing Light

Last revision 2025/12/18

This article introduces an Arduino project that combines reading button status and controlling an RGB LED to create a breathing light effect, offering practical learning for electronics enthusiasts.

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

Sample Code

RGB button red on press, gradient color by sine rule on release

#include <DFRobot_RGBButton.h>
DFRobot_RGBButton RGBButton(&Wire, /*I2CAddr*/ 0x2A);//set I2C address of the button module

void setup() {
   Serial.begin(115200);
   while( ! RGBButton.begin() ){       //init
   Serial.println("Communication with device failed, please check connection!");
   delay(3000);
  }
  Serial.println("Begin ok!\n");
}

int t = 0;   // basic variation factor of RGB values
uint8_t rValue = 0, gValue = 0, bValue = 0;

void loop() {
 if( RGBButton.getButtonStatus() ) {
    RGBButton.setRGBColor(RGBButton.eRed);
    delay(100);
  } else {
    rValue = (abs(sin(3.14 * t / 180))) * 255;
    gValue = (abs(sin(3.14 * (t + 60) / 180))) * 255;
    bValue = (abs(sin(3.14 * (t + 120) / 180))) * 255;
    t += 1;
    RGBButton.setRGBColor(/*r=*/rValue, /*g=*/gValue, /*b=*/bValue);//set pulse width value of red, green and blue LEDs
    delay(100);
  }
}

Result

After uploading the codes, RGB LED presents a breathing lighting effect; it turns red when the button is pressed and back to the color of the breathing light when released.

Was this article helpful?

TOP