|On this page…|
A Stateflow® chart that uses MATLAB® as the action language allows you to:
Use MATLAB syntax within the chart, such as for transition conditions and state actions.
Leverage the Symbol Wizard to infer size, type, and complexity for data in the chart, based on usage, instead of explicitly declaring it in the Model Explorer.
Add control flow logic, such as if-else expressions, in state actions, instead using a separate graphical function to define the control flow logic.
There are two general approaches to programming a chart:
Identify the operating modes of your system.
Identify the system interface, such as events to which your system reacts.
This tutorial uses the first approach— that is, start by identifying the operating modes of the system to program the chart.
This example shows how to build a Stateflow chart using MATLAB as the action language. The model represents a machine on an assembly line that feeds raw material to other parts of the line. This feeder behaves as follows:
At system initialization, check that the three sensor values are normal.
A positive value means the sensor is working correctly. A zero means that the sensor is not working.
If all sensor values are normal, transition from "system initialization" to "on".
If the feeder does not leave initialization mode after 5 seconds, force the feeder into the failure state.
After the system turns on, it starts counting the number of parts fed.
At each time step, if any sensor reading is 2 or greater, the part has moved to the next station.
If the alarm signal sounds, force the system into the failure state.
An alarm signal can occur when an operator opens one of the safety doors on the feeder or a downstream problem occurs on the assembly line, which causes all upstream feeders to stop.
If the all-clear signal sounds, resume normal operation and reset the number of parts fed to zero.
The feeder LED changes color to match the system operating mode— orange for "system initialization", green for "on", and red for "failure state".
Based on the description of feeder behavior, you can identify the key system attributes.
|Parallel Modes||No operating modes run in parallel. Only one mode can be active at any time.|
|Default Mode||System initialization|
In this exercise, you add a Stateflow chart to a Simulink® model that contains sensor and alarm input signals to the feeder.
Follow the exercises below to implement the model yourself. Otherwise, to open the supplied model, at the MATLAB command prompt enter:
Open the partially build model by executing the following at the MATLAB command prompt:
Save the model in your working folder.
Double-click the SensorSignals block to see the three sensor signals represented by pulse generator blocks.
The sensors signal indicates when the assembly part is ready to move to the next station.
Double-click the AlarmSignal block to see the step blocks that represent the alarm signal.
When the ALARM signal is active, the machine turns off.
Run the model to see the output of the sensor and alarm signals in the Scope block.
The upper axis shows the sensor signals. Only two sensor signals appear because two of the sensors have the same signal. The lower axis shows the alarm signal which turns the feeder off between the simulation time of 45 to 80 seconds.
Open the Stateflow Library by executing sflib at the MATLAB command prompt.
Select Chart(MATLAB) and drag it into your model.
Delete the connections from the SensorSignals subsystem to the scope and from the AlarmSignal subsystem to the scope.
Rename the label Chart (MATLAB) located under the Stateflow chart to Feeder. The model should now look like this:
Based on the system attributes previously described, there are three operating modes:
To add states for modeling the behavior of these operating modes:
Double-click the Feeder Chart to begin adding states.
Click the State Tool icon to bring a state into the chart.
Click the upper left corner of the state and type the name, InitializeSystem.
Repeat steps 2 and 3 to add two more states named On and FailState.
States perform actions at different phases of their execution cycle from the time they become active to the time they become inactive. Three basic state actions are:
|Type of Action||When Executed||How Often Executed While State Is Active|
|Entry||When the state is entered (becomes active)||Once|
|During||While the state is active and no valid transition to another state is available||At every time step|
|Exit||Before a transition is taken to another state||Once|
For example, you can use entry actions to initialize data, during actions to update data, and exit actions to configure data for the next transition. For more information about other types of state actions, see Syntax for States and Transitions.)
Press return after the InitializeSystem state name and add this text to define the state entry action:
entry: Light = ORANGE;
An orange LED indicates entry into the InitializeSystem state.
Add the following code after the FailState state name to define the entry action:
entry: Light = RED;
A red LED indicates entry in the FailState.
Add the following code after the On state name to define the entry action:
entry: Light = GREEN; partsFed = 0;
A green LED indicates entry in the On state. The number of parts fed is initialized to 0 each time we enter the On state
Add the following code to the On state after the entry action to check if there is a strong sensor signal and increment the parts fed to the next station:
during: if(any(sensors >= 2)) partsFed = partsFed + 1; end
The On state checks the sensor signal to determine if a part is ready to be fed to the next assembly station. If the sensor signal is strong (the number of sensors that are on is greater than or equal to 2), then the chart counts the part as having moved on to the next station.
The chart should now look like this figure.
Transition conditions specify when to move from one operating mode to another. When the condition is true, the chart takes the transition to the next state, otherwise, the current state remains active. For more information, see Transitions.
Based on the description of feeder behavior, specify the rules for transitions between states:
Connect a default transition to the InitializeSystem state to indicate the chart entry point.
Default Transitions specify where to begin the simulation.
Draw a transition from the InitializeSystem state to the On state:
Move the mouse over the lower edge of the InitializeSystem state until the pointer shape changes to crosshairs.
Click and drag the mouse to the upper edge of the On state. You then see a transition from the InitializeSystem state to the On state.
Double-click the transition to add this condition:
This transition condition verifies if all of the sensors have values greater than zero.
Repeat these steps to create these remaining transition conditions.
|On to FailState||[Alarm == 1]|
|FailState to InitializeSystem||[Alarm == 0]|
Draw another transition from InitializeSystem to FailState. On this transition, type the following to create the transition event:
If the sensors have not turned on after 5 seconds, this syntax specifies a transition from InitializeSystem to FailState.
Note: The syntax on this transition is an event rather than a transition condition. For details, refer to Control Chart Execution Using Temporal Logic.
The chart now looks like this figure.
Note: The outgoing transitions from InitializeSystem have a small label 1 and 2 to indicate the order in which transition segments are evaluated. If the numbers from the figure do not match your model, right click the transition and then change it by clicking on Execution Order. See Evaluation Order for Outgoing Transitions for details.
Start the simulation of your model. Errors about unresolved symbols appear, along with the Symbol Wizard.
The Symbol Wizard does not automatically add any data to your chart. It identifies the unresolved data and infers the scope of that data using the inference rules of MATLAB expressions in Stateflow actions. In the chart:
Data that is read from but not written to is inferred as input data. However, if the name of the data is in all uppercase letters, the Symbol Wizard infers the data as a parameter
Data that is written to but not read from is inferred as output data.
Data that is read from and written to is inferred as local data.
The Symbol Wizard infers the scope of the input data in your chart. However, you must fix the data scope for the partsFed Output. Follow these steps:
For the partsFed data: in the Data Scope column, select Output from the list
The Symbol Wizard now looks like this figure.
To add the data that the Symbol Wizard suggests, click OK.
Add initial values for the parameters. At the MATLAB command prompt, enter:
RED = 0;
Similarly, at the MATLAB command prompt, add the following initial values for the remaining parameters:
Return to the model and connect the inputs and outputs to their respective ports.
Start the simulation.
Double-click the Scope block to verify that the model captures the expected feeder behavior.
The upper axis shows the LED signal which varies between orange (1), green (2), and red (0) to indicate the current operating mode. The lower axis shows the number of parts fed to the next assembly station, which increases incrementally until the alarm signal turns the machine off and then resets.
In this exercise, you introduce a code generation error into your chart and troubleshoot the issue.
Open the Feeder model. Open either the one that you created in the previous exercises or the supplied model.
To open the supplied model, at the MATLAB prompt enter:
Save the model as FeederDebug in your working directory.
Add pause(3); after the entry in the InitializeSystem state.
Note: Control Chart Execution Using Temporal Logic can be used for temporal logic instead of the pause function
Run the model. The following error occurs:
Function 'pause' is not supported for code generation. Consider adding coder.extrinsic('pause') at the top of the function to bypass code generation.
The error indicates you will not be able to generate code from the model because pause is not supported for code generation.
Add coder.extrinsic('pause') before calling pause(3) in the InitializeSystem state.
The function coder.extrinsic excludes the specified function from code generation. This allows you to have the desired functionality for simulation, but not in the generated code.
For a complete list of supported functions, see Functions Supported for C/C++ Code Generation — Alphabetical List.
Simulate the model again. It runs without generating errors.
Another approach to programming the chart is to start by identifying parts of the system interface, such as events to which your system reacts.
In the previous example, when you use input data to represent an event, the chart wakes up periodically and verifies whether the conditions on transitions are valid. In this case, if ALARM == 1, then the transition to the failure state happens at the next time step. However, creating a Stateflow chart which reacts to input events allows you to react to the alarm signal when the event is triggered.
For details on when to use an event-based chart, see How Events Work in Stateflow Charts.
In the event-based approach, the system attributes to consider first are the events, inputs, and outputs.
In the following table, consider the characteristics of the event-driven Feeder Model that are different from the system based on transition conditions.
|Events||Two asynchronous events: an alarm signal and an all-clear signal|
|Inputs||Three sensor readings to detect if a part has moved to a downstream assembly station|
In this example, the Feeder model reacts to input events using a triggered chart. To open this model, at the MATLAB command prompt enter:
The chart now has only one input port on the left and an event triggered input on the top. For more information on how to create a Stateflow chart activated by events, see Activate a Stateflow Chart Using Input Events
When the ALARM signal triggers the chart, the chart responds to the trigger in that time step. If the current state is On when the alarm is triggered, then the current state transitions to FailState.
The scope output for the Event-triggered chart is in the following figure.
The upper axis shows the LED signal which varies between red (0), orange (1), and green (2) to indicate the current operating mode. The lower axis shows the number of parts fed to the next assembly station, which increases incrementally until the alarm signal turns the machine off and then resets. However, the event-based simulation feeds more parts to the next assembly station due to clock and solver differences.