What you’ll learn
- How to turn graphical state-machine models into C, C++, C#, or Java code.
- Why using a tool like Visual State is better than building a state machine in source code.
Artificial intelligence and machine learning tends to garner the limelight these days, but programming techniques like state machines remain an extremely useful tool. They often provide a model or requirements.
Turning that into an application becomes an easier task when using a product like IAR Systems’ Visual State, which now runs on Windows and Linux. The new cross-platform hosting gives Linux-based programmers the ability to turn state-machine diagrams into code, thereby reducing coding errors due to translation.
With Visual State’s graphical interface, state-machine models can be created using a familiar drag-and-drop approach (see figure). These models can be turned into C, C++, C#, or Java source code. In the past, Linux-based developers could do this in Windows and move the source code to their development system, but that tends to be annoying at best.
State machines are very useful for event-driven applications like many embedded applications. Transitions can be initiated by changes detected in the environment via sensors.
Though it’s possible to build a state machine in C source code, it’s often a collection of switch or conditional statements. This is what Visual State would generate, but the state transitions tend to get hidden in the text clutter, whereas a graphical presentation preserves them while hiding the details. The graphical version is easier to present and understand.
Safety standards like ISO 26262 and IEC 61508 are process-oriented. Using a tool like Visual State allows for movement of an idea, in the form of the state-machine model, to code, eliminating the human factor in the translation.
Tools like Visual State become more important as the size and complexity of a system grows. It’s easy to hand-code a state machine with a dozen states and a few status and control functions. However, dealing with hundreds of states can be daunting and error-prone, especially if changes are being made to the model that then need to be reflected in the source code and program testing.