Sub topic 5
Making the blink visible with delay()
This chapter covers delay(), the simplest way to control timing in an Arduino sketch. It explains why a blink needs a pause, what the function does inside the board, and where it stops being a good idea.
It assumes you have read the earlier chapters. You should know that a sketch has setup() and loop(), that pinMode() and digitalWrite() control a pin, and that you can upload a sketch to your board. You should also be comfortable with unsigned long and other integer types in C++.
Why a blink needs a pause
Consider a loop that turns an LED on and then immediately off:
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(LED_BUILTIN, LOW);
}This sketch compiles and uploads without errors, but the LED looks dim and steady instead of blinking. A typical 16 MHz board such as the Uno executes loop() many thousands of times per second. Each pass switches the pin on for a few microseconds and off for a few microseconds. Your eye cannot follow changes that fast. It averages them, so you see a constant, reduced brightness.
To see a blink, each state must last long enough for a person to notice it. The usual rule is that changes slower than about 20 to 30 times per second look like separate events. A half-second or one-second interval is comfortable.
What delay() does
delay(ms) pauses the sketch for ms milliseconds. A millisecond is one thousandth of a second, so delay(1000) waits one second.
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // LED on
delay(1000); // wait one second
digitalWrite(LED_BUILTIN, LOW); // LED off
delay(1000); // wait one second
}Each pass through loop() now takes about two seconds: one second with the LED on and one with it off. The pin keeps its last state while the board waits. digitalWrite() sets the pin and the pin holds that level until something changes it, so the LED stays lit for the whole first delay.
The argument type is unsigned long. Passing a negative number is a common mistake. It is converted to a very large unsigned value, so the board appears to hang for weeks. On AVR boards, an int literal such as delay(40000) also overflows a 16-bit int in intermediate arithmetic, for example delay(60 * 1000). Write delay(60UL * 1000UL) to be safe.
Timing at a glance
The on-time and off-time are independent. Changing one value changes the pattern without affecting the other.
| On time (ms) | Off time (ms) | Visible result |
|---|---|---|
| 1000 | 1000 | Slow, even blink, 0.5 Hz |
| 500 | 500 | Even blink, 1 Hz |
| 100 | 900 | Short flash once per second |
| 900 | 100 | Mostly lit, brief dark gap |
| 10 | 10 | Looks steadily lit at reduced brightness |
The last row shows the same effect as the loop without delays. A 10 ms on, 10 ms off cycle is 50 Hz, which most people cannot resolve as flicker.
The blink frequency is one divided by the full period. With 500 ms on and 500 ms off, the period is 1000 ms, so the frequency is 1 Hz.
How the wait works internally
On most Arduino cores, delay() is a loop that reads a running millisecond counter, the same counter that millis() returns. It keeps checking until the requested time has passed. The processor is busy during that time. It is not asleep, and it is not free to run your other code.
This explains several properties:
- The timing is accurate to about a millisecond, but not exact. The board's clock comes from a crystal or resonator. A resonator, as on many clone boards, can drift by around 0.5% or more.
- Interrupts still run during
delay(). The counter that tracks time depends on a timer interrupt, so time keeps advancing. Serial data arriving in the hardware buffer is still received, up to the buffer size. - Your own code does not run. Nothing after the
delay()call executes until it returns. - The total period is slightly longer than the sum of the delays. The calls to
digitalWrite()and the loop jump take a few microseconds each time.
Choosing the interval
Pick intervals by what you want to see, not by what is easy to type. A few guidelines:
- Start with 1000 ms while testing. A slow blink is easy to count, so you can check that the on and off times match what you wrote.
- Use 200 to 500 ms for a lively but readable blink.
- Avoid anything under about 30 ms when you want to see individual blinks.
- Keep the numbers in named constants once the sketch grows, so a change happens in one place.
const uint8_t LED_PIN = 8;
const unsigned int ON_MS = 150;
const unsigned int OFF_MS = 850;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(ON_MS);
digitalWrite(LED_PIN, LOW);
delay(OFF_MS);
}This sketch flashes the LED briefly once per second, like a status indicator. The unsigned int type holds values up to 65535 on AVR boards, which is enough for these intervals.
Common mistakes with delay()
- Forgetting the second delay. With only one
delay()afterHIGH, the LED turns off and on again in microseconds. The off period is too short to see, so the LED looks permanently lit. - Confusing seconds with milliseconds.
delay(1)waits a thousandth of a second. A learner expecting a one-second pause sees a 500 Hz flicker that looks steady. - Using a negative or oversized value. Compute long delays with
ULsuffixes. - Putting
delay()beforepinMode()logic that matters.setup()runs once, so a delay there only slows startup. This is sometimes useful, for example to let a sensor settle, but it does not make the blink slower. - Expecting the delay to be exact. Do not use
delay()as a stopwatch for a clock or a long measurement. Errors accumulate on every pass.
The cost of blocking
A function that does not return until a condition is met is called blocking. delay() is the most common example in Arduino code. While it waits, loop() cannot do anything else.
Suppose you add a button to the sketch and want the LED to react when the button is pressed. The program reads the button once per pass through loop(). With the two one-second delays, the button is read at most once every two seconds. A press shorter than that is easy to miss, and the response always feels late.
const uint8_t LED_PIN = 8;
const uint8_t BUTTON_PIN = 2;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(1000);
digitalWrite(LED_PIN, LOW);
delay(1000);
// Runs only once per two-second cycle, so most presses are missed.
if (digitalRead(BUTTON_PIN) == LOW) {
Serial.println("Button pressed");
}
}The button is read only after both delays. A tap that starts and ends during a delay is never seen. This is the main reason that delay() suits only simple sketches. It is fine for a first blink, for a quick test of a wire, and for short pauses such as letting a signal settle. It becomes a problem as soon as the board must do two things at once.
The alternative is to check the clock instead of waiting on it. The last chapter of this tutorial shows how to do that with millis(). The idea is that loop() runs continuously, and each pass asks whether it is time to toggle the LED yet. For now, treat delay() as the right tool for a first blink and remember its limit.
Checking your understanding of the timing
You can confirm the delay behaviour with the serial monitor. This sketch prints how long each half cycle took, measured with millis().
const uint8_t LED_PIN = 8;
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long start = millis();
digitalWrite(LED_PIN, HIGH);
delay(500);
unsigned long onTime = millis() - start;
start = millis();
digitalWrite(LED_PIN, LOW);
delay(500);
unsigned long offTime = millis() - start;
Serial.print("on: ");
Serial.print(onTime);
Serial.print(" ms, off: ");
Serial.print(offTime);
Serial.println(" ms");
}Open the serial monitor at 9600 baud. You should see values at or very close to 500 for each half. A reading of 501 is normal, because millis() counts whole milliseconds and the two calls can straddle a tick. Printing to the serial port takes a few milliseconds of its own, but that happens after the off-time measurement, so it does not distort the numbers.
Summary
- Without a pause, the LED toggles faster than the eye can follow and looks steadily dim.
delay(ms)holds the sketch for the given number of milliseconds, and the pin keeps its level during the wait.- On and off times are set separately, so you control both the blink rate and the duty pattern.
delay()blocksloop(). Interrupts still run, but your own code does not.- Use
ULsuffixes for long computed delays, and keep intervals in named constants.
Exercise
A sketch sets the LED pin HIGH, calls delay(100), sets it LOW, calls delay(400), and repeats. What is the period, the blink frequency, and the fraction of each cycle during which the LED is lit?
Show answer
The period is 100 ms + 400 ms = 500 ms, ignoring the few microseconds of overhead. The frequency is 1 / 0.5 s = 2 Hz. The LED is lit for 100 ms of each 500 ms, which is 20% of the cycle.
Exercise
A learner writes delay(60 * 1000) on an Uno, expecting a one-minute pause, and the pause is much shorter than expected. Explain the cause and give a corrected line.
Show answer
On an Uno, int is 16 bits, so 60 1000 is computed as an int and overflows, because 60000 exceeds the maximum of 32767. The result wraps to a wrong value before it reaches delay(). Use unsigned long constants: delay(60UL 1000UL);
Exercise
A sketch blinks an LED with two delay(1000) calls and checks a button once at the end of loop(). Why is a short button press often missed, and what general change fixes it?
Show answer
The button is read only once every two seconds, after both delays finish. A press that begins and ends during a delay is never sampled. The fix is to stop blocking: use millis() to decide when to toggle the LED, so loop() runs continuously and reads the button on every pass.