Application of Finite State Machine

State machine applications, generally software control a certain peripheral, the peripheral has many states or a certain business function has multiple execution steps, the software implementation process has multiple state nodes, generally called a finite state machine, abbreviated It is FSM (Finite State Machine).

To deal with this type of problem, you can define enumeration values ​​based on states or nodes, and the name must be able to express its meaning. The main body of the software adopts the switch-case structure or the look-up table method. When a new input condition is generated, it enters the processing function, first checks the current state, and then combines the logic to enter the new state.

For example, when communicating with a certain peripheral device, there are four states: A, B, C, and D. Under normal circumstances, they are executed in the order of A-B-C. C is a normal end, and D is an abnormal end. Even with the same input, because the current state is different, the next state is also different.

fsm=void fun(input)
{
    
        
  switch(fsm)    
  {
    
            
    case:            
    if(error)            
    {
    
                    
      fsm=}            
    else            
    {
    
                    
      fsm=//异常结束            
    } 
    break;
    
    case:            
    if(error)            
    {
    
     
      fsm=//异常结束            
    }           
    else            
    {
    
    
      fsm=//正常结束           
    }       
    break;
    default:      
    break;   
  }
}

This method is easy to read and understand, but it has poor scalability. Each state change needs to modify the same function and it is easy to conflict, and it leads to a huge function. When there are more states, you can use the table lookup method to improve. Create a state and callback function table, and add a status bar to the table when expanding.

typedef struct
{
    
        
    状态;
    回调函数;
 }table;
 
table[3]={
    
    , callback1,, callback2,, callback3
}

Then void fun(input) is changed to look up the table and execute the callback function corresponding to the current state.

This is just a simple state machine processing flow. In complex situations, each state will switch to each other; corresponding to this state machine logic processing, you must first organize the flowchart , clarify the state switching relationship, and start coding after you are confident, otherwise the subsequent search for problems will Spend more time. Add notes to key positions to benefit those who will take over.

For more development skills, please follow the WeChat public account
Insert picture description here

Guess you like

Origin blog.csdn.net/chengjunchengjun/article/details/108813580