Книга: Advanced PIC Microcontroller Projects in C

10.1 State Machines

10.1 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.


Figure 10.1: State machine implementation

for (;;) {

 state = 1;
 switch (state) {
 CASE 1:
  implement TASK 1
  state++;
  break;
 CASE 2:
  implement TASK 2
  state++;
  break;
 CASE 3:
  implement TASK 3
  state = 1;
  break;
 }
 Delay_ms(n);
}


Figure 10.2: State machine implementation in C

In many applications, the states need not be executed in sequence. Rather, the next state is selected by the present state either directly or based on some condition. This is shown in Figure 10.3.

for (;;) {

 state = 1;
 switch (state) {
 CASE 1:
  implement TASK 1
  state = 2;
  break;
 CASE 2:
  implement TASK 2
  state = 3;
  break;
 CASE 3:
  implement TASK 3
  state = 1;
  break;
 }
 Delay_ms(n);
}


Figure 10.3: Selecting the next state from the current state

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.

Оглавление книги


Генерация: 0.703. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз