typestar

Blink without delay in Arduino

millis never blocks: compare timestamps instead of sleeping.

// millis never blocks: compare timestamps instead of sleeping.
const unsigned long INTERVAL_MS = 750;

unsigned long lastToggle = 0;
bool ledOn = false;

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

void loop() {
  unsigned long now = millis();
  // Subtraction stays correct even when millis wraps around.
  if (now - lastToggle >= INTERVAL_MS) {
    lastToggle = now;
    ledOn = !ledOn;
    digitalWrite(LED_BUILTIN, ledOn ? HIGH : LOW);
  }
}

How it works

  1. millis() is the free-running clock since power-on.
  2. now - lastToggle >= INTERVAL_MS survives the 49-day wraparound.
  3. The loop stays free to do other work between toggles.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
430
Tokens
78
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 72 seconds.

Type this snippet

Step 1 of 3 in Timing, step 10 of 27 in Language basics.

← Previous Next →