const int buttonPin = 27; // the number of the pushbutton pin const int ledPin1 = 26; // the number of the first LED pin const int ledPin2 = 0; // the number of the second LED pin const int ledPin3 = 1; // the number of the third LED pin int buttonState = 0; // variable for reading the pushbutton status int lastButtonState = 0; // variable to store the previous state of the button unsigned long lastDebounceTime = 0; // the last time the output pin was toggled unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); pinMode(ledPin3, OUTPUT); // Initialize serial communication: Serial.begin(9600); } void loop() { // read the state of the pushbutton value: int reading = digitalRead(buttonPin); // check if the button state has changed if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } // if a certain amount of time has passed since the last change if ((millis() - lastDebounceTime) > debounceDelay) { // if the button state has changed if (reading != buttonState) { buttonState = reading; // check if the button is pressed if (buttonState == HIGH) { // increment LED count static int ledCount = 0; ledCount++; // turn off all LEDs digitalWrite(ledPin1, LOW); digitalWrite(ledPin2, LOW); digitalWrite(ledPin3, LOW); // light LEDs according to button presses if (ledCount == 1) { digitalWrite(ledPin1, HIGH); Serial.println("First LED on"); } else if (ledCount == 2) { digitalWrite(ledPin2, HIGH); Serial.println("Second LED on"); } else if (ledCount == 3) { digitalWrite(ledPin3, HIGH); Serial.println("Third LED on"); } else if (ledCount >= 4) { digitalWrite(ledPin3, LOW); Serial.println("LEDs off"); // reset LED count after lighting the third LED ledCount = 0; } } } } // save the current button state for comparison in the next loop iteration lastButtonState = reading; }