Introduction to Stateflow with Applications

Transcription

Introduction to Stateflow with Applications
Introduction to Stateflow®
with Applications
Steven T. Karris
Orchard Publications
www.orchardpublications.com
Introduction to Stateflow®
with Applications
Students and working professionals will find
Introduction to Stateflow® withApplications to
be a concise and easy-to-learn text. It provides complete, clear, and detailed explanations of the powerful interactive graphical
design tool. All topics are illustrated with realworld examples.
This text includes the following chapters and appendices:
• The Stateflow Chart • The Stateflow Truth Table • Embedded MATLAB Functions in Stateflow
Charts • Model Coverage for Embedded MATLAB Functions • Graphical Functions • Connective
Junctions • History Junctions and Transitions • Stateflow Boxes • Mealy and Moore Charts in
Stateflow • Introduction to MATLAB • Introduction to Simulink • Masked Subsystems in Simulink
Each chapter contains several practical applications.
Steven T. Karris is the president and founder of Orchard Publications. His undergraduate and
graduate degrees are from Christian Brothers University, Memphis, Tennessee, and from Florida
Institute of Technology, Melbourne, Florida. He is a registered professional engineer in California
and Florida. He has over 30 years of professional engineering experience in industry. In addition,
he has over 30 years of teaching experience as an adjunct professor at several educational institutions, the most recent at UC Berkeley, CA.
Orchard Publications
Visit us on the Internet
www.orchardpublications.com
or email us: info@orchardpublications.com
1-9
934404-0
07-2
2
ISBN-13: 978-1
934404-0
07-1
1
ISBN-10: 1-9
$69.95 U.S.A.
Preface
This text is an introduction to Stateflow ®, for use with Simulink® and MATLAB ®. It can be
considered as an continuation of Simulink and is written for students at the undergraduate and
graduate programs, as well as for the working professional.
Although some previous knowledge of MATLAB and Simulink would be helpful, it is not
absolutely necessary; Appendix A of this text is an introduction to MATLAB, and Appendix B is
an introduction to Simulink to enable the reader to begin learning MATLAB, Simulink, and
Stateflow simultaneously, and to perform graphical computations and programming.
Chapters 1 describes the basic workflow for building Stateflow charts that are used to model
eventdriven systems, and how they work with Simulink blocks. It begins with definitions that are
essential in understanding Stateflow and its relation to Simulink and MATLAB. It continues with
the description of a demo model provided by The MathWorks™, and concludes with an example
with step−by−step procedures.
Chapter 2 describes the basic workflow for building Stateflow truth tables to form decision−
making behavior, and how it works with Simulink blocks. We discuss the Truth Table block that
can be added directly to a Simulink model, and the Truth Table that can be called from a
Stateflow Chart block.
Chapter 3 describes the procedure for adding Embedded MATLAB functions to Stateflow charts.
It begins with an introduction to Embedded MATLAB functions using an example, followed by
procedures for building a Simulink model with a Stateflow chart that calls the Embedded
MATLAB function. It concludes with a procedure for debugging Embedded MATLAB functions
in Stateflow Charts.
Chapter 4 describes the procedure for adding Embedded MATLAB functions to Stateflow charts.
It begins with an introduction to Embedded MATLAB functions using an example, followed by
procedures for building a Simulink model with a Stateflow chart that calls the Embedded
MATLAB function.
Chapter 5 describes the procedure for creating graphical functions. It begins with an introduction
to graphical functions followed by procedures for building a Simulink model to define graphical
functions and includes illustrative examples.
Chapter 6 describes the use of connective junctions to represent a decision point between
alternate transition paths for a single transition. Flow diagram notation uses connective junctions
to represent common code structures such as for loops and if−then−else constructs without the
use of states.
Chapter 7 describes the use of history junctions to represent historical decision points in the
Stateflow diagram. A description with an illustrative example is provided, and the chapter
concludes with a discussion on transitions. For easy reference, the examples presented are the
same or similar to those included in the Stateflow documentation.
Chapter 8 is a short chapter describing the use of boxes to extend Stateflow Chart diagrams. We
describe how to create a state and changing it to a box, and how to create a box and change it to
a state.
Chapter 9, the last chapter, begins with an overview of the Mealy and Moore machines, then
describes the procedure for creating Mealy and Moore charts in Stateflow, and concludes with
illustrative examples for each.
Appendix C presents an overview of masked subsystems, and a step−by−step procedure to create
custom user interfaces, i.e., masks for Simulink subsystems. It is included in this text as a quick
reference to masked subsystems in the Stateflow demos.
This text is only an introduction to Stateflow, and the author feels that with the background
gained after studying the material of this text, the reader should not have any difficulty going
through the Stateflow demos which undoubtedly are real−world examples.
This is the first edition of this title, and although every effort was made to correct possible
typographical errors and erroneous references to figures and tables, some may have been
overlooked. Accordingly, the author will appreciate it very much if any such errors are brought to
his attention so that corrections can be made before the next printing.
The author wishes to express his gratitude to the staff of The MathWorks™, the developers of
MATLAB® and Simulink® for the encouragement and unlimited support they have provided me
with during the production of this text.
Orchard Publications
www.orchardpublications.com
info@orchardpublications.com
Table of Contents
1 The Stateflow Chart
1.1
1.2
1.3
1.4
1.5
1.6
1.7
2
3
5
3−1
Introduction to Embedded MATLAB Functions ....................................................3−1
Building the Model with a Stateflow Embedded MATLAB Function ...................3−2
Programming the Stateflow Chart with an Embedded MATLAB Function.........3−11
Simulation of the Matrix Operations Stateflow Chart ..........................................3−15
Summary ...............................................................................................................3−35
Exercises for the Reader........................................................................................3−40
Solution to the End−of−Chapter Exercises ...........................................................3−42
Model Coverage for Embedded MATLAB Functions
4.1
4.2
4.3
4.4
2−1
Truth Tables in Stateflow........................................................................................2−1
Summary ................................................................................................................2−62
Exercises.................................................................................................................2−64
Solution to End−of−Chapter Exercises..................................................................2−66
Embedded MATLAB Functions in Stateflow Charts
3.1
3.2
3.3
3.4
3.5
3.6
3.7
4
Finite State Machines..............................................................................................1−1
Event−Driven Systems.............................................................................................1−2
Construction of Finite−State Machines with Stateflow..........................................1−2
Procedure for Creating a Stateflow Chart .............................................................1−11
Summary ................................................................................................................1−70
Exercise for the Reader..........................................................................................1−78
Solution to the End−of−Chapter Exercise.............................................................1−79
The Stateflow Truth Table
2.1
2.2
2.3
2.4
1−1
4−1
Introduction to Embedded MATLAB Functions ................................................... 4−1
Summary .............................................................................................................. 4−18
Exercises for the Reader....................................................................................... 4−19
Solution to the End−of−Chapter Exercises........................................................... 4−20
Graphical Functions
5−1
5.1 Introduction to Graphical Functions...................................................................... 5−1
5.2 Creating a Graphical Function............................................................................... 5−1
5.3 Subcharts .............................................................................................................. 5−10
5.4 Exporting Graphical Functions to Stateflow ........................................................ 5−17
5.5 Summary ............................................................................................................... 5−29
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
i
5.6 Exercise for the Reader ......................................................................................... 5−31
5.7 Solution to the End−of−Chapter Exercise............................................................ 5−32
6
Connective Junctions
6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
7
8
7−1
History Junction Defined....................................................................................... 7−1
The Stateflow History Junction Tool .................................................................... 7−1
Changing the History Junction Size ...................................................................... 7−2
Changing History Junction Properties................................................................... 7−5
Entering a State ..................................................................................................... 7−9
Executing an Active State ................................................................................... 7−10
Exiting an Active State........................................................................................ 7−11
Execution Order for Parallel States ..................................................................... 7−13
Transitions ........................................................................................................... 7−15
Transition Connections ....................................................................................... 7−19
Inner Transitions ................................................................................................. 7−22
Summary .............................................................................................................. 7−25
Exercise for the Reader ........................................................................................ 7−27
Solution to the End−of−Chapter Exercise........................................................... 7−28
Boxes in Stateflow
8.1
8.2
8.3
8.4
ii
The Stateflow Connective Junction Tool .............................................................. 6−1
Creating a Connective Junction ............................................................................ 6−2
Changing Connective Junction Size ...................................................................... 6−3
Changing Connective Junction Properties............................................................. 6−6
Uses of Connective Junctions ................................................................................ 6−7
Summary .............................................................................................................. 6−16
Exercise for the Reader ........................................................................................ 6−17
Solution to the End−of−Chapter Exercise ........................................................... 6−18
History Junctions and Transitions
7.1
7.2
7.3
7.4
7.5
7.6
7.7
7.8
7.9
7.10
7.11
7.12
7.13
7.14
6−1
8−1
Creating a Box.......................................................................................................... 8−1
Changing a State to a Box ....................................................................................... 8−2
Using Boxes in Stateflow.......................................................................................... 8−4
Summary .................................................................................................................. 8−6
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
9
Mealy and Moore Charts in Stateflow
9−1
9.1 Mealy Machine Defined...........................................................................................9−1
9.2 Moore Machine Defined ..........................................................................................9−3
9.3 Mealy and Moore Machines in Stateflow ................................................................9−4
9.4 Creating a Mealy Chart............................................................................................9−6
9.5 Creating a Moore Chart .........................................................................................9−10
9.6 Changing Chart Type.............................................................................................9−17
9.7 Debugging Mealy and Moore Charts .....................................................................9−17
9.8 Summary.................................................................................................................9−20
9.9 Exercises for the Reader .........................................................................................9−21
9.10 Solution to the End−of−Chapter Exercises............................................................9−22
A
Introduction to MATLAB®
A.1
A.2
A.3
A.4
A.5
A.6
A.7
A.8
A.9
A.10
A.11
B
C
MATLAB® and Simulink®................................................................................A−1
Command Window .............................................................................................A−1
Roots of Polynomials ...........................................................................................A−3
Polynomial Construction from Known Roots......................................................A−4
Evaluation of a Polynomial at Specified Values ..................................................A−6
Rational Polynomials ...........................................................................................A−8
Using MATLAB to Make Plots .........................................................................A−10
Subplots..............................................................................................................A−18
Multiplication, Division, and Exponentiation ...................................................A−18
Script and Function Files...................................................................................A−26
Display Formats .................................................................................................A−31
Introduction to Simulink®
B.1
B.2
B−1
Simulink and its Relation to MATLAB ............................................................... B−1
Simulink Demos ................................................................................................. B−20
Masked Subsystems
C.1
C.2
C.3
C.4
A−1
C−1
Masks Defined ........................................................................................................ C−1
Advantages Using Masked Subsystems.................................................................. C−1
Mask Features......................................................................................................... C−1
Creating a Masked Subsystem ................................................................................ C−2
References
R−1
Index
IN1
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
iii
Chapter 1
The Stateflow Chart
T
his chapter describes the basic workflow for building Stateflow charts that are used to
model event−driven systems, and how they work with Simulink blocks. It begins with definitions that are essential in understanding Stateflow and its relation to Simulink and MATLAB. It continues with the description of a demo model provided by The MathWorks™, and
concludes with an example with step−by−step procedures.
1.1 Finite State Machines
A finite state machine is a model describing the behavior of a finite number of states, the transitions between those states, and actions.
A state represents an operating mode of a machine, for instance, a typical household portable
space heater has four states, off, low, medium, and high.The on state is omitted because the
machine (space heater) must be on to operate in the low, medium, and high states.
An action describes the activity that is to be performed. An action can be further classified as an
entry action which is performed when entering the state, an exit action which is performed when
exiting the state, and as a transition action which is performed during a transition.
A finite state machine can be represented either by a state diagram or a state transition table.
Thus, a typical household space heater can be represented as shown in Figure 1.1, or as a state
transition table shown as Table 1.1.
State
Medium
Low
Transition
High
Off
Figure 1.1. State transition diagram for a typical finite state machine
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
1−1
Procedure for Creating a Stateflow Chart
Of all the subsystems in the model of Figure 1.2, we are most interested in the shift_logic Stateflow logic block. When we double−click on this block, we obtain the Stateflow chart shown as
Figure 1.18 below.
Figure 1.18. The shift_logic Stateflow logic block
The two dashed rectangles represent two independent modes of operation and are normally
referred to as Parallel (AND) states, and the numbers 1 and 2 indicate the execution order. The
solid rectangles within the parallel states 1 and 2 represent mutually exclusive modes of operation and are normally referred to as Exclusive (OR) states.
1.4 Procedure for Creating a Stateflow Chart
To understand the basic steps for creating a Stateflow Chart, we will present an example and we
will follow the procedure recommended by The MathWorks illustrated in the functional block
diagram shown in Figure 1.19 below.
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
1−11
Chapter 1 The Stateflow Chart
Figure 1.70. The Scope block displaying the EndingBalance output
Step 7: Debugging the Stateflow Chart
In Step (a) below we will illustrate a procedure for debugging a state inconsistency error, and
in Step (b) a procedure for debugging data range violations.
a. We save the model as Example_1_1_Debug in the same directory, we double−click the
Transfer Controller to open the Stateflow chart, and we delete the default transitions to
Overdraft Off and Savings Off states by selecting them and pressing the Delete key.
We recall that there must be a default transition at every level of Stateflow hierarchy that
has exclusive (OR) decomposition, and thus removing the default transition will cause a
state inconsistency error. With both default transitions in state TransferOn, our Stateflow
Editor window now appears as shown in Figure 1.71.
1−58
Introduction to Stateflow®with Applications
Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.71. The Stateflow Editor with missing default transitions
We open the Stateflow debugger by clicking the Debug tool
to make sure that State
Inconsistency is checked in the Error checking options panel as shown in Figure 1.72.
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
1−59
Chapter 1 The Stateflow Chart
Figure 1.72. The Stateflow Debugging window for checking State Inconsistencies
We save the chart and then we build it by clicking the Build tool
in the Stateflow
Editor in Figure 1.71, and the window opens as shown in Figure 1.73 where we observe
that Stateflow has generated two coder warnings indicated by gray bullets. These warnings
indicate that two states identified by numbers #21and #22 have no unconditional path to
a substate and that the sources of the problems are Overdraft and Savings.
To locate the offending states, in the Stateflow Builder in Figure 1.73 we double−click
the coder warnings text or we can click the link to the state numbers in the status panel at
the bottom of the Stateflow Builder dialog box in Figure 1.73. Thus, if we double−click
#21, Stateflow highlights the Overdraft state in the Stateflow Editor chart as shown in Figure 1.74. Likewise, if we double−click #22, Stateflow highlights the Savings state in the
Stateflow Editor chart.
We add the default transitions to the Overdraft state and to the Savings state in the
Stateflow Editor chart, we build the chart again, and we observe that the chart builds successfully without parser or code generation errors as shown in Figure 1.75.
1−60
Introduction to Stateflow®with Applications
Copyright©Orchard Publications
Chapter 1 The Stateflow Chart
We can speed through the rest of the simulation by unchecking all breakpoints, change the Animation Delay to 0 and click the Continue button repeatedly. We observe that when the simulation time reaches 25.5 seconds, the Stateflow Debugger window indicates that the number of
boards produced is 6,870, and that the production has changed from 0 to 1. At this time, the
AddShift.On state becomes active as shown below, because the number of boards produced is
greater than 5,000.
As we continue clicking the Continue button repeatedly, eventually the status panel at the upper
part of the Stateflow Debugger window indicates Simulink Time: 50.000000. At this time the
SWITCH signal from the Function Builder block returns to 0 and the AddShiftOff state becomes
active while the AddShiftOn state becomes inactive as shown below.
1−120
Introduction to Stateflow®with Applications
Copyright©Orchard Publications
Chapter 2
The Stateflow Truth Table
T
his chapter describes the basic workflow for building Stateflow truth tables to form decision−making behavior, and how it works with Simulink blocks. We discuss the Truth
Table block that can be added directly to a Simulink model, and the Truth Table that can
be called from a Stateflow Chart block.
2.1 Truth Tables in Stateflow
A Stateflow truth table represents logical decision−making behavior with conditions, decisions, and
actions. As in Chapter 1 where a Stateflow Chart block is inserted as a block in a Simulink model,
a Truth Table block can also be added to a Simulink model to call a truth table function. A
Truth Table block consists of a Condition Table column and two or more Decision columns
denoted as D1, D2, and so on, and an Action Table below the Condition Table with a Description column and Action columns as shown in Table 2.1 below.
TABLE 2.1 Truth Table arrangement in Stateflow
Condition Table
Description
Condition
D1
D2
D3
D4
......
A is logical 1 A == 1
T
B is logical 1 B == 1
T
C is logical 1 C == 1
T
D is logical 1 D == 1
T
..............
Action Table
Description
Action
t=1
DN
−
−
−
−
t=2
t=3
t=4
.......
The table above implements the function
t = ttable ( A, B, C, D )
In Table 2.1 above, each of the conditions entered in the Condition column must evaluate to
true (nonzero value) or false (zero value). Outcomes for each condition are specified as T (true),
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
2−1
Chapter 2 The Stateflow Truth Table
d. In the Condition Table of Figure 2.6 we make the entries shown in the Condition Table
of Figure 2.7.
Figure 2.7. The contents of the Condition Table for Example 2.1
In the Condition Table of Figure 2.7 above, each decision column D1 through D11 forms
a group of decision outcomes with the logical AND relationship into a decision. The False
(F)* and True (T) entries in decision columns D1 through D10 are in agreement with the
generic table, Table 2.2. The last decision column, D11, is referred to as the default decision column for the truth table, and covers any remaining decisions not listed in decision
columns D1 through D10. All entries in the default decision column must be indicated
with the dash (−) character and it represents a true or false condition, i.e., a don’t care condition. The default decision column must always be the last decision column.
*
We can press the space bar to toggle through the possible values F, −, and T. We can also enter these by typing them. Any
other characters are rejected.
2−8
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
Truth Tables in Stateflow
e. In the Action Table of Figure 2.6 we make the entries shown in Figure 2.8 below. We
observe that the actions X0 through X10 are those appearing in the last row of the Condition Table in Figure 2.7.
Figure 2.8. The contents of the Action Table for Example 2.1
From the dec2BCDtt1/Truth Table window of Figure 2.7 or Figure 2.8, we click on Edit
Data/Ports from the Add drop menu, and the Ports and Data Manager window appears
as shown in Figure 2.9.
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
2−9
Chapter 2 The Stateflow Truth Table
We check the validity of this model with the Manual Switch block configured as shown above,
and specifying the simulation time as 0, 1, .... 9.
2−74
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table
2. We repeat step (g).1 above for the Truth Table Editor toolbar of ttable2, and again we
are told that no errors were found.
3. In the MATLAB Command window, we enter the values X=0; Y=0; Cin=0;
4. We return to the Simulink model, we issue the simulation command, and our Simulink
model now is as shown below. We save the model as FullAdder.
5. We continue stepping through the simulation by changing the values of X, Y, and Cin
in accordance with the generic truth table of the Full adder to verify that the model
outputs the correct values for the Sum and Cout outputs.
2−90
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
Solution to End−of−Chapter Exercises
6. The Simulink model above can be improved by replacing the Constant blocks X, Y,
and Cin, with three Pulse Generator blocks, and replacing the Display blocks with
Scope blocks as shown below.
7. The waveforms of the Pulse Generator blocks and the waveforms for Sum and Cout
are shown below.
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
2−91
Chapter 2 The Stateflow Truth Table
2−92
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
Chapter 3
Embedded MATLAB Functions in Stateflow Charts
T
his chapter describes the procedure for adding Embedded MATLAB functions to Stateflow
charts. It begins with an introduction to Embedded MATLAB functions using an example,
followed by procedures for building a Simulink model with a Stateflow chart that calls the
Embedded MATLAB function. It concludes with a procedure for debugging Embedded MATLAB functions in Stateflow Charts.
3.1 Introduction to Embedded MATLAB Functions
Figure 3.1 below shows a Stateflow Chart in a Simulink model, the Embedded MATLAB function inside the Stateflow Chart, and the Embedded MATLAB function in the Editor window.
Figure 3.1. Example of a Simulink model with a Stateflow Chart that contains an Embedded MATLAB function
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
3−1
Simulation of the Matrix Operations Stateflow Chart
The functions det(A) and inv(A) are defined in MATLAB but are not included in the Embedded MATLAB Run−Time Function Library List. This list includes common functions as sqrt,
sin, cos, and others. Thus, had we issued the simulation command without defining the function
[det, inv] = matrix(A), Simulink would have issued the following warnings:
Output det must be assigned before returning from the function
Output inv must be assigned before returning from the function
Our model is now complete and it is shown in Figure 3.18 where we have named the Stateflow
Chart block Matrix Operations, and we have stretched the Display 2 block to accommodate
the nine elements of the inverse matrix after the simulation command is issued. The value of the
determinant will provide us with an indication whether the given matrix is well-behaved or is an
ill-conditioned matrix.* We save the model and we will simulate it in the next section.
Figure 3.18. The completed model for Example 3.1 prior to execution of the simulation command.
3.4 Simulation of the Matrix Operations Stateflow Chart
To set the simulation parameters, we double−click the Matrix Operations Stateflow chart in Figure 3.18, in the Stateflow Editor window from the Simulation drop menu we select Configuration Parameters, we click Solver in the left Select pane, and in the Simulation time and Solver
options panes we verify the selections shown in Figure 3.19, and we make changes if necessary.
We click OK to accept these values.
* This topic is discussed in Numerical Analysis Using MATLAB and Excel, ISBN-13: 978-1-934404-03-4
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
3−15
Simulation of the Matrix Operations Stateflow Chart
Figure 3.25. The Stateflow Editor, the Scope block, and the Stateflow Debugging windows for data observation
In the Stateflow Debugger window in Figure 3.25, we begin simulation by clicking the Start button. We observe that Stateflow displays a Block Error message for the Constant block as indicated in Figure 3.26. This is because we failed to define the elements of the matrix A in the
MATLAB Command Window before starting the simulation. Therefore, we open the MATLAB
Command Window and we enter the elements of matrix A as
A=[3 −2 0; −1 4 7; 5 8 −6];
In the Stateflow Debugger window in Figure 3.25 we click again the Start button and we
observe that it is changed to a Continue button as shown in Figure 3.27. We also observe that
the Browse Data field is now active, in the model window in Figure 3.28 the Display blocks
have been filled with zeros, and the Start command button has been replaced with the Stop
button and the Pause button .
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
3−21
Simulation of the Matrix Operations Stateflow Chart
Figure 3.28. The Simulink model of Example 3.1 at the start of simulation
We can also view this value in the MATLAB Command window by pressing the Enter key at
the command prompt and MATLAB displays
debug>>
and at the command prompt we type det and MATLAB displays the value of the determinant at
the start of the simulation.
det =
0
To see the value of the inverse of the matrix, at the MATLAB Command Window we type inv
and MATLAB displays
inv =
0
0
0
0
0
0
0
0
0
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
3−23
Chapter 4
Model Coverage for Embedded MATLAB Functions
T
his chapter describes the procedure for adding Embedded MATLAB functions to Stateflow
charts. It begins with an introduction to Embedded MATLAB functions using an example,
followed by procedures for building a Simulink model with a Stateflow chart that calls the
Embedded MATLAB function.
4.1 Introduction to Embedded MATLAB Functions
Figure 4.1 below shows an example of a Stateflow Chart in a Simulink model and Model Coverage for an Embedded MATLAB function inside the Stateflow Chart.
Figure 4.1. Example with a Stateflow Chart that contains a Model Coverage for Embedded MATLAB function
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
4−1
Chapter 5
Graphical Functions
T
his chapter describes the procedure for creating graphical functions. It begins with an introduction to graphical functions followed by procedures for building a Simulink model to
define graphical functions and includes illustrative examples.
5.1 Introduction to Graphical Functions
Stateflow defines three types of functions: truth table, Embedded MATLAB, and graphical. We
described truth table and Embedded MATLAB functions in the previous chapters. In this chapter we will discuss graphical functions.
Like the truth table and Embedded MATLAB functions, a graphical function is an extension of
Stateflow actions. We define a program once in a function, and we can call it as many times as we
need in Stateflow action language.
5.2 Creating a Graphical Function
We create a Stateflow graphical function in Stateflow diagrams with the following steps:
1. We select the graphical tool function
from the Stateflow drawing toolbar in the Stateflow
Editor window, we move the cursor inside the empty area of the Stateflow Editor, and we click
to place it near the top of the empty area. The graphical function now appears as an unnamed
object in the Stateflow Editor with a flashing text cursor as shown in Figure 5.1 below. We save
this function as graph_func_stateflow.
2. The syntax of a typical graphical function has a signature of the following form:
y = f ( x 1, x 2, … , x n )
Accordingly, in the Stateflow Editor window we define our function as
w = f ( x, y, z )
and the Stateflow Editor window now appears as shown in Figure 5.2.
3. We click the Model Explorer icon
at the top toolbar of the Stateflow Editor window and
this function now appears in the Model Explorer window shown in Figure 5.3.
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
5−1
Chapter 5 Graphical Functions
In the graphical function rectangle shown in Figure 5.6, we enter the condition action of the
function signature Z=f(R,XL,XC), a default transition with a terminating junction, the equation
for the impedance Z = sqrt ( R^2+(XL-XC )^2) , and the default transition for the function argument Zout = f ( Rin, XLin, XCin ) . We save this function as impedance_stateflow, and the Stateflow Chart Editor now appears as shown in Figure 5.7.
Figure 5.7. The Stateflow Chart Editor with the graphical function
Next we click the Model Explorer tool
and the Model Explorer window appears as shown in
Figure 5.8 where with the Chart highlighted in the Model Hierarchy pane (left), the Contents
pane (right) shows the function arguments Rin , X L , and X C as inputs, and the return value
Zout as the output.
5−6
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
Chapter 5 Graphical Functions
5.7 Solution to the End-of-Chapter Exercise
As a first approximation, we use the MATLAB plot command to plot y versus x .
x=-1:0.01:5; y=cos(2.*x)+sin(2.*x)+x-1; plot(x,y); grid
The plot above reveals that one root is at x = 0 , and this can be easily verified by inspection of
the given function. The second root is near the vicinity x = 1.3 , and the third near the vicinity
x = 2.2 . Following the procedure of Example 5.2, we begin by typing sfnew at the MATLAB
command prompt and in the model that appears we add a Constant block from the Commonly
Used Blocks Library, two Reshape blocks from the Math Operations Library, and two Display
blocks from the Sinks Library. Our model is as shown below.
5−32
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
Chapter 6 Connective Junctions
Figure 6.11. Flow diagram notations for Example 6.2
In the flow diagram above, the transition A to B occurs if state A is active, if event e_one occurs,
and [c_one] is true. The transition A to C occurs if state A is active, if event e_one occurs, and
[c_two] is true. The transition A to D occurs if state A is active and event e_one occurs. Since we
did not specify [c_three], the transition condition is not [c_one] and not [c_two].
Example 6.3
This is a connective junction example with a self−loop.
In some situations, the transition event occurs but a condition is not met. No transition is taken,
but an action is generated. We can represent this situation by using a connective junction or a
self−loop transition (transition from state to itself).
Let us consider the flow diagram notations in Figure 6.12.
Figure 6.12. Flow diagram notations for Example 6.3
In the flow diagram on the left, if state A is active when event e occurs and the condition [c1] is
met, the transition from state A to state B occurs, and generates action a1. The transition from
state A to state A is valid if event e occurs and [c1] is not true. In this self−loop transition, the system exits and reenters state A, and executes action a2.
In the equivalent representation on the right, the use of a connective junction makes it unnecessary to specify the implied condition [~c1] explicitly.
6−10
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
Uses of Connective Junctions
Example 6.4
This is a connective junction example with and For Loops.
Let us consider the flow diagram notations in Figure 6.13.
Figure 6.13. Flow diagram notations for Example 6.4
This flow diagram shows a combination of flow diagram notation and state transition notation.
Self−loop transitions to connective junctions can be used to represent for loop constructs.
In state A, event e occurs. The transition from state A to state B is valid if the conditions along
the transition path are true. The first segment of the transition does not have a condition, but
does have a condition action {i=0}, and this condition action is executed. The condition on the
self−loop transition is evaluated as true and the condition actions {i++;func1()} execute. The
condition actions execute until the condition [i<10] is false. The condition actions on both the
first segment and the self−loop transition to the connective junction effectively execute a for
loop (for i values 0 to 9 execute func1()). The for loop is executed outside the context of a state.
The remainder of the path is evaluated. Because there are no conditions, the transition completes at the destination, state B.
Example 6.5
This is a flow diagram notation example.
Let us consider the flow diagram notations in Figure 6.14.
Figure 6.14. Flow diagram notations for Example 6.5
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
6−11
Chapter 7
History Junctions and Transitions
T
his chapter describes the use of history junctions to represent historical decision points in
the Stateflow diagram. A description with an illustrative example is provided, and the
chapter concludes with a discussion on transitions. For easy reference, the examples presented are the same or similar to those included in the Stateflow documentation.
7.1 History Junction Defined
A history junction records a previously active state in which it is resident. It is used to represent
historical decision points in the Stateflow diagram. The decision points are based on historical
data relative to state activity. Placing a history junction in a superstate* indicates that historical
state activity information is used to determine the next state to become active. The history junction applies only to the level of the hierarchy in which it appears.
7.2 The Stateflow History Junction Tool
Figure 7.1 is our familiar Stateflow Editor window, and when we place the mouse cursor over the
History Junction tool
, its name appears at the bottom of the window.
To create a history junction, we do the following:
1. In the diagram toolbar, we click the History Junction tool
.
2. We move the cursor into the diagram editor.The cursor takes on the shape of a history junction as shown in Figure 7.2. We click to place a connective junction in the desired location in
the drawing area.
* We recall from Chapter 1 that objects in Stateflow exist in a hierarchy and states can contain other states referred to as substates, and can be contained by other states referred to as superstates.
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
7−1
Chapter 9
Mealy and Moore Charts in Stateflow
T
his chapter begins with an overview of the Mealy and Moore machines, then describes the
procedure for creating Mealy and Moore charts in Stateflow, and concludes with illustrative examples for each.
9.1 Mealy Machine Defined
In the theory of computation, a Mealy machine is a finite state machine that generates an output
based on its current state and an input. This means that the state diagram will include both an
input and output signal for each transition edge.
Example 9.1
This is a Mealy machine example.
Let us consider the state table below denoted as Table 9.1.
TABLE 9.1
Present State
Input
Q1
Q0
x
0
0
0
0
0
0
Next State
Output
n+1
y
0
1
0
1
1
1
1
1
0
1
0
0
0
1
1
0
0
1
1
0
0
1
1
0
1
0
1
0
1
1
1
1
0
0
0
0
1
1
1
1
0
1
n
n
n+1
Q1
Q0
We can represent the state table above with the timing diagram shown in Figure 9.1 below.
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
9−1
Chapter 9 Mealy and Moore Charts in Stateflow
CP
0
1
0
1
0
1
0
1
0
n
0
0
1
1
0
0
1
1
0
n
0
0
0
0
1
1
1
1
0
1
1
0
0
1
1
0
0
0
0
1
1
0
1
0
0
1
0
0
1
0
1
0
1
0
1
0
x
Q0
Q1
n+1
Q0
n+1
Q1
y
0
Figure 9.1. Timing diagram for state table Table 9.1
The Mealy machine for the state table in Table 9.1 and timing diagram in Figure 9.1 is shown in
Figure 9.2 below.
00
01
11
10
Figure 9.2. The Mealy machine for Example 9.1
In the state diagram in Figure 9.2, the numbers inside the states represented by the circles are the
four states of a synchronous counter that counts clockwise from 00 to 01 to 10 to 11 to 00 and
repeats whenever the input signal x is 0 , and counts counterclockwise from 11 to 10 to 01 to
00 to 11 and repeats whenever the input signal x is 1 .
9−2
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
Moore Machine Defined
In a Mealy machine such as that of Figure 9.2, it is customary to indicate that the output y is
dependent on the current state, e.g., 00 and the input x by expressing the transition from one
state to another as x ⁄ y and placing it near the transition arrow. For example, for the transition
from state 00 to 01 the arrow in the clockwise direction has the designation 0 ⁄ 0 , and for the
transition from state 01 to 00 the arrow in the counterclockwise direction has the designation
1 ⁄ 1.
9.2 Moore Machine Defined
In contrast to the Mealy machine whose output depends on its current state and input, the output of a Moore machine depends only on the machine's current state.
Besides showing the state inside the circle representing a state, Moore machines show also the
n
n
outputs inside the circle. Thus, for a two−bit Moore machine, the state is represented as Q 1 Q 0 ,
the output is represented as y 1 y 0 , and the state and output are separated by a slash (/). For
instance, in the designation 10 ⁄ 01 , 10 indicates the state, and 01 indicates the output.
Example 9.2
This is a Moore machine example.
Let us consider the Moore machine shown in Figure 9.3.
00 ⁄ 01
01 ⁄ 10
11 ⁄ 00
10 ⁄ 11
Figure 9.3. Moore machine for Example 9.2
Introduction to Stateflow®with Applications
Copyright © Orchard Publications
9−3
Appendix C
Masked Subsystems
T
his appendix presents an overview of masked subsystems, and a step−by−step procedure to
create custom user interfaces, i.e., masks for Simulink subsystems.
C.1 Masks Defined
A mask is a custom user interface for a subsystem. A masked subsystem conceals the subsystem's
contents, and it appear to the user as an atomic block with its own icon and parameter dialog box.
However, a masked subsystem provides only graphical, not functional, grouping. We can create a
mask for any Simulink subsystem using the Mask Editor.
C.2 Advantages Using Masked Subsystems
A masked subsystem allows us to
1. Replace the parameter dialogs of a subsystem and its contents with a single parameter dialog
with its own block description, parameter prompts, and help text.
2. Replace a subsystem's standard icon with a custom icon that shows its purpose.
3. Prevent accidental modification of subsystems by concealing their contents behind a mask.
4. Placing a masked subsystem in a library. We can also mask S−Function and Model blocks.
C.3 Mask Features
Masks can include any of the following features:
Mask Icon − The mask icon replaces a subsystem's standard icon, i.e., it appears in a block
diagram in place of the standard icon for a subsystem block. Simulink uses
MATLAB code that we supply to draw the custom icon. We can use any
MATLAB drawing command in the icon code.
Mask Parameters − Masked subsystems allow us to define a set of user−specified parameters.
Simulink stores the values of these parameters in the mask workspace as the
value of a variable whose name you specify. These associated variables allow
us to link mask parameters to specific parameters of blocks inside a masked
subsystem.
Introduction to Stateflow® with Applications
Copyright © Orchard Publications
C−1
Creating a Masked Subsystem
Figure C.9. The Function Block Parameters window with the values of the constants
With the variables defined as above, the masked subsystem implements the quadratic equation
2
y = x – 5x + 6
and the roots of this equation are x 1 = 2 and x 2 = 3 . Our model is tested for the first root as
shown in Figure C.10.
Figure C.10.
The Mask Editor also contains the Initialization tab that allows us to enter MATLAB commands
that initialize the masked subsystem, and the Documentation tab that lets us define or modify the
type description and help text for a masked subsystem. These tabs are shown in Figures C.11 and
C.12, and are not used in this example.
Introduction to Stateflow® with Applications
Copyright © Orchard Publications
C−9
Index
Symbols
D
% (percent) symbol in MATLAB A-2
data icon 3-6
data points in MATLAB A-14
data range 1-64
data range violation 1-58
Debug tool 1-48, 3-18
decibels A-13
decision 2-1, 2-2
decision columns 2-1, 2-2
decision coverage 4-2
decomposition 1-26
deconv in MATLAB A-6
default A-12
default color A-15
default decision 2-2
default decision column 2-8
default line in MATLAB A-15
default marker in MATLAB A-15
default transition 1-14, 7-16
default transition 7-16
Default Transition tool 1-37, 3-4
default transitions 1-37
delay 3-18
demo in MATLAB A-2
description 2-1
Disable all field 3-24
Display block in Simulink B-18
display formats in MATLAB A-31
dot multiplication operator in MATLAB A-20
during action 1-14
A
abs(z) in MATLAB A-23
action 1-1
action table 2-1
actions 2-1
algebraic constrain blocks in Simulink B-18
All Data (Current Chart) in Simulink 3-22
angle(z) in MATLAB A-23
animation in Simulink 3-16
animation delay 1-55
animation of Stateflow charts 1-47
autoscale icon in Simulink B-12
axis in MATLAB A-16
B
backtracking behavior 6-14
block error 1-67
blocking 3-40
box in Stateflow 8-1
box in MATLAB A-12
box tool in Stateflow 8-1
breakpoints 1-49, 3-19
Browse Data 1-50, 3-19
Build tool 1-60
C
exit in MATLAB A-2
exit action 1-1
exiting an Active State 7-11
explicit ordering 1-29
explicit ordering of parallel states 7-14
exporting graphical functions
to Stateflow 5-17
F
figure window in MATLAB A-13
finite state machine 1-10
Flip Block command in Simulink B-11
for 4-18
for loops 6-11
format A-31
fplot in MATLAB A-27
function block parameters B-10
function file in MATLAB A-26
function header 4-18
fzero in MATLAB A-26
G
Gain block in Simulink B-18
graphical functions 5-1
graphical tool function 5-1
grid in MATLAB A-12
gtext in MATLAB A-13
guarding a transition 1-39
H
E
changing a box to a state 8-1
changing a state to a box 8-1
Chart Entry 1-49, 3-19
Chart Entry 3-19
Classic Machine in Stateflow 9-4
clc in MATLAB A-2
clear in MATLAB A-2
code generation errors 1-60
Coder Options 1-48, 3-18
column vector A-19
command screen in MATLAB A-1
Command Window in MATLAB A-1
commas in MATLAB A-8
comment line in MATLAB A-2
Commonly Used Blocks in Simulink B-7
complex conjugate A-4
complex numbers in MATLAB A-3
condition 1-2, 1-14, 7-18
condition action 7-18
condition table 2-1
conditions 2-1
configuration parameters 1-46, 3-15, B-12
Connective Junction 6-1
Contents pane 3-6, B-7
Continue button 1-56, 3-21
Continue Debugging 3-33
conv in MATLAB A-6
Creating a Mealy Chart 9-6
Creating a Moore Chart 9-10
Editor window in MATLAB A-1
Editor/Debugger in MATLAB A-1
electric field strength example 3-40
element-by-element division and
exponentiation in MATLAB A-21
element-by-element multiplication
in MATLAB A-18, A-20
eM functions 3-4
Embedded MATLAB Editor 3-7
Embedded MATLAB function 3-1
Embedded MATLAB Function tool 3-3
Entering a State 7-9
entry action 1-1, 1-14
eps in MATLAB A-22
Erlang 3-40
Erlang B 3-40
Erlang B model 3-41
Erlang C 3-40
Erlang C model 3-41
error checking options 1-59
event 1-2, 1-14, 7-17
event driven systems 1-2
event properties dialog box 1-44
event trigger 7-17
exclusive (OR) state 1-12
executing an Active State 7-10
execution order 1-12, 1-27
execution Order for Parallel States 7-13
history junction 7-1
History Junction tool 7-1
I
If 4-18
if-then-else 6-13
imag(z) in MATLAB A-23
implicit ordering 1-29
increments between points in MATLAB A-14
inner transition 7-22
input argument 3-6
L
Launch Model Explorer tool 1-68
lims = in MATLAB A-27
linspace in MATLAB A-14
local data 9-7
log in MATLAB A-13
log(x) A-13
log10(x) in MATLAB A-13
log2(x) in MATLAB A-13
loglog in MATLAB A-13
loglog(x,y) in MATLAB A-13
M
mask C-1
IN1
Mask Editor C-1
mask icon C-1
mask parameters C-1
masked subsystem 1-8, C-1
Math Operations B-11
MATLAB Demos A-2
MATLAB’s Editor/Debugger A-1
matrix multiplication in MATLAB A-19
Mealy machine 9-1
Mealy machines in Stateflow 9-4
mesh(x,y,z) in MATLAB A-17
meshgrid(x,y) in MATLAB A-17
m-file in MATLAB A-1, A-26
Model Coverage for an Embedded
MATLAB function 4-1
Model Explorer 3-5
Model Explorer tool 5-6
Model Hierarchy pane 3-6
Modified Condition Decision Coverage 4-18
Moore machine 9-3
Moore machines in Stateflow 9-4
multiple connective junctions 6-2
N
NaN in MATLAB A-26
O
observer state 1-28
order of execution 1-27
output argument 3-6
P
Parallel (AND) state 1-12
parser errors 1-60
Pause button 3-21
plot in MATLAB A-10, A-15
plot3 in MATLAB A-15
Poisson 3-40
Poisson model 3-41
polar plot in MATLAB A-23, A-24
poly in MATLAB A-4
polyder in MATLAB A-7
Polynomial construction from known
roots in MATLAB A-4
polyval in MATLAB A-6
power density example 3-40
progress bar in Simulink 3-24
Q
quit in MATLAB A-2
R
real(z) in MATLAB A-23
roots in MATLAB A-3
roots of polynomials in MATLAB A-3
round(n) in MATLAB A-24
row vector in MATLAB A-3, A-19
running Simulink B-7
run-time activities 3-19
IN2
S
U
Scope block in Simulink B-12
script file in MATLAB A-26
semantics 9-7
semicolons in MATLAB A-8
semilogx in MATLAB A-12
semilogy in MATLAB A-12
sfprj 1-50
sfprj 3-20
sfun 1-48
sfun 3-18
signature label 2-17
signature return values 3-45
simout To Workspace block B-13
simulation diagnostics 1-66
Simulation drop menu B-12
simulation start icon B-12
Simulation Target 1-47, 3-16
Simulink icon B-7
Simulink Library Browser B-8
Sinks library B-18
Start button 3-21
Start command button 3-21
Start simulation B-12
Start Simulation tool 3-27
state 1-1
state action 1-14
state entry 1-49
state inconsistency error 1-58
State tool 1-24
Stateflow Builder 1-60
Stateflow Debugging 1-48
Stateflow Debugging 3-18
Stateflow Editor 1-24
Stateflow Editor chart 1-12
Stateflow Target Builder 3-16
State-Space block B-12
Step In tool 3-27
Step Out tool 3-30
Step tool 3-27
Stop button 3-21
string in MATLAB A-16
subchart 5-10
subcharted state 5-10
subplot(m,n,p) in MATLAB A-18
switch 4-18
User specified state/transition
execution order 1-30
using boxes in Stateflow 8-1
T
Target Builder 1-48, 3-18
text A-14
title(‘string’) in MATLAB A-12
Traffic Light example with a Moore
state machine 9-14
transition action 1-1, 7-18
transition connections 7-19
transitions 7-15
Tree Pane B-7
trigger port 1-42
Truth Table block 2-1
V
valid transitions 7-18
Vending Machine example with a
Mealy state machine 9-8
W
while 4-18
X
xlabel in MATLAB A-12
Y
ylabel in MATLAB A-12

Similar documents

StateFlow Hands On Tutorial

StateFlow Hands On Tutorial ƒ State transitions caused by occurrence of  asynchronous discrete events ƒ Parallel execution of multiple systems

More information

STATEFLOW

STATEFLOW Creating States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Moving and Resizing States . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Substates . . ....

More information