Is there a way to get delay() to not affect other components timing?

Im currently making a “cyclone” sort of game with my new arduino.
Here is the code:

int buttonPin = 2;
int period = 1000;
unsigned long time_now = 0;

void setup() {
  for (int Pin = 4; Pin < 8; Pin++) {
    pinMode(Pin, OUTPUT);
    
    Serial.begin(9600);
    pinMode(buttonPin, INPUT);

  }
}

void loop() {

  for (int Pin = 4; Pin < 8; Pin++) {
    digitalWrite(Pin, HIGH);
    delay(150);
    digitalWrite(Pin, LOW);
  }

  for (int Pin = 7; Pin >= 4; Pin--) {
    digitalWrite(Pin, HIGH);
    digitalWrite(Pin, LOW);
  }
  
//  leds();
  int buttonState = digitalRead(buttonPin);
  Serial.println(buttonState);
  delay(1);
  
}

I have a button set up to print “1” (in the serial monitor) whenever its clicked. But print “0” when not clicked. But in the meantime my LEDs are also making its task. So, when I click the button whenever the LED goes on or off, it doesn’t print 1, since its like if delay() is ignoring anything else apart from the LEDs when being switched. Now when I click the button in the right time, it does print. Is there a more efficient way of making this?

Not sure what you mean by “affect”… delay is blocking your code where it is for an amount of time. That’s why it’s called delay(). (Could also have been called pleaseWaitHereWithoutDoingAnything() But that was too long to type :slight_smile: )

This code will basically lockup the processor for 600ms

for (int Pin = 4; Pin < 8; Pin++) {
    digitalWrite(Pin, HIGH);
    delay(150);
    digitalWrite(Pin, LOW);
  }

whilst this code

for (int Pin = 7; Pin >= 4; Pin--) {
    digitalWrite(Pin, HIGH); // <=== YOU WONT GET TO SEE THAT
    digitalWrite(Pin, LOW);
  }

will turn LEDs off and you won’t have the time to see them on as there is no delay.

Read the post at the top of the forum titled Using millis() for timing. A beginners guide if you want to Program in a non blocking way (or study “blink without delay”)

its like if delay() is ignoring anything else

That is the purpose of delay().

To learn a more efficient way to program, study this excellent tutorial.

The functions delay() and delayMicroseconds() block the Arduino until they complete.
Have a look at how millis() is used to manage timing without blocking in Several Things at a Time.

And see Using millis() for timing. A beginners guide if you need more explanation.

…R

Read the post at the top of the forum titled Using millis() for timing. A beginners guide if you want to Program in a non blocking way (or study “blink without delay”)

Thanks, I will read the page and see if I can get this done.