State Machines
State machines are simple constructs used to perform several activities, usually in a sequence. Many real-life systems fall into this category. For example, the operation of a washing machine or a dishwasher is easily described with a state machine construct.
Perhaps the simplest method of implementing a state machine construct in C is to use a switch-case statement. For example, our temperature monitoring system has three tasks, named Task 1, Task 2, and Task 3 as shown in Figure 10.1. The state machine implementation of the three tasks using switch-case statements is shown in Figure 10.2. The starting state is 1, and each task increments the state number by one to select the next state to be executed. The last state selects state 1, and there is a delay at the end of the switch-case statement. The state machine construct is executed continuously inside an endless for loop.
State machines, although easy to implement, are primitive and have limited application. They can only be used in systems which are not truly responsive, where the task activities are well-defined and the tasks are not prioritized.
Moreover, some tasks may be more important than others. We may want some tasks to run whenever they become eligible. For example, in a manufacturing plant, a task that sets off an alarm when the temperature is too hot must be run. This kind of implementation of tasks requires a sophisticated system like RTOS.