// Pin definitions
const int buttonPin = 2; // Push button pin (using internal pull-up)
const int ledPins[] = {3, 4, 5}; // LED pins (3 LEDs)
const int numLeds = 3; // Number of LEDs
// Variables
int counter = 0; // Tracks button presses
int lastButtonState = HIGH; // For button debouncing
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
// Set up LEDs as outputs
for (int i = 0; i < numLeds; i++) {
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], LOW);
}
// Set up button with internal pull-up resistor
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
int reading = digitalRead(buttonPin);
// Debounce logic
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button state has changed:
if (reading == LOW && lastButtonState == HIGH) {
// Button pressed (LOW because of pull-up)
counter++;
// Reset counter if exceeds number of LEDs
if (counter > numLeds) {
counter = 0;
}
// Update LEDs based on counter
updateLeds();
}
}
lastButtonState = reading;
}
void updateLeds() {
// Turn off all LEDs first
for (int i = 0; i < numLeds; i++) {
digitalWrite(ledPins[i], LOW);
}
// Turn on LEDs up to the current counter value
for (int i = 0; i < counter; i++) {
digitalWrite(ledPins[i], HIGH);
}
}