const int switchPin = 13; // Connect the push button to digital pin 13
const int ledPins[] = {23, 22, 21, 4}; // Connect the LEDs to digital pins 23, 22, 21, and 4
const int numLeds = sizeof(ledPins) / sizeof(ledPins[0]); // Calculate the number of LEDs
bool buttonState = false; // variable to store the state of the push button
bool lastButtonState = false; // variable to store the previous state of the push button
int ledState = 15; // variable to store the LED pattern, starts from 15 (binary: 1111)
void setup() {
pinMode(switchPin, INPUT_PULLUP); // Enable internal pull-up resistor for the push button
for (int i = 0; i < numLeds; i++) {
pinMode(ledPins[i], OUTPUT); // Set LED pins as OUTPUTs
}
updateLeds(); // Initially update LEDs based on the initial ledState
}
void loop() {
buttonState = digitalRead(switchPin);
// Check if the button state has changed
if (buttonState != lastButtonState) {
// If the new state is LOW (pressed), decrement the LED pattern
if (buttonState == LOW) {
if (ledState > 0) {
ledState--; // Decrement the LED pattern
updateLeds(); // Update LEDs based on the new ledState
}
}
// Save the current button state for comparison in the next iteration
lastButtonState = buttonState;
// A small delay to debounce the button (optional, depending on your button)
delay(50);
}
}
// Function to update the LEDs based on the current ledState
void updateLeds() {
for (int i = 0; i < numLeds; i++) {
digitalWrite(ledPins[i], (ledState & (1 << i)) ? HIGH : LOW); // Check each bit of ledState and set corresponding LED
}
}