// Define pins for LEDs and buttons
int ledPins[] = {2, 3, 4, 5, 6};
int buttonPins[] = {7, 8, 9, 10, 11};
// Initialize variables for storing LED states and button states
int ledStates[] = {LOW, LOW, LOW, LOW, LOW};
int buttonStates[] = {LOW, LOW, LOW, LOW, LOW};
// Function to generate random LED index
int randomLED() {
return random(0, 5);
}
// Function to turn on specified LED
void turnOnLED(int index) {
digitalWrite(ledPins[index], HIGH);
ledStates[index] = HIGH;
}
// Function to turn off specified LED
void turnOffLED(int index) {
digitalWrite(ledPins[index], LOW);
ledStates[index] = LOW;
}
// Function to check button states and toggle LEDs accordingly
void checkButtons() {
for (int i = 0; i < 5; i++) {
// Read button state
buttonStates[i] = digitalRead(buttonPins[i]);
// If button is pressed, toggle corresponding LED
if (buttonStates[i] == HIGH) {
if (ledStates[i] == LOW) {
turnOnLED(i);
} else {
turnOffLED(i);
}
}
}
}
void setup() {
// Set random seed
randomSeed(analogRead(0));
// Set LED pins as outputs
for (int i = 0; i < 5; i++) {
pinMode(ledPins[i], OUTPUT);
}
// Set button pins as inputs
for (int i = 0; i < 5; i++) {
pinMode(buttonPins[i], INPUT);
}
}
void loop() {
// Generate random LED index
int index = randomLED();
// Turn on random LED
turnOnLED(index);
// Check button states and toggle LEDs accordingly
checkButtons();
// Delay for 500 milliseconds
delay(500);
// Turn off random LED
turnOffLED(index);
// Check button states and toggle LEDs accordingly
checkButtons();
// Delay for 500 milliseconds
delay(500);
}