0
0
AutocadHow-ToBeginner · 3 min read

How to Use delay() Function in Arduino for Pausing Code

In Arduino, use the delay(milliseconds) function to pause your program for a specific time in milliseconds. For example, delay(1000) pauses the program for 1 second. This is useful to create timed pauses between actions.
📐

Syntax

The delay() function takes one argument: the number of milliseconds to pause the program. The syntax is:

delay(milliseconds);

Here, milliseconds is an unsigned long integer representing the pause duration in milliseconds (1000 ms = 1 second).

arduino
delay(1000);
💻

Example

This example blinks the built-in LED on and off every second using delay(). It turns the LED on, waits 1 second, then turns it off and waits another second.

arduino
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH); // LED on
  delay(1000);                     // wait 1 second
  digitalWrite(LED_BUILTIN, LOW);  // LED off
  delay(1000);                     // wait 1 second
}
Output
The built-in LED blinks on for 1 second, then off for 1 second, repeatedly.
⚠️

Common Pitfalls

Using delay() stops all code execution, so the Arduino cannot do anything else during the pause. This can cause problems if you need to read sensors or respond to inputs while waiting.

Instead of delay(), consider using millis() for non-blocking timing if you want your program to keep running other tasks.

arduino
/* Wrong: blocks all code during delay */
digitalWrite(LED_BUILTIN, HIGH);
delay(5000); // Arduino does nothing else for 5 seconds

/* Better: non-blocking timing with millis() */
unsigned long previousMillis = 0;
const long interval = 5000;

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    // toggle LED or do other tasks
  }
  // other code runs here without blocking
}
📊

Quick Reference

delay() Cheat Sheet:

  • delay(1000); pauses for 1 second
  • Argument is in milliseconds (1000 ms = 1 second)
  • Blocks all code during delay
  • Use for simple pauses or blinking LEDs
  • Use millis() for multitasking without blocking

Key Takeaways

Use delay(milliseconds) to pause Arduino code for a set time in milliseconds.
delay() stops all code execution during the pause, blocking other tasks.
For multitasking, use millis() instead of delay() to avoid blocking.
delay() is simple and good for basic timing like blinking LEDs.
Always specify delay time in milliseconds (1000 ms = 1 second).