// Pin setup
const int joyX = A0;
const int joyY = A1;
const int joyBtn = 2;
const int redPin = 9;
const int greenPin = 10;
const int bluePin = 11;
// Colors: [R, G, B]
byte colors[][3] = {
{255, 0, 0}, // Red
{0, 255, 0}, // Green
{0, 0, 255}, // Blue
{255, 255, 0}, // Yellow
{0, 255, 255}, // Cyan
{255, 0, 255}, // Magenta
{255, 255, 255} // White
};
int colorIndex = 0;
bool ledOn = true;
void setup() {
pinMode(joyBtn, INPUT_PULLUP);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
applyColor(255); // full brightness at start
}
void loop() {
int x = analogRead(joyX);
int y = analogRead(joyY);
static bool buttonPressed = false;
// Convert Y-axis to brightness (joystick up = 0, down = 1023)
int brightness = map(y, 1023, 0, 0, 255); // inverted so up = bright
// Change color (Left/Right)
if (x < 300) {
colorIndex = (colorIndex - 1 + 7) % 7;
delay(200);
} else if (x > 700) {
colorIndex = (colorIndex + 1) % 7;
delay(200);
}
// Toggle LED On/Off with button press
if (digitalRead(joyBtn) == LOW) {
if (!buttonPressed) {
ledOn = !ledOn;
delay(200); // debounce
buttonPressed = true;
}
} else {
buttonPressed = false;
}
if (ledOn) {
applyColor(brightness);
} else {
applyColor(0);
}
delay(50); // small delay for smoother behavior
}
// Apply current color and brightness
void applyColor(int brightness) {
analogWrite(redPin, (colors[colorIndex][0] * brightness) / 255);
analogWrite(greenPin, (colors[colorIndex][1] * brightness) / 255);
analogWrite(bluePin, (colors[colorIndex][2] * brightness) / 255);
}