#define RED_PIN 9
#define GREEN_PIN 10
#define BLUE_PIN 11
#define FADE_BUTTON 2
#define POT_PIN A0
bool fadeMode = false;
int lastButtonState = HIGH;
unsigned long prevMillisFade = 0;
const unsigned long fadeInterval = 20;
int fadeBrightness = 0;
int fadeDirection = 1;
int redVal = 255, greenVal = 0, blueVal = 0;
unsigned long prevMillisColor = 0;
const unsigned long colorInterval = 30;
int phase = 0;
const int colorStep = 5;
void setup() {
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
pinMode(FADE_BUTTON, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int currentButtonState = digitalRead(FADE_BUTTON);
if (lastButtonState == HIGH && currentButtonState == LOW) {
fadeMode = !fadeMode;
Serial.print("Mod fade: ");
Serial.println(fadeMode ? "ON" : "OFF");
delay(50);
}
lastButtonState = currentButtonState;
int potVal = analogRead(POT_PIN);
float brightnessScale = potVal / 1023.0;
if (fadeMode) {
unsigned long currentMillis = millis();
if (currentMillis - prevMillisFade >= fadeInterval) {
prevMillisFade = currentMillis;
fadeBrightness += fadeDirection;
if (fadeBrightness >= 255) {
fadeBrightness = 255;
fadeDirection = -1;
} else if (fadeBrightness <= 0) {
fadeBrightness = 0;
fadeDirection = 1;
}
redVal = greenVal = blueVal = fadeBrightness;
}
} else {
unsigned long currentMillis = millis();
if (currentMillis - prevMillisColor >= colorInterval) {
prevMillisColor = currentMillis;
switch (phase) {
case 0: greenVal += colorStep; if (greenVal >= 255) { greenVal = 255; phase = 1; } break;
case 1: redVal -= colorStep; if (redVal <= 0) { redVal = 0; phase = 2; } break;
case 2: blueVal += colorStep; if (blueVal >= 255) { blueVal = 255; phase = 3; } break;
case 3: greenVal -= colorStep; if (greenVal <= 0) { greenVal = 0; phase = 4; } break;
case 4: redVal += colorStep; if (redVal >= 255) { redVal = 255; phase = 5; } break;
case 5: blueVal -= colorStep; if (blueVal <= 0) { blueVal = 0; phase = 0; } break;
}
}
}
int outRed = redVal * brightnessScale;
int outGreen = greenVal * brightnessScale;
int outBlue = blueVal * brightnessScale;
analogWrite(RED_PIN, outRed);
analogWrite(GREEN_PIN, outGreen);
analogWrite(BLUE_PIN, outBlue);
Serial.print("Duty cycle R=");
Serial.print((outRed * 100) / 255); Serial.print("%, G=");
Serial.print((outGreen * 100) / 255); Serial.print("%, B=");
Serial.print((outBlue * 100) / 255); Serial.println("%");
delay(100);
}