0
const int buttonPin = 1; // the pin number of the pushbutton input pin
const int ledPins[] = {2, 3, 4, 5, 10, 11, 12, 13}; // variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int buttonPressCount = 0;
int numberOfLED = 8;
void setup() { // initialize the LED pin as an output:
 for (int i = 0; i < numberOfLED; i++) {
 pinMode(ledPins[i], OUTPUT);
 } 
 pinMode(buttonPin, INPUT);
}
void loop() { // read the state of the pushbutton value:
 buttonState = digitalRead(buttonPin); // check if the pushbutton is pressed. // if it is, the buttonState is HIGH:
 if (buttonState == HIGH) {
 for (int i = 0; i < numberOfLED; i++) {
 if (buttonPressCount % numberOfLED == i)
 digitalWrite(ledPins[i], HIGH); // turn LED on
 else
 digitalWrite(ledPins[i], LOW); // turn LED off
 }
 } 
 buttonPressCount++; 
 delay(300);
}
csg
1411 gold badge1 silver badge6 bronze badges
asked Nov 7, 2018 at 6:27
0

1 Answer 1

2

instead of changing every time the buttonState == HIGH, change it when the button state was LOW the previous time but HIGH now:

buttonState = digitalRead(buttonPin);
if (oldButtonState != buttonState && buttonState == HIGH) {
 //...
}
oldButtonState = buttonState;

However keep in mind contact bounce. Which can result in multiple transitions being detected. Most solutions for that set a minimal delay between handling transitions, dropping all others detected.

answered Nov 7, 2018 at 10:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.