#define colorBtn 6
#define durationBtn 7
// LED Pins
#define RED_PIN 13
#define GREEN_PIN 12
#define BLUE_PIN 11
bool colors[][3] = {
{1,1,1} , {1,0,0},{0,1,0},{0,0,1}, // wrgb
{0,1,1} , {1,1,0},{1,0,1},{0,0,0} // cymk
};
char* colorNames[] = {
"white","red","green","blue",
"cyan","yellow","megenta","black" // black is off, cycle limit will skip index 7
};
int delays[] = {
1000, 800, 600, 400, 200
};
// Array limits
const int totalColors = 7; // Excludes "black" (index 7) from cycling
const int totalDelays = sizeof(delays) / sizeof(delays[0]);
// State variables
int colorIdx = 0; // Initial: "white"
int delayIdx = 0; // Initial: 1000 ms
unsigned long lastBlinkTime = 0;
bool ledState = false;
// Edge detection variables
bool lastColorBtnState = HIGH;
bool lastDurationBtnState = HIGH;
void setup() {
Serial.begin(115200);
// Configure LED pins
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
// Configure Button pins with internal pull-up resistors
pinMode(colorBtn, INPUT_PULLUP);
pinMode(durationBtn, INPUT_PULLUP);
// Display initial settings
Serial.println("RGB LED Controller Initialized");
Serial.print("Initial Color: ");
Serial.println(colorNames[colorIdx]);
Serial.print("Initial Duration: ");
Serial.print(delays[delayIdx]);
Serial.println(" ms");
}
void loop() {
unsigned long currentMillis = millis();
// --- 1. Read Button Inputs (Active LOW with INPUT_PULLUP) ---
bool colorBtnState = digitalRead(colorBtn);
bool durationBtnState = digitalRead(durationBtn);
// Handle Color Button press (Falling Edge)
if (colorBtnState == LOW && lastColorBtnState == HIGH) {
colorIdx = (colorIdx + 1) % totalColors; // Cycle through indices 0 to 6
Serial.print("Color changed to: ");
Serial.println(colorNames[colorIdx]);
delay(150); // Software debounce
}
lastColorBtnState = colorBtnState;
// Handle Duration Button press (Falling Edge)
if (durationBtnState == LOW && lastDurationBtnState == HIGH) {
delayIdx = (delayIdx + 1) % totalDelays; // Cycle through available delay speeds
Serial.print("Duration changed to: ");
Serial.print(delays[delayIdx]);
Serial.println(" ms");
delay(150); // Software debounce
}
lastDurationBtnState = durationBtnState;
// --- 2. Non-blocking Blinking Logic ---
if (currentMillis - lastBlinkTime >= delays[delayIdx]) {
lastBlinkTime = currentMillis;
ledState = !ledState;
if (ledState) {
digitalWrite(RED_PIN, colors[colorIdx][0] ? HIGH : LOW);
digitalWrite(GREEN_PIN, colors[colorIdx][1] ? HIGH : LOW);
digitalWrite(BLUE_PIN, colors[colorIdx][2] ? HIGH : LOW);
} else {
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);
}
}
}