Sub topic 4
The cost of delay()
This chapter explains what delay() does inside the processor, why that makes a sketch unresponsive, and how to recognize the problem in your own code. It assumes you can write a basic sketch with setup() and loop(), use pinMode(), digitalRead() and digitalWrite(), wire a pushbutton and an LED, and read if statements, booleans and integer types in C++. The next chapter introduces millis(), the tool that replaces delay() in most sketches.
What delay() actually does
delay(ms) pauses your sketch for ms milliseconds. On AVR boards such as the Uno, the core implements it as a loop that watches the microsecond counter. It keeps checking the time until enough has passed, then returns. While it runs, the processor executes only that wait loop.
This is called blocking. A blocking call holds the CPU inside one function until the function finishes. Nothing after the call in your loop() runs until it returns. Nothing before it runs again either.
The simplest example is the classic blink:
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}This works well because the sketch has only one job. The trouble starts when you add a second job.
A sketch that misses button presses
Add a button that should toggle a second LED. The button connects pin 2 to GND, and INPUT_PULLUP keeps the pin HIGH when the button is released, so a press reads LOW.
const uint8_t BUTTON_PIN = 2;
const uint8_t LED_PIN = 8;
bool ledOn = false;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
// Task 1: blink the built-in LED
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
// Task 2: check the button
if (digitalRead(BUTTON_PIN) == LOW) {
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn);
}
}Upload this and press the button. Most presses do nothing. A press registers only if you happen to hold the button down at the moment the sketch reaches the digitalRead() line. That line runs once every 1000 ms, and a typical press lasts 50 to 150 ms. Your chance of catching a press is roughly 5 to 15 percent.
The sketch is not broken in the sense of containing a syntax error or a bad pin number. The structure is the problem. The processor spends about 99.9 percent of its time inside delay() and checks the button for a few microseconds per second.
The timeline
The diagram shows one pass through loop() and where the button gets read.
Any press that begins and ends inside one of the two wait boxes is lost. The processor is awake and powered, but it is not looking at the pin.
Why this is not just a button problem
A button is the easiest way to notice blocking, but the same flaw affects every input and every output that needs attention on a schedule.
- A serial command arrives during a
delay(). The bytes wait in the receive buffer, which holds 64 bytes on an Uno. A long enough delay lets it overflow, and data is lost. - A sensor needs sampling every 10 ms, but another part of the sketch calls
delay(200). You collect samples at 5 Hz instead of 100 Hz. - A motor or servo needs a position update at a regular rate. A long delay makes it stutter or freeze.
- An emergency stop input needs a reaction within a few milliseconds. A 1 second delay means a 1 second worst-case reaction time.
The general rule: a sketch that calls delay(N) has a worst-case response time of at least N milliseconds for every other task in the program.
Delay arithmetic: adding delays together
Delays accumulate. If loop() contains several, the worst-case latency is their sum, plus the time the other code takes.
| Delays in loop() | Total blocked time per pass | Approximate worst-case response |
|---|---|---|
| `delay(500)` once | 500 ms | 500 ms |
| `delay(500)` twice | 1000 ms | 1000 ms |
| `delay(10)` plus `delay(1000)` | 1010 ms | 1010 ms |
| `delay(20)` once | 20 ms | 20 ms |
A short delay is not always harmful. A 20 ms pause in a sketch that has nothing time-critical is fine. The question to ask is whether any other task in the program is allowed to wait that long.
Two tempting workarounds that do not work
Shortening the delay
You can reduce the delay to 50 ms and read the button more often. This improves the odds of catching a press, but it changes the blink rate, so you would need to count passes to rebuild a 500 ms blink. You end up writing your own timer on top of delay(). It also still blocks for 50 ms on every pass, and any additional task makes the same compromise again.
Reading the button inside the delay
Another idea is to read the button several times between small delays:
for (int i = 0; i < 50; i++) {
if (digitalRead(2) == LOW) { /* handle press */ }
delay(10);
}This works for one button and one blink pattern. Each new feature must be pushed into the same loop and kept in step with the others. The code becomes harder to change, and the timing of each task depends on the delays of every other task. This is the pattern that non-blocking timing replaces.
What delay() does not block
delay() does not stop everything on the chip. Hardware peripherals and interrupts keep working.
- Timer-driven PWM from
analogWrite()continues. An LED dimmed with PWM keeps its brightness during a delay, because the timer hardware generates the waveform without CPU help. - Interrupts still fire. A function attached with
attachInterrupt()runs even whiledelay()waits, and the delay resumes afterward. millis()keeps counting. The timer interrupt behind it continues to run, which is the fact the next chapter builds on.- Serial reception on AVR is handled by an interrupt, so incoming bytes are stored in the buffer. Your code just does not read them until the delay ends.
Interrupts running during a delay is why one chapter later in this tutorial can show an interrupt-based button handler that works alongside blocking code. It has its own pitfalls, which that chapter covers.
delayMicroseconds() and the same principle
delayMicroseconds(us) blocks in the same way, for a shorter time. It is reasonable for very short waits, such as the setup timing some sensors require, where the pause is only a few microseconds. Beyond a few milliseconds, prefer delay() or, better, non-blocking timing. Accuracy is poor above about 16383 µs on AVR, so the documentation recommends delay() for longer waits.
When delay() is acceptable
Blocking is a cost, not a prohibition. Use delay() when:
- The sketch does exactly one thing, such as a first blink test or a demonstration.
- The pause happens in
setup(), for example waiting 100 ms for a sensor to power up before the sketch starts responding to anything. - The delay is short compared with the response time anything else needs, and you have checked that this is true.
- The pause is a deliberate stop, such as a shutdown routine that has no other work to do.
Avoid delay() in loop() when any other input, output or timer must respond while it waits.
How to spot blocking in existing code
Look for these signs when a sketch feels sluggish or drops events:
- Any
delay()call longer than a few milliseconds insideloop()or inside functions thatloop()calls. whileloops that wait for a pin to change, such aswhile (digitalRead(pin) == HIGH) {}. These block just asdelay()does and can freeze the sketch forever if the pin never changes.- Calls to library functions that wait, such as
pulseIn()with a long timeout, or sensor libraries that sleep until a reading is ready. - Serial calls that wait, such as
Serial.readString(), which waits up to the timeout (1000 ms by default) for data.
A quick way to measure the problem is to print how long each pass of loop() takes:
unsigned long lastPass = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long now = micros();
Serial.println(now - lastPass);
lastPass = now;
delay(100); // try removing this line and compare the output
}With the delay, each pass takes just over 100000 µs, and the sketch can look at its inputs only 10 times per second. Without it, passes take far less, limited mainly by the serial printing, and the sketch can check inputs many times more often. Short pass times are the goal of the non-blocking style.
The idea that replaces delay()
The fix is to change the question the sketch asks. Blocking code says, "wait 500 ms, then continue." Non-blocking code says, "has 500 ms passed yet? If not, move on and ask again on the next pass."
For that, loop() has to run fast, hundreds or thousands of times per second, and each pass must do only a small amount of work. A running clock is then enough to schedule actions. That clock is millis(), and the sketch stores the time of each event instead of pausing for it. The next chapters build this up in steps.
Common mistakes
- Putting a delay in every function "to be safe." Small waits add up across helper functions called in one pass.
- Using delay() as a debounce. A
delay(50)after a press hides bounce, but it blocks everything else for 50 ms on every press and still misreads long holds. A later chapter shows the replacement. - Assuming a fast processor means no problem. A 16 MHz chip executes millions of instructions per second, and
delay()wastes all of them. Speed does not help when the code chooses to wait. - Testing with only one task. A sketch with one blink and no input always looks fine. Test with the full set of inputs active.
Exercise
A sketch blinks an LED with delay(300) on and delay(300) off, then reads a button once at the end of loop(). The button press lasts 100 ms and is equally likely to start at any moment. What is the maximum fraction of presses the sketch can catch, and why is it unreliable? What single change in approach fixes it?
Show answer
The loop takes about 600 ms, and the button is read only once per pass, for a few microseconds. A press is caught only if it is still active at that instant. A 100 ms press overlaps the read moment in about 100/600, or roughly 17 percent, of cases at best. The sketch is unreliable because delay() blocks the processor, so the input is not checked during the waits. The fix is to stop blocking: track the blink with a timestamp from millis() and run loop() fast so the button is read thousands of times per second.
Exercise
Name two things that keep working while delay() is waiting on an AVR board, and one thing that does not.
Show answer
Timer-based PWM output from analogWrite() and interrupt handlers (also the millis() counter and serial reception into the buffer) keep working. Your own loop() code does not: it cannot read inputs, update outputs, or run any other logic until the delay returns.