Problems using while loop with buttons

I'm a new arduino user and I've found a trouble making a new project.
I'm tryna make a Formula 1 RPM lights bar. My intent was to let the LEDs light up while I press the button.
But when I press once for a really short time the button, all the LEDs turn on.
Please help me
P.S. Don't mind the pins name written in italian!

nt stato = 0;
#define ROSSO1 2
#define ROSSO2 3
#define ROSSO3 4
#define GIALLO1 9
#define GIALLO2 10
#define BTN 13
byte led[] = {ROSSO1, ROSSO2, ROSSO3, GIALLO1, GIALLO2};
void setup() {
  for (int i = 0; i < 6; i++) {
    pinMode (led[i], OUTPUT);
    digitalWrite (led, LOW);
  }

}

void loop() {
  int i = 0;
  stato = digitalRead(BTN);
  if (stato == LOW) {
    for (; stato == LOW; i++) {
      digitalWrite(led[i], HIGH);
      delay(500);
    }
  }
  if (stato == HIGH) {
    for (i = 4; stato == HIGH; i--) {
      delay(500);
      digitalWrite(led[i], LOW);
    }
  }
}

if you test for a pin state being LOW or HIGH, it will detect that state 1000s of times a sec. you can't just press the button for that short a time.

you should recognize the change in state and you may be delay just a bit to avoid a bounce

   stato = digitalRead(BTN);
    if (stato != statoLst)  {
        stato = statoLst;
        delay (20);

        // some code
    }

sorry. i see you have a 500 msec delay.

shouldn't you re-read the button before testing if it's LOW/HIGH again in your for loop?

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.