We’ve actually already used state when we built our adder.
The adder’s output normally obeys the truth table .
However, when the carry is active, the output’s truth table becomes instead.
In other words, the adder’s behaviour depends on its current state. The adder has 2 states, which we might call normal mode and carry mode.
state machine
The truth tables above don’t fully describe how the adder works. We need to also describe how it transitions between states:
input | normal | carry |
---|---|---|
00 | 0 | 1 ⇒ normal |
01 | 1 | 0 |
10 | 1 | 0 |
11 | 0 ⇒ carry | 1 |
This description is called a state machine.
As an example of a more complex state machine, suppose we’re programming NPCs (non-playable characters) for a game like the Sims. To make them behave realistically in their daily routine, we might use a state machine:
event | asleep | awake | … |
---|---|---|---|
alarm goes off | ⇒ awake | (no action) | … |
bedtime | (no action) | ⇒ asleep | … |
doorbell rings | (no action) | answer the door | |
feeling hungry | (no action) | make dinner | |
… | … | … | … |
We could potentially have hundreds of different states, with rules for how our NPC behaves in each.
State machines will be a useful tool when we build devices that have to switch between multiple stages of operation.
persistent state
Our adder only stores state for a single step. In general, however, we’ll want to store state for an indefinite amount of time. This will let our devices:
- save intermediate results of complex operations
- remember our inputs
- follow programs
Next, we’ll look at more general ways to store state.
continue