# Arduino timing without blocking loop()

Move from delay() to millis() with a minimal example, timing tradeoffs, and an exercise to extend.

https://elmehdi-essamit.me/en/notes/arduino-sans-delay/

## Replace waiting with a condition

A first LED sketch often uses delay(). During this pause, the main program flow waits. To check an input regularly or prepare multiple tasks, compare elapsed time against an interval and return control to loop().

millis() returns elapsed milliseconds since startup as an unsigned long. The counter wraps around after about 50 days.

[Arduino · millis()](https://www.arduino.cc/en/Reference/millis)

## A minimal example to adapt

This teaching sketch controls the built-in LED. Each call to loop() checks whether 500 ms have elapsed; it does not wait for the next change.

```C++ / Arduino
constexpr unsigned long intervalMs = 500UL;
unsigned long lastToggle = 0;
bool ledOn = false;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop() {
  const unsigned long now = millis();
  if (now - lastToggle >= intervalMs) {
    lastToggle = now;
    ledOn = !ledOn;
    digitalWrite(LED_BUILTIN, ledOn ? HIGH : LOW);
  }
  // Add other short, non-blocking tasks here.
}
```

Unsigned subtraction handles counter wraparound for this short interval, provided the condition is checked regularly. Here, lastToggle = now favors simplicity; timing can drift if the loop runs late.

[Arduino · Blink Without Delay, official example](https://github.com/arduino/arduino-examples/blob/main/examples/02.Digital/BlinkWithoutDelay/BlinkWithoutDelay.ino)

## Observe before adding features

- Change the interval and compare the expected behavior with the LED.
- Add a second timed state with its own timestamp.
- Deliberately introduce a slow task and observe the delays: millis() does not make the program parallel.

The LED changes state twice per full cycle. A 500 ms interval therefore gives a period of about one second. This is simple cooperative scheduling, without hard real-time guarantees.

This note extends the workshop topics. It does not replace the original materials, credited to the BeurdByte Builders team.

