Lessons · Lesson K4 · Code basics · 30 min
Timing and states
Stop the board from freezing during a wait, keep time with millis(), then build a small alarm as a state machine. About 30 minutes, with a diagram you can press.
The light that cannot hear
Picture a traffic light that changes colour every few seconds. A pedestrian walks up and presses the crossing button. Nothing happens, because the controller is busy “waiting” for the next change and does not look at the button until the wait ends. A real crossing must do both at once: keep the cycle going and stay alert.
You can make this mistake with delay(). On classic Arduino boards it is a busy wait: the processor sits on it and does nothing else [3]. The ESP32 is a little different: during a delay() the chip’s own background tasks keep running. But that does not help you, because your loop() is still stuck on that line and cannot read the button. During the wait your code cannot read an input, process data or change an output [2][3]. The Arduino reference says the same: no sensor reading, calculation or pin change can happen during a delay(), so most other activity stops [2]. (A few background jobs carry on, such as characters arriving on the serial line being stored [2]. Your own code does not.)
For a blinking LED this does not matter. For an alarm that must react to a button, it matters a lot.
In this lesson you will:
- watch a board freeze and then fix it with the clock,
- learn why that fix survives the clock running over,
- build a small alarm that remembers what state it is in.
Watch the clock instead
Instead of stopping for a second, you can look at a clock now and then. The board has one built in: millis() returns the number of milliseconds since the program started [1]. (A millisecond is a thousandth of a second, so 1000 of them make one second.)
The idea is a schedule and an eye on the clock [4]:
- Write down the time of the last change (
lastBlink). - On every pass of
loop(), read the clock (now). - If
now - lastBlinkis at least the interval you want, it is time: do the job and write down the new time. - Otherwise do nothing and go on. Other jobs, such as reading a button, run in the same pass.
loop() now spins very fast and checks the clock each time, instead of waiting. The Arduino documentation points to this method as the alternative to long delays [2]. The example sketch that comes with the IDE is called BlinkWithoutDelay [4].
Where the picture stops. A wall clock keeps going while you read a book. millis() also keeps going, but your code only looks at it when loop() comes round. If some part of the loop takes a long time, the check comes late. So the rule is simple: no delay() in a sketch that has to stay responsive, and no long jobs inside loop().
Blink and still listen
Wire the parts from lesson K2: the button on GPIO 27 (other leg to GND), the LED on GPIO 26 through 220 Ω, the active buzzer on GPIO 25. The LED is our “traffic light”, and the buzzer is the “pedestrian beeper”.
Upload this sketch and open the Serial Monitor at 115200 baud:
// Tinker Mission, lesson K4: blink without freezing (millis) and still hear a button
// Wiring (same parts as lesson K2):
// Button: one leg to GPIO 27, the diagonally opposite leg to GND (no resistor needed)
// LED: GPIO 26 -> 220 ohm -> LED long leg; LED short leg -> GND
// Active buzzer: + leg to GPIO 25, other leg to GND (3-pin module: VCC to 3V3, GND to GND, I/O to GPIO 25)
// The LED is the "traffic light": it changes every second.
// The buzzer is the "pedestrian beeper": it sounds while you hold the button.
// Open the Serial Monitor at 115200 baud: it shows how many times loop() ran in the last second.
// Try it: change USE_DELAY to true, upload, and hold the button. Then change it back.
const int BUTTON_PIN = 27;
const int LED_PIN = 26;
const int BUZZER_PIN = 25;
const bool USE_DELAY = false; // false = millis() version, true = delay() version
const unsigned long BLINK_INTERVAL = 1000; // the LED changes every 1000 ms
const unsigned long REPORT_INTERVAL = 1000; // print a report every 1000 ms
unsigned long lastBlink = 0; // the time (in ms) of the last LED change
unsigned long lastReport = 0; // the time of the last report
unsigned long loopCount = 0; // how many times loop() ran since the last report
int ledState = LOW;
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
unsigned long now = millis(); // the board's clock: milliseconds since it started
loopCount = loopCount + 1;
// Job 1: the slow one, change the LED every second.
if (USE_DELAY) {
digitalWrite(LED_PIN, HIGH);
delay(1000); // the whole board waits here
digitalWrite(LED_PIN, LOW);
delay(1000); // and here
} else {
if (now - lastBlink >= BLINK_INTERVAL) {
lastBlink = now; // note the time of this change
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LED_PIN, ledState);
}
}
// Job 2: the quick one, sound the buzzer while the button is held.
if (digitalRead(BUTTON_PIN) == LOW) {
digitalWrite(BUZZER_PIN, HIGH);
} else {
digitalWrite(BUZZER_PIN, LOW);
}
// Job 3: once a second, say how often loop() ran.
if (now - lastReport >= REPORT_INTERVAL) {
lastReport = now;
Serial.print("loop() ran ");
Serial.print(loopCount);
Serial.println(" times in the last second");
loopCount = 0;
}
}
Download the sketch folder (.zip)
The LED changes once a second. Press the button at any moment: the buzzer answers at once. The Serial Monitor shows a very large number of loop() passes per second. Read yours: the board is not idle, it is checking everything all the time.
Now the experiment. Change USE_DELAY to true, upload again, and press the button in short taps. The LED still blinks, but the buzzer is late, misses your tap altogether, or keeps sounding after you let go, because the board is stuck inside a delay(). The report line now shows only 1 pass of loop(), and it appears once every two seconds (it still says “in the last second”, but each pass now takes two). Change it back to false when you are done.
What the new lines do:
const bool USE_DELAYis a switch for the experiment. Aboolholdstrueorfalse.unsigned long now = millis();reads the clock once per pass. The type isunsigned longbecause that is whatmillis()returns [1].now - lastBlink >= BLINK_INTERVALasks: “have 1000 ms gone by since the last change?”lastBlink = now;writes down the time of this change, so the next wait starts from here.
When the clock runs over
millis() cannot count forever. It is an unsigned long, a 32-bit number that goes from 0 to 4,294,967,295 [5]. After about 50 days it overflows and goes back to zero [1]. (Do the sum: 4,294,967,296 ms is about 49.7 days.)
Does the blink break on that day? Not if you compare the way the sketch does: subtract, then compare.
A small clock. Imagine a clock that counts 0 to 99 and then starts over at 0. You noted the time 95. A moment later the clock says 3. Eight ticks have gone by (96, 97, 98, 99, 0, 1, 2, 3). The subtraction 3 - 95 gives -92 on paper. An unsigned number cannot be negative: it works in a circle, like this clock, and -92 wraps around to 100 - 92 = 8. The right answer.
The real clock does the same with 4,294,967,296 positions instead of 100. Say lastBlink is 4,294,967,000 and now has wrapped round to 200. The sum now - lastBlink comes out as 496, which is exactly how many milliseconds have passed (296 to get back to zero, then 200 more). You can check this on your own board in “Try your own changes”.
What breaks it. Writing if (now >= lastBlink + 1000) looks equivalent, but it is not. With lastBlink at 4,294,967,000, the sum lastBlink + 1000 itself wraps round to 704, so the test passes at once, long before the interval is over. And storing the time in an int is no good either: smaller types lead to logic errors, and even a signed long only goes half as high [1].
The habit to take away: unsigned long variables, and now - last >= interval. The wait you measure can be as long as the clock allows, about 49 days, far more than any blink or alarm needs.
States: a memory for the board
Now a bigger job: an alarm with moods. It is armed and waiting. When something is detected it goes to alarm. When you press the silence button it goes silenced for a while, then armed again.
The right tool for this is a state machine. The idea needs only three things:
- a list of states, the situations the machine can be in (here: ARMED, ALARM, SILENCED),
- a variable that remembers the current state (
state), - rules: in each state, what to do, and which event moves you to another state.
Think of a board game. You stand on one square at a time. The square tells you what you may do, and a certain roll sends you to another square. The machine is always on exactly one square.
Our three squares:
- ARMED: the LED gives a short flash about every two seconds, a quiet “I am watching”. If the sensor trips, go to ALARM.
- ALARM: LED and buzzer pulse together. If the silence button is pressed, go to SILENCED.
- SILENCED: LED steady on, buzzer off. After 10 seconds, go back to ARMED.
Notice what you do not need: no delay(). Each state has its own few lines, and every pass of loop() runs only the lines of the current state. The flashing uses the same clock trick as before. The 10-second silence is just now - stateStart >= SILENCE_TIME.
Press the virtual buttons in the diagram below: the current state lights up, and the arrows show where each event leads. Then flip the switch to “frozen” to see what the same machine does when it uses delay() to wait.
Simulation of the sketch, not the real board.
state = ARMED
no timer in this state
loop() runs on: buttons read on every pass
Button not read: you let go during the wait.
ARMED: waiting for the sensor.
This is the starting state: the controls need JavaScript.
The alarm, in code
Add a second button as a pretend sensor, between GPIO 33 and GND (same wiring style as the first button). In later lessons you will swap it for a real sensor. Both buttons use INPUT_PULLUP, the board’s own pull-up, as in lesson K2. The datasheet says most digital GPIOs can be set up with an internal pull-up [6].
// Tinker Mission, lesson K4: a tiny alarm built as a state machine (ARMED, ALARM, SILENCED)
// Wiring:
// Silence button: one leg to GPIO 27, the diagonally opposite leg to GND (no resistor needed)
// Pretend sensor: a second button, one leg to GPIO 33, the diagonally opposite leg to GND
// (pressed = "something was detected"; later lessons swap in real sensors)
// LED: GPIO 26 -> 220 ohm -> LED long leg; LED short leg -> GND
// Active buzzer: + leg to GPIO 25, other leg to GND (3-pin module: VCC to 3V3, GND to GND, I/O to GPIO 25)
// ARMED: the LED flashes briefly, about once every 2 seconds. Pressing the sensor button starts the alarm.
// ALARM: the LED and the buzzer pulse together. Pressing the silence button stops the noise.
// SILENCED: the LED stays on, the buzzer is off. After 10 seconds the alarm is armed again.
// No delay() anywhere: every state keeps checking its buttons all the time.
const int BUTTON_PIN = 27; // silence button, pressed = LOW
const int SENSOR_PIN = 33; // pretend sensor, pressed = LOW
const int LED_PIN = 26;
const int BUZZER_PIN = 25;
// The three states, as numbers with names.
const int STATE_ARMED = 0;
const int STATE_ALARM = 1;
const int STATE_SILENCED = 2;
const unsigned long HEARTBEAT_ON = 100; // armed: LED on for 100 ms ...
const unsigned long HEARTBEAT_OFF = 1900; // ... then off for 1900 ms
const unsigned long ALARM_HALF = 200; // alarm: on 200 ms, off 200 ms
const unsigned long SILENCE_TIME = 10000; // silenced: 10 seconds
int state = STATE_ARMED; // the memory of the machine: which state are we in?
unsigned long stateStart = 0; // the time when we entered this state
unsigned long lastToggle = 0; // the time of the last pulse change
int pulse = LOW; // the current pulse level (HIGH = on)
// Switch to a new state and restart its clocks.
void enterState(int newState, unsigned long now) {
state = newState;
stateStart = now;
lastToggle = now;
pulse = HIGH; // every state starts with its pulse on
if (state == STATE_ARMED) {
Serial.println("-> ARMED");
} else if (state == STATE_ALARM) {
Serial.println("-> ALARM");
} else {
Serial.println("-> SILENCED");
}
}
// Flip the pulse when it has lasted long enough, without waiting.
void updatePulse(unsigned long now, unsigned long onTime, unsigned long offTime) {
unsigned long needed = offTime;
if (pulse == HIGH) {
needed = onTime;
}
if (now - lastToggle >= needed) {
lastToggle = now;
if (pulse == HIGH) {
pulse = LOW;
} else {
pulse = HIGH;
}
}
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(SENSOR_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
enterState(STATE_ARMED, millis());
}
void loop() {
unsigned long now = millis();
bool buttonPressed = (digitalRead(BUTTON_PIN) == LOW);
bool sensorTriggered = (digitalRead(SENSOR_PIN) == LOW);
if (state == STATE_ARMED) {
updatePulse(now, HEARTBEAT_ON, HEARTBEAT_OFF);
digitalWrite(LED_PIN, pulse);
digitalWrite(BUZZER_PIN, LOW);
if (sensorTriggered) {
enterState(STATE_ALARM, now);
}
} else if (state == STATE_ALARM) {
updatePulse(now, ALARM_HALF, ALARM_HALF);
digitalWrite(LED_PIN, pulse);
digitalWrite(BUZZER_PIN, pulse);
if (buttonPressed) {
enterState(STATE_SILENCED, now);
}
} else {
// STATE_SILENCED
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, LOW);
if (now - stateStart >= SILENCE_TIME) {
enterState(STATE_ARMED, now);
}
}
}
Download the sketch folder (.zip)
Open the Serial Monitor: it prints a line each time the state changes. Press the sensor button, then the silence button, then wait.
How to read it:
- The three
const int STATE_...lines give each state a name.stateholds the current one. loop()reads both buttons once, then the bigif / else if / elsepicks the lines of the current state. Only one branch runs per pass.enterState()is the only place where the state changes. It also notes the time (stateStart), so each state can measure how long it has lasted.updatePulse()is the blink trick from screen 3, written once and reused for the slow heartbeat and the fast alarm.- The
-> ARMEDmessages are only for you, to watch the machine move.
Try your own changes
Change one thing, upload, observe.
-
See the rollover. At the end of
setup()inl-k4-millis, add these lines, upload, and read the Serial Monitor:unsigned long last = 4294967000UL; // the letters UL mean "unsigned long" unsigned long before = 4294967001UL; // 1 ms later unsigned long after = 200; // the clock has gone round the circle Serial.println(after - last); // elapsed time across the rollover Serial.println(before - last >= 1000); // the safe test: 1 means "time is up" Serial.println(before >= last + 1000); // the unsafe testWhat do the three numbers say, and which test gets it wrong? (If nothing shows up, press the EN button on the board: it restarts the program and runs setup() again.) Remove the lines afterwards.
-
Longer silence. Set
SILENCE_TIMEto 3000. How does the machine feel now? -
A new state. Add a fourth state,
STATE_TEST, entered by holding the silence button in ARMED, that lights the LED steadily for 2 seconds. Which lines do you add: the constant, a branch inloop(), a name inenterState()?
When it does not work
- The LED never changes (millis version). Check that
lastBlink = now;is inside theif, and thatBLINK_INTERVALis not tiny or huge. - Pressing the button changes nothing. Check
GNDon the button’s other leg and theINPUT_PULLUPline. A button is read asLOWwhen pressed, as in K2. - The alarm starts by itself. The pretend sensor pin reads
LOWtoo often: a loose wire toGNDor a wrongly placed button. Press nothing and look at the Serial Monitor. - The silence button does nothing. By design, it only works in ALARM. In ARMED and SILENCED it is ignored.
- ALARM comes back right after SILENCED. The sensor button is still held (see quiz question 3).
- Timings are a bit late. Look for a
delay()or a slow job hiding in your changes. - Nothing in the Serial Monitor. Set it to 115200 baud, the same as
Serial.begin(115200).
Check yourself
Three short questions. Nothing is saved, take your time.
While delay(1000) is running, what can the board do?
- Keep reading the button, since delay() only pauses the LED
- Almost nothing: it cannot read inputs or change outputs until the wait is over
- Run two programs at once
Show the answer
Almost nothing: it cannot read inputs or change outputs until the wait is over. delay() pauses the program. No sensor reading, calculation or pin change can happen in the meantime, so most activity stops [2][3]. That is why a button pressed during the wait can be answered late, or missed.
Which variable type should hold a value returned by millis()?
- int
- unsigned long
- byte
In the alarm sketch, the 10 seconds of SILENCED end while the pretend sensor button is still held down. What happens next?
- The alarm stays ARMED and quiet until you release the button
- The state goes back to ARMED, then straight to ALARM
- The board restarts
Show the answer
The state goes back to ARMED, then straight to ALARM. When the silence time is over, the machine enters ARMED. In ARMED the sketch checks the sensor on every pass of loop(), sees it is still pressed, and moves to ALARM. That is the right behaviour for a door that is still open.
In short
delay()stops yourloop(): while it runs, your code cannot read inputs or change outputs, even though the ESP32’s background tasks carry on [2][3].millis()is the board’s clock, in milliseconds, since the program started [1].- The pattern: write down the last time, and on each pass ask
now - last >= interval. If yes, act and note the new time. - Use
unsigned long. The subtraction keeps working when the clock runs over, after about 50 days [1][5]. - A state machine is a list of states, a variable that remembers the current one, and rules for moving between them. Each pass of
loop()runs only the current state.
Next steps: a sensor wired in place of the pretend button, and K5 for modules that talk to the board.
Sources
Show the 6 sources
- Arduino, Language Reference, “millis()” (returns the number of milliseconds since the board began running the current program; the number overflows, going back to zero, after approximately 50 days; return type unsigned long; arithmetic with smaller types such as int can cause logic errors, and signed long has half the maximum of unsigned) — https://docs.arduino.cc/language-reference/en/functions/time/millis/
- Arduino, Language Reference, “delay()” (pauses the program for the given number of milliseconds; no other reading of sensors, calculations or pin manipulation can occur during the delay, so it brings most other activity to a halt; the Blink Without Delay sketch polls millis() as an alternative; serial data arriving at RX is still recorded) — https://docs.arduino.cc/language-reference/en/functions/time/delay/
- Adafruit, “Multi-tasking the Arduino - Part 1”, “Ditch the delay()” (on classic Arduino boards delay() is a busy wait that monopolizes the processor; during a delay() call you cannot respond to inputs, process data or change outputs) — https://learn.adafruit.com/multi-tasking-the-arduino-part-1/ditch-the-delay
- Adafruit, “Multi-tasking the Arduino - Part 1”, “Using millis() for timing” (make a schedule and keep an eye on the clock instead of a world-stopping delay; the BlinkWithoutDelay example sketch that comes with the IDE) — https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing
- Arduino, Language Reference, “unsigned long” (stores 32 bits, range 0 to 4,294,967,295, which is 2^32 - 1; no negative numbers) — https://docs.arduino.cc/language-reference/en/variables/data-types/unsignedLong/
- Espressif, ESP32 Series Datasheet v5.3 (most digital GPIOs can be configured as internal pull-up or pull-down, or set to high impedance) — https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf