Immediately change a status with a button

Hello.

I am trying to make an up pair counter and an odd down counter. It changes from pair to odd with a button but does the complete loop. I need it when I press the button to change from pair to odd immediately. The code is as follows.

int A=8;
int B=9;
int C=10;
int D=11;

int pulsador=12;
int estado=0;

void setup() {
  pinMode(A,OUTPUT);
  pinMode(B,OUTPUT);
  pinMode(C,OUTPUT);
  pinMode(D,OUTPUT);
}

void loop() {
  estado = digitalRead(pulsador);
  if (estado == 0){

    // 0
    digitalWrite(A,0);
    digitalWrite(B,0);
    digitalWrite(C,0);
    digitalWrite(D,0);
    delay(500);

    // 2
    digitalWrite(A,0);
    digitalWrite(B,1);
    digitalWrite(C,0);
    digitalWrite(D,0);
    delay(500);

    // 4
    digitalWrite(A,0);
    digitalWrite(B,0);
    digitalWrite(C,1);
    digitalWrite(D,0);
    delay(500);

    // 6
    digitalWrite(A,0);
    digitalWrite(B,1);
    digitalWrite(C,1);
    digitalWrite(D,0);
    delay(500);

    // 8
    digitalWrite(A,0);
    digitalWrite(B,0);
    digitalWrite(C,0);
    digitalWrite(D,1);
    delay(500);
  }
    else {
    // 9
    digitalWrite(A,1);
    digitalWrite(B,0);
    digitalWrite(C,0);
    digitalWrite(D,1);
    delay(500);

    // 7
    digitalWrite(A,1);
    digitalWrite(B,1);
    digitalWrite(C,1);
    digitalWrite(D,0);
    delay(500);

    // 5
    digitalWrite(A,1);
    digitalWrite(B,0);
    digitalWrite(C,1);
    digitalWrite(D,0);
    delay(500);

    // 3
    digitalWrite(A,1);
    digitalWrite(B,1);
    digitalWrite(C,0);
    digitalWrite(D,0);
    delay(500);

    // 1
    digitalWrite(A,1);
    digitalWrite(B,0);
    digitalWrite(C,0);
    digitalWrite(D,0);
    delay(500);
    }
}

Then you have to stop using delay() :wink:

Let the loop() loop as fast as possible. That's the only way you can react directly on a button press.

You need to change it to a state machine and time it with milis() (see Blink without delay).

sergiomelec:
Hello.

I am trying to make an up pair counter and an odd down counter. It changes from pair to odd with a button but does the complete loop. I need it when I press the button to change from pair to odd immediately. The code is as follows.

Your code is like you did it:

"delay(500);" ist BLOCKING THE EXECUTION OF THE PROGRAM!

Your code contains several lines of "delay(500);" so you are blocking the program execution all the time.

That's NOT a very efficient way to use a microcontroller for blocking program execution all the time.

You better learn to program WITHOUT delay() for writing efficient programs.

The demo Several Things at a Time illustrates the use of millis() to manage timing without blocking.

...R