State machines in C

前端 未结 9 1722
一整个雨季
一整个雨季 2021-01-30 07:34

What is the best way to write a state machine in C?
I usually write a big switch-case statement in a for(;;), with callbacks to re-enter the state machine when an external

9条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 08:26

    I use function pointers and a 2d look-up table where I use the state for one parameter and the event as the other.

    I use excel (or any spreadsheet tool) to map a function to every state/event combination.

    When an event occurs, I que it up, so then I have something that looks like this

    int main(void)
    {
        StateList currentState = start_up;
        EventList currentEvent;
    
        uint8_t stateArray[STATE_COUNT][EVENT_COUNT];
    
        InitializeStateArray(stateArray);
        InitializeEventQue();
    
        while(1)
        {
            currentEvent = GetPriorityEvent();
            currentState = (StateList)(*(stateArray[currentState][currentEvent]))();
        }
        return 1;  //should never get here
    }
    

    This method essentially forces the developer to consider all possible events in each state, and in my experience makes debugging a little easier.

提交回复
热议问题