State machines
In our introductory example of cooperative multitasking, we chose two tasks that are extremely small and that do the exact same thing each time they are executed. However, tasks can get much more complicated and might require us to execute several different steps each time they are called. In other words, we need to break a big chunk of code up into small pieces. A great way to implement these more complex tasks in the cooperative multitasking framework is by writing them as state machines.
A state machine is a piece of code that keeps track of the state of the task (hence the name). Certain conditions, such as timing checks, can trigger a transition between states, which causes a bit of code to be executed. The LED blink task from the last example can easily be implemented as a state machine. This adds a few lines of code, but it makes it much more readable. In the blink task state machine, the state is the state of the LED, which is either ON or OFF. The transition...