Skip to content

State Machines

Published On:
Sep 11, 2024
Last Updated:
Sep 11, 2024

State Machines (single process)

State machines are coding structures/methodologies to write the top-level code which performs the high level control of your program. State machines are essential for any thing but the most simple of programs, as they organise the code, improve the readability, and make it easy for the code to be changed. A state machine is based on the theory that a program will rest in certain states, and that particular inputs will cause the program to change into another state.

Sequential logic theory (the subject which involves these state machines) says that if the combination of the inputs and the state which the program is in determines the outputs it is a Mealy state machine. If just the state determines the outputs, then it is a Moore state machine. Usually however, when writing a state machine in C for a program, you don’t have to strictly follow these rules, as you will find that it can make unnecessary complications to your code.

For the basics, check out the A Switch Statement State Machine page. This shows you how to write a simple state machine using a switch statement.

Go to the A Function Pointer State Machine page for a worked example on how to write a moderately powerful state machine.

There is software out there that lets you convert graphical state machine diagrams into usable code. One popular one is the QP state machine framework and the QM modelling tool (http://www.state-machine.com/).

Child Pages