মূল বিষয়বস্তুতে যান
Learn/Programming patterns/Doing several things at once with millis()
Programming patterns · Lesson
12 min read

Doing several things at once with millis()

Replace delay() with timestamps so your sketch stays responsive.

What You Will Learn

  • Use millis() for timing
  • Run two blinking rhythms at once
  • Handle unsigned long overflow correctly

delay() freezes the whole program. millis() returns the number of milliseconds since start-up, so you can check 'has enough time passed?' and carry on with other work.

Arduino C++
unsigned long lastBlink = 0;
bool ledOn = false;

void loop() {
  if (millis() - lastBlink >= 500) {
    lastBlink = millis();
    ledOn = !ledOn;
    digitalWrite(9, ledOn);
  }
  // ...read buttons, sensors, serial here without waiting
}
Always write millis() - last >= interval (subtraction). It keeps working when millis() wraps around after about 49 days.

Check Your Understanding

Test what you learned in this lesson

1Why use millis() instead of delay()?

2Which type should store millis() values?