Siddharth Sharma, MathWorks
Build and simulate a state machine.
Let us get started with the Stateflow modeling environment to develop and simulate decision making systems. To access Stateflow blocks, click the Library Browser icon in Simulink and navigate the Stateflow block library. The Stateflow block library contains blocks to model state diagrams, state transition tables, and truth tables.
To add a state diagram, drag the chart block into the Simulink Editor. Let us design a system that switches between two states based on the value of an input, u. For this example, I added the sine wave block to provide the input u and the scope block to view signal values. Both blocks can be found in the Simulink block library.
Double click on the chart block to open the Stateflow editor. In this editor, you develop state machines by dragging graphical objects like states and junctions from the palette on the left. For our example, drag the state object and change its name to on.
Similarly, create another state object, off. This system should transition from the state on to off when the value of the input, u, becomes less than 0. You can model transitions between states by connecting them with the transition object. This transition should be taken when u is less than 0.
In Stateflow, state machine syntax like brackets are added automatically. Draw another transition from the state off to on which is active when u becomes greater than 0. Place a default transition onto the state on to define which state the system should start in.
To perform actions and states, type the commands in the states directly. In our example, we will send an output of 1 to Simulink when the system enters the state on and an output of minus 1 when it enters off. The keyword, "entry," is added automatically, and marks that this action executes as soon as the state is entered.
To learn more about objects and keywords in Stateflow, right click on the object and select help. Automatic keyword additions and tab completion help you improve your productivity during development. When you run the state machine, Stateflow identifies the variables used in the diagram and suggests their scope based on usage.
In our example, since u is only being read from, it is suggested as an input. And since y is only being written to, it is suggested as an output to Simulink. I can of course, change the scope of the variables if needed.
Notice that in the Simulink editor, the hart block now has an input port and an output port. Connect the Stateflow chart with the input and output. You are now ready to run the state machine and visualize its response.