millis()0 msCPU · SRAMnow–last–011301121digitalWrite(13, HIGH);2delay(500);3digitalWrite(13, LOW);4delay(500);5int b = digitalRead(2);6digitalWrite(12, !b);1now = millis();2if (now - last >= 500) {3 last += 500;4 led = !led;5 digitalWrite(13, led);6}7int b = digitalRead(2);8digitalWrite(12, !b);CPUnowLOWHIGH11
Back: an Uno with a button, the millis() clock, the CPU with now and last, and two LEDsFront: loop() with delay(), and loop() with millis()Tokens: the CPU walking the code, button reads, clock reads and pin writesAn Arduino Uno with two jobs: blink the LED on pin 13 every 500 ms, and light the LED on pin 12 while the button on pin 2 is held. With delay(), the CPU sits on one line for 500 ms at a time and reads the button once per 1,000 ms pass, so a press from 1,200 to 1,450 ms is never seen. With millis(), every pass reads the clock, does only what is due and reads the button, so the press shows at once and LED 13 still flips on time. The motion is slowed down a great deal.

Waiting with delay()

  1. Our Arduino Uno has two jobs. Blink the LED on pin 13 every 500 ms. And light the LED on pin 12 while you hold the button on pin 2. Both jobs must keep going at the same time.

Checking the clock instead

What happens

;; step 1/9 · jobs
board   Arduino Uno R3, ATmega328P at 16 MHz
job 1   pin 13: flip every 500 ms
job 2   pin 12 = button held?
button  pin 2 to GND, INPUT_PULLUP
        held -> LOW, open -> HIGH

The cards shorten the code: the full sketch declares unsigned long now and last, bool led, and sets pin 2 to INPUT_PULLUP in setup(). digitalRead returns LOW (0) while the button is held, so !b is true and LED 12 lights. How fast is a pass? Most ATmega328P instructions take one clock cycle, 62.5 ns at 16 MHz. Even a pass of 1,000 such instructions takes 62.5 µs, about 16,000 passes a second. The figure slows this down enormously: it runs one pass per millisecond, about 1,000 a second, so you can follow it.