state machines

Status
Not open for further replies.

floating.

Well-known member
I wonder what's the best way to implement state machines on the Teensy.

I started with a switch statement that was initially around 100 - 150 lines or so. But due to additional requirements, creeping features, plus error checking/handling, it's over 700 lines now, and I wonder if it would be better to switch to function pointers, or some other method that would eliminate that big switch(){} because it's a royal PITA to work with that.

The high level (logical) state machine contains only 5 states: ON, OFF, INIT, POWERDOWN, and FAIL where INIT stands for the OFF -> ON transition and POWERDOWN stands for the ON -> OFF transition. The low level state machine has 20+ states with most of the growth coming from the breakup of INIT and POWERDOWN states, plus various error handling/retry states not indicated in the high level description.

Is there any disadvantage to use function pointers in Arduino?
Is there any other method aside from the two I already mentioned that could be used to efficiently implement a state machine while having easily maintainable code?

HW & SW: T3.2, Arduino 1.8.4, Teensyduino 1.41
 
Vague hand-waving follows.

State machines should not be a problem for 'moderately' sized code. Have done some state machines with T3.1s and T3.2s, but do not directly use the arduino system. That is, not certain how you would know where stuff is, so ability to discern a memory issue not known.

For FPs, you will need to determine if you want pointers to methods (C++), or pointers to functions (C), as they become very different animals after the compiler eats your code. For C-only stuff, simple FPs should be easy to read, easy to maintain, and are typically faster than going through the switch statement.

Would suppose that if the function that does the state transition stuff does anything else other than decode the event and determine the next state, your overhead would tend to resemble the traditional switch() state machine. Remember, the code that is called for each iteration must not have any overhead that is specific to only a particular state transition, otherwise, much slower.
 
Aside from having relatively small amounts of RAM, C++ and C on the Teensy are both pretty normal.

I'm a fan of arrays of function pointers or objects for state machines. In addition to being concise, being data-driven makes it easier to write test automation.

The question of how best to code state machines has been around for many decades. If you search, you'll find plenty of sage advice and some clever coding tricks.
 
Status
Not open for further replies.
Back
Top