#define NUMELEMENTS(x) (sizeof(x) / sizeof(x[0]))
struct COLOR {
String name;
int red;
int green;
int blue;
};
COLOR colors[] = {
{"red", 255, 0, 0},
{"green", 0, 255, 0},
{"blue", 0, 0, 255},
{"off", 0, 0, 0},
{"yellow", 255, 255, 0},
{"cyan", 92, 255, 255},
{"magenta", 255, 0, 255},
{"aqua", 0, 255, 255}
};
byte redPin = 11;
byte greenPin = 10;
byte bluePin = 9;
String myColor;
bool found = false;
// Fade control variables
int currentRed = 0, currentGreen = 0, currentBlue = 0;
int targetRed = 0, targetGreen = 0, targetBlue = 0;
int steps = 50;
int stepCount = 0;
unsigned long lastFadeTime = 0;
unsigned long fadeInterval = 20; // ms
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(115200);
Serial.println("Ready for color input.");
}
void loop() {
// Handle serial input
if (Serial.available()) {
myColor = Serial.readStringUntil('\n');
myColor.trim(); // remove whitespace/newlines
for (uint8_t cnt = 0; cnt < NUMELEMENTS(colors); cnt++) {
if (colors[cnt].name.equalsIgnoreCase(myColor)) {
setTargetColor(colors[cnt].red, colors[cnt].green, colors[cnt].blue);
found = true;
break;
}
}
if (!found) {
Serial.println("I do not know that color");
setTargetColor(0, 0, 0); // turn off
} else {
found = false;
}
}
// Handle fading effect
fadeStep();
}
void setTargetColor(int r, int g, int b) {
targetRed = r;
targetGreen = g;
targetBlue = b;
stepCount = 0;
}
void fadeStep() {
if (stepCount >= steps) return;
unsigned long now = millis();
if (now - lastFadeTime >= fadeInterval) {
lastFadeTime = now;
stepCount++;
int r = map(stepCount, 0, steps, currentRed, targetRed);
int g = map(stepCount, 0, steps, currentGreen, targetGreen);
int b = map(stepCount, 0, steps, currentBlue, targetBlue);
analogWrite(redPin, r);
analogWrite(greenPin, g);
analogWrite(bluePin, b);
if (stepCount == steps) {
currentRed = targetRed;
currentGreen = targetGreen;
currentBlue = targetBlue;
}
}
}