Programming patterns · Lesson
12 min read
State machines
Model behaviour as states and transitions for clear, bug-free logic.
What You Will Learn
- Represent states with constants
- Use switch to handle each state
- Change state on events and timers
Many devices behave differently depending on what they're doing: a traffic light is GREEN, then YELLOW, then RED. Storing the current state in a variable and handling each state in a switch makes this explicit.
Arduino C++
const int GREEN = 0, YELLOW = 1, RED = 2;
int state = GREEN;
unsigned long since = 0;
void loop() {
unsigned long now = millis();
switch (state) {
case GREEN: if (now - since > 3000) { state = YELLOW; since = now; } break;
case YELLOW: if (now - since > 1000) { state = RED; since = now; } break;
case RED: if (now - since > 3000) { state = GREEN; since = now; } break;
}
}Combine with millis(): the loop never blocks, so a pedestrian button can be checked in every state.
Check Your Understanding
Test what you learned in this lesson