// Define pin numbers for buttons and LEDs
const int buttonPins[6] = {2, 3, 4, 5, 6, 7};
const int ledPins[6] = {8, 9, 10, 11, 12, 13};
// Variables to store the last button state and debounce timing
bool lastButtonState[6] = {true, true, true, true, true, true}; // Default HIGH for INPUT_PULLUP
bool ledState[6] = {false, false, false, false, false, false}; // LED off initially
unsigned long lastDebounceTime[6] = {0, 0, 0, 0, 0, 0}; // Time for debouncing
unsigned long debounceDelay = 50; // Debounce delay time in milliseconds
// Variable to track the index of the currently ON LED
int currentLed = -1; // -1 means no LED is currently on
void setup() {
// Set button pins as input with internal pull-up resistors
for (int i = 0; i < 6; i++) {
pinMode(buttonPins[i], INPUT_PULLUP); // Use internal pull-up resistors
pinMode(ledPins[i], OUTPUT); // Set LED pins as output
}
}
void loop() {
// Loop through all buttons
for (int i = 0; i < 6; i++) {
int reading = digitalRead(buttonPins[i]); // Read button state
unsigned long currentTime = millis(); // Get current time for debouncing
// Check if the button state has changed (debouncing)
if (reading != lastButtonState[i]) {
lastDebounceTime[i] = currentTime; // Reset debounce timer
}
// Only change the LED state if the button has been stable for the debounce period
if ((currentTime - lastDebounceTime[i]) > debounceDelay) {
// If the button is pressed (LOW for INPUT_PULLUP), and it's not already ON
if (reading == LOW && currentLed != i) {
// Turn off the previous LED if any
if (currentLed != -1) {
digitalWrite(ledPins[currentLed], LOW); // Turn off the previous LED
}
// Turn on the current LED
digitalWrite(ledPins[i], HIGH);
currentLed = i; // Update the index of the currently ON LED
}
}
// Save the current reading as the last button state for debouncing
lastButtonState[i] = reading;
}
}