#define colorBtn 6
#define durationBtn 7
#define RED_PIN 13
#define GREEN_PIN 12
#define BLUE_PIN 11
// RGB logic levels for specified colors (excluding black/off from cycle)
bool colors[][3] = {
{1, 1, 1}, // White
{1, 0, 0}, // Red
{0, 1, 0}, // Green
{0, 0, 1}, // Blue
{0, 1, 1}, // Cyan
{1, 1, 0}, // Yellow
{1, 0, 1} // Magenta
};
const char* colorNames[] = {
"white", "red", "green", "blue", "cyan", "yellow", "magenta"
};
const int totalColors = 7;
int delays[] = {1000, 800, 600, 400, 200};
const int totalDelays = 5;
// State tracking variables
volatile int currentColorIdx = 0;
volatile int currentDelayIdx = 0;
volatile bool colorChanged = false;
volatile bool durationChanged = false;
volatile unsigned long lastColorInterruptTime = 0;
volatile unsigned long lastDurationInterruptTime = 0;
const unsigned long debounceDelay = 200; // Debounce threshold in ms
unsigned long previousMillis = 0;
bool ledState = false;
// Interrupt Service Routines (ISRs)
void ISR_colorBtn() {
unsigned long currentTime = millis();
if (currentTime - lastColorInterruptTime > debounceDelay) {
currentColorIdx = (currentColorIdx + 1) % totalColors;
colorChanged = true;
lastColorInterruptTime = currentTime;
}
}
void ISR_durationBtn() {
unsigned long currentTime = millis();
if (currentTime - lastDurationInterruptTime > debounceDelay) {
currentDelayIdx = (currentDelayIdx + 1) % totalDelays;
durationChanged = true;
lastDurationInterruptTime = currentTime;
}
}
void setup() {
Serial.begin(9600);
// Configure RGB 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);
// Attach Hardware Interrupts (Triggered when button is pressed/falling to GND)
attachInterrupt(digitalPinToInterrupt(colorBtn), ISR_colorBtn, FALLING);
attachInterrupt(digitalPinToInterrupt(durationBtn), ISR_durationBtn, FALLING);
}
void loop() {
// Handle serial prints outside ISRs
if (colorChanged) {
colorChanged = false;
Serial.print("Color: ");
Serial.println(colorNames[currentColorIdx]);
}
if (durationChanged) {
durationChanged = false;
Serial.print("Duration: ");
Serial.print(delays[currentDelayIdx]);
Serial.println(" ms");
}
// Non-blocking RGB blinking mechanism
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= delays[currentDelayIdx]) {
previousMillis = currentMillis;
ledState = !ledState;
if (ledState) {
digitalWrite(RED_PIN, colors[currentColorIdx][0]);
digitalWrite(GREEN_PIN, colors[currentColorIdx][1]);
digitalWrite(BLUE_PIN, colors[currentColorIdx][2]);
} else {
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);
}
}
}