// Pin definitions
#define JOYSTICK_H A0 // Joystick horizontal axis
#define JOYSTICK_V A1 // Joystick vertical axis
#define JOYSTICK_BTN 12 // Joystick button pin
// RGB LED pins
#define RGB1_R 4
#define RGB1_G 3
#define RGB1_B 2
#define RGB2_R 7
#define RGB2_G 6
#define RGB2_B 5
#define RGB3_R 10
#define RGB3_G 9
#define RGB3_B 8
int selectedLED = 0; // Tracks the currently selected RGB LED
bool buttonPressed = false;
void setup() {
// Initialize joystick pins
pinMode(JOYSTICK_BTN, INPUT_PULLUP);
// Initialize RGB LED pins
pinMode(RGB1_R, OUTPUT);
pinMode(RGB1_G, OUTPUT);
pinMode(RGB1_B, OUTPUT);
pinMode(RGB2_R, OUTPUT);
pinMode(RGB2_G, OUTPUT);
pinMode(RGB2_B, OUTPUT);
pinMode(RGB3_R, OUTPUT);
pinMode(RGB3_G, OUTPUT);
pinMode(RGB3_B, OUTPUT);
// Start serial communication (optional for debugging)
Serial.begin(9600);
}
void loop() {
// Check if the button is pressed
if (digitalRead(JOYSTICK_BTN) == LOW) {
if (!buttonPressed) {
buttonPressed = true;
selectedLED = (selectedLED + 1) % 3; // Cycle between 0, 1, and 2
clearAllLEDs(); // Turn off all LEDs
}
} else {
buttonPressed = false;
}
// Read joystick position
int horizontal = analogRead(JOYSTICK_H);
int vertical = analogRead(JOYSTICK_V);
// Map joystick values to PWM range (0-255)
int red = map(horizontal, 0, 1023, 255, 0);
int green = map(vertical, 0, 1023, 255, 0);
int blue = map((horizontal + vertical) / 2, 0, 1023, 255, 0);
// Control the selected RGB LED
switch (selectedLED) {
case 0:
setLED(RGB1_R, RGB1_G, RGB1_B, red, green, blue);
break;
case 1:
setLED(RGB2_R, RGB2_G, RGB2_B, red, green, blue);
break;
case 2:
setLED(RGB3_R, RGB3_G, RGB3_B, red, green, blue);
break;
case 3:
setLED(RGB1_R, RGB1_G, RGB1_B, red, green, blue);
setLED(RGB2_R, RGB2_G, RGB2_B, red, green, blue);
setLED(RGB3_R, RGB3_G, RGB3_B, red, green, blue);
break;
}
delay(10); // Small delay to debounce and stabilize readings
}
// Function to set RGB LED color
void setLED(int redPin, int greenPin, int bluePin, int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}
// Function to clear all RGB LEDs
void clearAllLEDs() {
setLED(RGB1_R, RGB1_G, RGB1_B, 0, 0, 0);
setLED(RGB2_R, RGB2_G, RGB2_B, 0, 0, 0);
setLED(RGB3_R, RGB3_G, RGB3_B, 0, 0, 0);
}