Robotics and Embedded Systems

Lesson 11: Timers, Interrupts and Non-Blocking CodeNew-age

So far your programs have used delay(), which stops everything while it waits. That is fine for a blinking LED, but a robot cannot afford to freeze: while it waits for a sensor, it should still be watching its buttons, updating its display and steering its motors. This lesson replaces delay() with non-blocking code — the millis() timer, state machines and interrupts — so your programs can do several things at once.

Non-blocking code is the difference between a toy and a robot. It is a little harder to write at first, but once you learn the pattern, you will use it in every project. The pattern is simple: never wait; check the time, do what is due, and move on.

Key Terms.
  • Blocking code — code that stops the program while it waits, such as delay().
  • Non-blocking code — code that checks whether something is due and returns immediately if not.
  • millis() — a function returning the milliseconds since the board started.
  • State machine — a program organised as states — such as IDLE, RUNNING, STOPPED — with rules for moving between them.
  • Interrupt — a signal that pauses the main program to run a short handler immediately.
  • Timer — a hardware counter that triggers an action at a set interval.
  • Polling — repeatedly checking whether something has happened.
  • Overflow — the millis() counter wrapping back to zero after about 50 days.

Why delay() is a problem

delay(1000) stops the program for a full second: no buttons are read, no sensors are checked, no motors are updated. A robot that delays for a second after every sensor reading will miss a button press, drive past a line, or fail to stop at an obstacle. The longer the delay, the worse the problem, and a program with several delays becomes unresponsive in ways that are hard to debug — because the code looks correct, line by line, and only the timing is wrong.

The fix is to stop waiting and start checking. Instead of “wait one second, then blink”, write “if one second has passed since the last blink, blink now”. The program checks the time on every loop, does what is due, and moves on. Nothing ever waits, so nothing is ever missed.

The millis() pattern

millis() returns the number of milliseconds since the board started. To run an action every 1000 ms, remember the time of the last run and compare: if (millis() - lastBlink >= 1000) { lastBlink = millis(); blink(); }. The subtraction handles the counter’s overflow correctly, because unsigned arithmetic wraps around — a detail that matters only after the board has run for about 50 days, but it is good to get right from the start.

Use a separate timer variable for each repeated action: one for blinking, one for reading a sensor, one for updating a display. Each is checked independently on every loop, so the actions run at their own rates without interfering. This is the core pattern of non-blocking code, and it scales: a program with ten timed actions is no harder to write than one with two.

State machines

A state machine organises a program as a set of states with rules for moving between them. A traffic light has three states — RED, AMBER, GREEN — and a timer moves it from one to the next. A robot might have IDLE, FORWARD, TURNING and STOPPED. The code keeps a variable for the current state and a switch statement that does the right thing for that state and checks whether it is time to move on.

State machines make complex behaviour readable. Instead of a tangle of if statements, the program says plainly what it is doing and what would make it do something else. They also make bugs easier to find: if the robot is stuck, ask which state it is in and why it never leaves it. Draw the states and their transitions on paper before you code them — the drawing is the design.

Interrupts: when polling is not fast enough

Polling — checking an input on every loop — is fast enough for buttons and most sensors. But some events are too brief to poll: a wheel encoder that pulses for a microsecond, or a signal that must be caught the instant it arrives. For those, use an interrupt: a hardware signal that pauses the main program, runs a short handler function, and returns. Attach one with attachInterrupt(digitalPinToInterrupt(pin), handler, RISING), and the handler runs whenever the pin rises.

Worked example — blink without delay

The classic example blinks an LED every second while the program stays responsive. The LED toggles when 1000 ms have passed since the last toggle, and the rest of the loop is free to read sensors and buttons.

const int LED = 13;
unsigned long last = 0;
bool on = false;
void loop() {
  if (millis() - last >= 1000) {
    last = millis();
    on = !on;
    digitalWrite(LED, on);
  }
  // other work goes here and runs every loop
}

Common mistakes

  • Using delay() inside a program that must also watch inputs. The program freezes and misses events.
  • Comparing millis() with > instead of subtracting: if (millis() > last + 1000) breaks when the counter overflows.
  • Writing long interrupt handlers that print or delay. Keep them to a flag or a counter.
  • Using one timer variable for two different actions, so they interfere with each other.

Discussion questions

  1. A program uses delay(10) in its loop. Is that a problem? How short must a delay be before it stops mattering?
  2. A state machine for a robot has states IDLE, FORWARD, TURNING and STOPPED. What events move it between states, and what happens if an event is missed?
  3. Polling checks an input every loop; an interrupt reacts instantly. Why not use interrupts for everything?

Practice questions

  1. Why is delay() a problem in a robot program? Answer: It stops the whole program while it waits, so buttons, sensors and motors are ignored. A robot that delays will miss events. Explanation: delay() freezes everything.
  2. Write the condition that runs an action every 500 ms using millis(). Answer: if (millis() - lastRun >= 500) { lastRun = millis(); /* action */ }. The subtraction handles overflow correctly. Explanation: Subtract, don’t compare directly.
  3. What is a state machine, in one sentence? Answer: A program organised as states with rules for moving between them, such as a traffic light moving RED → GREEN → AMBER. Explanation: States plus transitions.
  4. When should you use an interrupt instead of polling? Answer: When an event is too brief or too urgent to be caught by checking each loop, such as a fast encoder pulse. Explanation: Interrupts catch what polling misses.
  5. Why must an interrupt handler be kept very short? Answer: Because interrupts are disabled inside it, so the program can do nothing else until it returns. A long handler blocks everything. Explanation: Handlers should only set a flag.

✅ Check your understanding

Quick recall check, generated from this lesson’s key terms. It is practice only and is not graded.

Keep reading to complete this lesson