int buttonPin = 12; // Button connected to pin 12
int ledPins[] = {2, 3, 4, 5, 6, 7}; // LEDs connected to pins 2, 3, 4, 5, 6, 7
int buttonState = 0;
int lastButtonState = 0;
void setup() {
pinMode(buttonPin, INPUT);
for (int i = 0; i < 6; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the button state
// Check if button was pressed (transition from LOW to HIGH)
if (buttonState == HIGH && lastButtonState == LOW) {
int ledsToLight = random(1, 7); // Choose a random number of LEDs to light (from 1 to 6)
lightRandomLeds(ledsToLight);
delay(100); // Small delay to debounce the button
}
lastButtonState = buttonState; // Save the current state for the next loop
}
void lightRandomLeds(int ledsToLight) {
// Turn off all LEDs first
for (int i = 0; i < 6; i++) {
digitalWrite(ledPins[i], LOW);
}
// Randomly select LEDs to turn on
int count = 0;
while (count < ledsToLight) {
int ledIndex = random(0, 6); // Randomly select an LED from the array
if (digitalRead(ledPins[ledIndex]) == LOW) { // Check if the LED is off
digitalWrite(ledPins[ledIndex], HIGH); // Turn it on
count++; // Increment the count of LEDs turned on
}
}
}