LED countdown when pressing button, please help

Hello

I'm trying to make a simple countdown using a momentary switch, it should work something like this:

When the switch is not pressed down, nothing happens.
When the switch is pressed a row of LEDs light up and then turn off one at a time, but if the switch is released before the end is reached, the whole thing should reset.
When the last LED is reached it changes the state of a static variable. This will be used to turn on/off an external relay.
So basically the relay should change state every time the button is pressed. I just want a sort of safety timer included, so it's necessary to hold the button down for a long time before something happens, akin to a debouncer.

My initial problem is this: the countdown goes all the way to the end even if I release the button early.

int buttonState = 0;
void setup() {
  
  pinMode(2,INPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);

}

void pressed(){
  digitalWrite(3,HIGH);
  delay(200);
  digitalWrite(4,HIGH);
  delay(200);
  digitalWrite(5,HIGH);
  delay(200);
  digitalWrite(6,HIGH);
  delay(200);
  digitalWrite(7,HIGH);
  delay(20);
  digitalWrite(7,LOW);
  delay(20);
  digitalWrite(7,HIGH);
  delay(20);
  digitalWrite(7,LOW);
  delay(20);
  digitalWrite(7,HIGH);
  delay(20);
  digitalWrite(7,LOW);
  delay(20);
  digitalWrite(7,HIGH);
  delay(20);
  
}
void released(){
  digitalWrite(3,LOW);
  digitalWrite(5,LOW);
  digitalWrite(4,LOW);
  digitalWrite(6,LOW);
  //delay(500);
  digitalWrite(7,LOW);
}

void loop() {
  static byte oldButtonState = digitalRead(2);

  byte buttonState = digitalRead(2);
  if(buttonState != oldButtonState){
    if(buttonState){
      released();
    } 
    else {
      pressed();
    }
    oldButtonState = buttonState;

  }
}

I've used part of the code from this topic, which helped a lot :slight_smile:
http://forum.arduino.cc/index.php?PHPSESSID=a4o52n8n0tssi8kjtph12ch125&topic=177392.0

Thank you
Daniel Twellmann

Scrap the delays. Take a look at BlinkWithoutDelay example.

You need to know 3 things:

  1. When you pressed the button (record millis() at the time)
  2. What the time is now (look at millis())
  3. The time difference between the two, which can be mapped to a number of LEDs to illuminate.