We now have an idea of how our device will work, at least at the state level. What we want next is a function which will implement this behaviour for us.

On the right is an empty function which implements the state diagram above. We have used the switch construction to allow us to select appropriate operation, both in terms of a set of behaviour depending on the state of the device, but also to select the action to be performed when a particular event occurs.

When we get an event we call the function to deal with it. Note how I have given printable values for the events and states. I have also used the DEBUG technique so that I can turn on statements which will show the state of my system before and after I feed it an event. This will let me prove that it works (which is something I should always consider when I am writing the code).