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);
}
1 Answer 1
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