Waiting with delay()
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.
The easy way uses delay(). delay(500) pauses the program for 500 ms. The CPU sits on that line and does nothing else: no reading pins, no maths, no writing pins. Only interrupts still run.
At 1,200 ms you press the button, and you let go at 1,450 ms. The CPU is inside a delay(500) the whole time, so it never looks. The press comes and goes, and LED 12 stays dark.
This loop reads the button only once per pass, on line 5, and a pass takes 1,000 ms. Short presses vanish, and long ones wait up to a second. Every delay you add makes it worse.
Checking the clock instead
The fix: never wait. Each pass starts with now = millis(), the milliseconds since the board started. A pass with no waiting is very short, so loop() comes round again almost at once, thousands of times a second.
Line 2 asks: have 500 ms passed since last? At now = 1,130, now - last is 130, so no. The CPU skips the LED code, reads the button on line 7, sets LED 12 on line 8, and starts the next pass.
You press at 1,200 ms. The very next pass reaches line 7 and reads LOW, which means held. Line 8 turns LED 12 on, microseconds after your press. Nothing is missed, because nothing waits.
At now = 1,500, now - last is 500, so line 2 is true. last becomes 1,500, the LED state flips, and line 5 turns LED 13 on. Then the pass carries on and reads the button as usual.
Give every timed job its own last and interval, and check it on each pass. Never wait inside a pass: no delay(), no while loop waiting for a pin. The lesson “Event-driven firmware as a state machine” builds on this.
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.