// Define pin connections
const int redPin = 10; // Pin for Red LED
const int greenPin = 9; // Pin for Green LED
const int bluePin = 6; // Pin for Blue LED
const int buttonPin = 12; // Pin for the button
// Variables for button state and LED colors
int buttonState = 0; // Current state of the button
int lastButtonState = 0; // Previous state of the button
unsigned long lastDebounceTime = 0; // Last time the output pin was toggled
unsigned long debounceDelay = 50; // Debounce time in milliseconds
// RGB color variables
int redValue = 0;
int greenValue = 0;
int blueValue = 0;
void setup() {
// Initialize LED pins as OUTPUT
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
// Initialize button pin as INPUT
pinMode(buttonPin, INPUT_PULLUP); // Using internal pull-up resistor
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Read the button state
int reading = digitalRead(buttonPin);
// Check for button press
if (reading != lastButtonState) {
lastDebounceTime = millis(); // Reset the debounce timer
}
// If the button state has been stable for longer than the debounce delay
if ((millis() - lastDebounceTime) > debounceDelay) {
// Check if the button was pressed (LOW means pressed due to pull-up)
if (reading == LOW) {
// Change RGB color on button press
changeColor();
Serial.print("Button pressed: ");
Serial.print("R: "); Serial.print(redValue);
Serial.print(" G: "); Serial.print(greenValue);
Serial.print(" B: "); Serial.println(blueValue);
}
}
lastButtonState = reading; // Save the reading as the last state for next loop
}
// Function to change RGB color
void changeColor() {
// Simple color cycling logic
if (redValue == 0 && greenValue == 0 && blueValue == 0) {
redValue = 255; // Red
} else if (redValue == 255) {
redValue = 0;
greenValue = 255; // Green
} else if (greenValue == 255) {
greenValue = 0;
blueValue = 255; // Blue
} else if (blueValue == 255) {
blueValue = 0;
}
// Update the LED colors
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}