Event-driven firmware as a state machine
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Firmware that reacts to buttons and to time gets tangled fast if it is written as a list of steps with delay() and flags. A state machine fixes that: name the few situations the device can be in (states), name what can happen (events), and write one rule for each arrow between them. Build a stair light on an Arduino Uno R3, with a button on pin 2 and the LED on pin 13: three states, two events, five arrows, and a loop() that never waits. The Hardware lesson “State machines” covers state diagrams and Moore and Mealy machines; “Non-blocking code: replacing delay()” covers the millis() timing used here.
The job: a stair light
A stair light on an Arduino Uno R3. Press the button on pin 2 and the LED on pin 13 comes on. After 10 s it blinks for 3 s as a warning, then goes off. A press while it blinks keeps it on.
board Arduino Uno R3 (ATmega328P)
button pin 2 to GND, pinMode(BTN, INPUT_PULLUP)
LED pin 13 (the on-board LED)
rules press: on for 10 s, then blink 3 s, then off
press while on: off
press while blinking: on for another 10 sاقرأ الدرس خطوة بخطوة
The job: a stair light
A stair light on an Arduino Uno R3. Press the button on pin 2 and the LED on pin 13 comes on. After 10 s it blinks for 3 s as a warning, then goes off. A press while it blinks keeps it on.
board Arduino Uno R3 (ATmega328P) button pin 2 to GND, pinMode(BTN, INPUT_PULLUP) LED pin 13 (the on-board LED) rules press: on for 10 s, then blink 3 s, then off press while on: off press while blinking: on for another 10 sThree named states
A state is what the device is doing right now. We need three: IDLE, LIGHT and WARN. An enum gives each one a name, and one variable, state, always holds exactly one of them. It starts at IDLE.
enum State { IDLE, LIGHT, WARN }; // 0, 1, 2 State state = IDLE; // the initial state IDLE light off, waiting for a press LIGHT light on, timing 10000 ms WARN light blinking, timing 3000 msTwo kinds of event
An event is something that happens. PRESS: pressed() saw a new press on pin 2. TIMEOUT: age(), the time since we entered the state, reached its limit. loop() checks for both on every pass and never waits.
PRESS bool press = pressed(); true once per press (debounced: 50 ms of quiet, as in "Debouncing a button") TIMEOUT age() >= limit age() = millis() - t0, t0 = when we entered the state no delay(): each pass checks, maybe moves, and returnsswitch picks the case
switch (state) jumps straight to the case for the current state. Each case only checks the events that matter there. break ends the case; without it the code would fall through into the next case.
line 1 switch (state) { IDLE -> lines 2-4 LIGHT -> lines 5-9 WARN -> lines 10-14 break leaves the switch without it, execution falls through into the next caseIDLE + PRESS → LIGHT
We press. In case IDLE, line 3 sees press and calls go(LIGHT). go() stores the new state and t0 = millis(), the moment we entered it. After the switch, the LED is set from the state: on.
t = 1000 ms pressed() returns true line 3 if (press) go(LIGHT); go() state = LIGHT; t0 = millis(); after on = (state == LIGHT) -> LED onWaiting without blocking
In LIGHT nothing happens for a while. Each pass of loop() asks two questions: press? age() >= 10000? No and no, so it moves on at once. age() climbs by itself, because millis() keeps counting.
every pass, in case LIGHT: line 6 press? no line 7 age() >= 10000? no line 9 break; loop() never stops here, so a press is never missedLIGHT + TIMEOUT → WARN
At age() = 10,000 ms, line 7 is true and line 8 calls go(WARN). t0 is reset. Now the LED blinks: (millis() / 250) % 2 flips every 250 ms.
t = 11000 ms age() = 10000 ms >= ON_MS line 8 go(WARN); LED on while (millis() / 250) % 2 == 0 250 ms on, 250 ms off: 2 blinks per secondWARN + PRESS → LIGHT
Someone presses during the warning. Line 11 sends us back to LIGHT, and go() resets t0, so the full 10 s starts again. In LIGHT the same press means off; here it means stay on. The state decides.
t = 12000 ms press in WARN line 11 if (press) go(LIGHT); t0 12000: the 10 s start again same event, different state, different arrow: PRESS in LIGHT -> IDLE PRESS in WARN -> LIGHTWARN + TIMEOUT → IDLE
Left alone, WARN blinks for 3,000 ms. Then line 12 is true and line 13 calls go(IDLE). The LED goes dark. The machine is back where it began, waiting for the next press.
t = 22000 ms LIGHT times out -> WARN t = 25000 ms age() = 3000 ms >= WARN_MS line 13 go(IDLE); LED offFive arrows, one table
The whole design is five arrows: state plus event gives the next state. An event with no arrow is ignored, such as TIMEOUT in IDLE. To add a feature, add a state or an arrow and its case; the rest stays untouched.
state event next line IDLE PRESS LIGHT 3 LIGHT PRESS IDLE 6 LIGHT TIMEOUT WARN 8 WARN PRESS LIGHT 11 WARN TIMEOUT IDLE 13 IDLE TIMEOUT (none: ignored)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01In this firmware, what is a state?
IDLE, LIGHT and WARN are the states. The variable state always holds exactly one of them, and the switch uses it to pick which rules apply.
02The light is in LIGHT and age() reaches 10000 ms. Nobody presses. What happens?
Line 7, else if (age() >= ON_MS), is true, so line 8 calls go(WARN). go() resets t0, and the LED now blinks every 250 ms.
03The button is pressed. Which statement is true?
PRESS in IDLE goes to LIGHT, PRESS in LIGHT goes to IDLE, and PRESS in WARN goes back to LIGHT. Same event, different state, different arrow.
04Why does go() store t0 = millis()?
Each state's timeout is measured from the moment we entered it. Storing t0 on every transition restarts that clock, which is why a press in WARN gives a full 10 s again.
05What does break do at the end of each case?
The Arduino reference says break exits the switch statement. Without it, the code would carry on into the following case's statements.
المسرد
- State machine
- A design where the device is always in one of a few named states and moves between them when events happen.
- State
- One named situation the device can be in, such as IDLE, LIGHT or WARN.
- Event
- Something that happens and may cause a transition, such as a button press or a timeout.
- Transition
- A move from one state to another, caused by an event; an arrow in the state diagram.
- enum
- A C++ type that gives names to a list of whole-number constants: IDLE = 0, LIGHT = 1, WARN = 2.
- switch...case
- A statement that compares a variable with each case value and runs the matching case.
- Blocking
- Code that waits, such as delay(), and does nothing else meanwhile, so it can miss events.
- millis()
- An Arduino function that returns the milliseconds since the program started, as an unsigned long.
الملاحظات والمصادر
- Valvano lists what a finite state machine needs: a finite set of states with one initial state, a set of inputs, a set of outputs, and for every state and input an explicit next state. Here the inputs are the two events and the output is the LED.
- The Hardware lesson "State machines" explains Moore and Mealy machines. Our LED is set after the switch from the state (plus the 250 ms blink clock in WARN), not from the button, which is the Moore idea: outputs come from the state.
- The card shows only the switch. The whole sketch also declares the enum, go(), age() and a debounced pressed() (the "Debouncing a button" lesson, 50 ms), and sets the LED after the switch. Press checks come before timeouts, so a press always wins in the same pass.
- millis() counts milliseconds since the program started, as an unsigned long, and wraps to 0 after about 50 days. Because age() is millis() - t0 on unsigned long values, the subtraction still gives the right answer across the wrap.
- 10 s, 3 s and 250 ms are design choices for this example, not standards. The figure speeds up the long waits.
- J. W. Valvano, Embedded Systems: Shape the World, ch. 10: Finite State Machines (UT Austin)
- Arduino language reference: switch...case (source)
- Arduino language reference: millis() (source)
- Arduino language reference: pinMode() (source)
- Arduino built-in example: BlinkWithoutDelay.ino
- Arduino built-in example: Blink.ino (LED on pin 13)
- cppreference: enumeration declaration
- Arduino UNO R3 product datasheet (A000066)
اختبار يتاح بعد الخطوة الأخيرة.