Once again, I am going to look at a topic helpfully suggested by my colleague Rizwan Rasheed. Unless you have used UML, or a similar tool/methodology, you may not have encountered state machines.
Although they are the basis of some formal methodologies, the concept of a state machine can be used by itself as an approach to program design, which, IMHO, is particularly appropriate to many embedded applications …
When I first heard the term, I was confused by the word “machine”. Of course, we are not talking about a mechanical device at all, but a conceptual one. The concept is quite simple and can be summed up in a few statements:
- At any time a system is in a particular state.
- Specific, precisely-defined events can result in the system moving to another state.
- A sequence of actions may be performed on entry of a new state.
A “system” could be anything, but we are only really concerned with software. However, for an embedded system, taking a more holistic view – i.e. software and hardware – might lead to better design.
The usual tool that is applied to designing systems is a state transition diagram. Each state is represented by a box, which may contain a description of the entry actions, and transitions between states are represented by arrows/lines.
To illustrate the concept, I will talk about a commonly used example; a microwave oven.
- The starting state is “door closed, oven off”. There are 2 events that can trigger transitions out of this state: opening the door or starting the oven.
- If the state becomes “door open”, the entry actions might be to turn off the magnetron [to be sure!] and turn on the light. The only transition could be back to “door closed, oven off”, when the entry action would be to turn off the light.
- If the state becomes “cooking”, the entry actions might be to turn on the magnetron and the light. The possible triggers for a state transition might be the user stopping the microwave or opening the door.
Hopefully, you get the idea.
To me, the attraction of thinking in terms of states is that it maps well onto the usage of many embedded devices. The stimulus to state transition is commonly a user action, so a clean design can come out of careful consideration of what a user might [want to] do in any given situation. A state transition diagram is also a concise and precise way to describe the [required] functionality of a system and can map directly on to the implementation, thus increasing the likelihood that the product will behave in the way the designer intended.