Software That Lasts

State Machines & millis()

14 minStudent plan

How to do several things at once on a chip with one core, and finally stop using delay().

After this lesson you can

  • Replace delay() with millis() timing
  • Write a sketch that does two things at once
  • Structure behaviour as states rather than a pile of ifs

The problem with delay()

delay() blocks. During delay(1000) the processor does nothing else, no button reads, no sensor checks, no display updates.

With one blinking LED that is fine. With an LED that blinks while a button is watched and a sensor is sampled, it is fatal: the button press that happens during the delay is simply never seen.

The fix is to stop waiting and start checking the clock. millis() returns the number of milliseconds since the board started, and it keeps counting whatever else you are doing. Instead of "wait 500 ms", you ask "has 500 ms passed since last time?", and if it has not, you go and do something else.

In the full lesson

  1. The problem with delay()
  2. Non-blocking timing
  3. State machines

This lesson comes with the Student plan. The first module of Programming is free.