Language
State machines
Describe behaviour as states and the events that move between them. The compiler draws the diagram and checks every state can be reached.
When a device behaves differently depending on what’s happened so far, such as a door that’s locked, unlocked or alarmed, a state machine is easier to read than flags and ifs.
hardware {
pin relay: Output = 4
pin button: PullUpInput = 23
}
var request: bool = false
var failures: int = 0
every 50ms {
if button.is_pressed() {
request = true
}
}
machine door {
initial state locked {
enter { relay.off() }
on request [failures < 3] -> unlocked { request = false }
on failures >= 3 -> alarm
}
state unlocked {
enter { relay.on() }
exit { log("door", "relocking") }
after 10s -> locked
}
state alarm {
enter { log("door", "ALARM") }
after 30s -> locked { failures = 0 }
}
}Try it. Press Check, then change
after 10s -> lockedtoafter 10s -> lockd. Every target has to be a state of the machine.
States
A machine is in exactly one state at a time. It starts in the state marked initial, or the first one if none is marked.
enter { … }runs each time the machine arrives in the state.exit { … }runs each time it leaves.- Anything else in the state runs while the machine is in it.
Transitions
| Transition | Moves when |
|---|---|
on condition -> target | the condition is true |
after 10s -> target | the machine has been in the state that long |
Either can have a guard in square brackets, which must also hold for the move to happen, and an action block that runs on the way:
on request [failures < 3] -> unlocked { request = false }On a move, the action runs first, then the old state’s exit, then the new state’s enter.
When the condition is just a bool variable, as with on request, taking the transition sets it back to false, so one request makes one move.
What the compiler checks
- Every target is a state in the machine.
- Every state can be reached from the initial one. A state nothing leads to gets a warning, since it’s usually a typo or a forgotten transition.
aftertakes a duration with its unit.
In Volt IDE and the playground, the State machines view draws each machine as a diagram as you type, so you can see the transitions you wrote.