Engineering note

Arduino timing without blocking loop()

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

Type
Engineering note
Project
BeurdByte Builders workshops
Status
Documented method
Updated
2026-11-15
Read time
4 min
Language
EN
Markdown
In this document
  1. Replace waiting with a condition
  2. A minimal example to adapt
  3. Observe before adding features

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()

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.

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

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.

IN 60 SECONDS

Elmehdi Essamit

I build complete systems, from the ESP32 sensor to the power-flow solver, and validate every result against a reference.

Profile
Engineering student, year 1 · EHTP
Looking for
Introductory internship · 1 to 2 months
Period
Summer 2027
Mobility
Morocco or abroad
Languages
Arabic · French · English
Download the CVessamit.elmehdi@proton.meLinkedInFull recruiter page

Search the portfolio