Stateflow Book

Embed Size (px)

Citation preview

  • 8/2/2019 Stateflow Book

    1/38

    Orchard Publicationswww.orchardpublications.com

    Introduction to Stateflowwith Applications

    Steven T. Karris

  • 8/2/2019 Stateflow Book

    2/38

    $69.95 U.S.A.ISBN-13: 978-1-934404-07-2

    Orchard Publications

    Visit us on the Internetwww.orchardpublications.com

    or email us: [email protected]

    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 insti-tutions, the most recent at UC Berkeley, CA.

    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 inStateflow Introduction to MATLAB Introduction to Simulink Masked Subsystems in Simulink

    Each chapter contains several practical applications.

    Students and working professionals will find

    Introduction to Stateflow withApplications tobe a concise and easy-to-learn text. It pro-

    vides complete, clear, and detailed explana-tions of the powerful interactive graphical

    design tool. All topics are illustrated with real-

    world examples.

    IntroductiontoStateflowwithApplications

    ISBN-10: 1-934404-07-1

  • 8/2/2019 Stateflow Book

    3/38

    Preface

    This text is an introduction to Stateflow , for use with Simulink and MATLAB . It can beconsidered as an continuation of Simulink and is written for students at the undergraduate andgraduate programs, as well as for the working professional.

    Although some previous knowledge of MATLAB and Simulink would be helpful, it is notabsolutely necessary; Appendix A of this text is an introduction to MATLAB, and Appendix B isan introduction to Simulink to enable the reader to begin learning MATLAB, Simulink, andStateflow simultaneously, and to perform graphical computations and programming.

    Chapters 1 describes the basic workflow for building Stateflow charts that are used to modeleventdriven systems, and how they work with Simulink blocks. It begins with definitions that areessential in understanding Stateflow and its relation to Simulink and MATLAB. It continues withthe description of a demo model provided by The MathWorks, and concludes with an examplewith stepbystep procedures.

    Chapter 2 describes the basic workflow for building Stateflow truth tables to form decisionmaking behavior, and how it works with Simulink blocks. We discuss the Truth Table block thatcan be added directly to a Simulink model, and the Truth Table that can be called from aStateflow 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 byprocedures for building a Simulink model with a Stateflow chart that calls the EmbeddedMATLAB function. It concludes with a procedure for debugging Embedded MATLAB functionsin 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 byprocedures for building a Simulink model with a Stateflow chart that calls the EmbeddedMATLAB 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 graphicalfunctions and includes illustrative examples.

    Chapter 6 describes the use of connective junctions to represent a decision point betweenalternate transition paths for a single transition. Flow diagram notation uses connective junctionsto represent common code structures such as for loops and ifthenelse constructs without theuse of states.

    Chapter 7 describes the use of history junctions to represent historical decision points in theStateflow diagram. A description with an illustrative example is provided, and the chapter

  • 8/2/2019 Stateflow Book

    4/38

    concludes with a discussion on transitions. For easy reference, the examples presented are thesame 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. Wedescribe how to create a state and changing it to a box, and how to create a box and change it toa state.

    Chapter 9, the last chapter, begins with an overview of the Mealy and Moore machines, thendescribes the procedure for creating Mealy and Moore charts in Stateflow, and concludes withillustrative examples for each.

    Appendix C presents an overview of masked subsystems, and a stepbystep procedure to createcustom user interfaces, i.e., masks for Simulink subsystems. It is included in this text as a quickreference to masked subsystems in the Stateflow demos.

    This text is only an introduction to Stateflow, and the author feels that with the backgroundgained after studying the material of this text, the reader should not have any difficulty going

    through the Stateflow demos which undoubtedly are realworld examples.

    This is the first edition of this title, and although every effort was made to correct possibletypographical errors and erroneous references to figures and tables, some may have beenoverlooked. Accordingly, the author will appreciate it very much if any such errors are brought tohis 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 ofMATLAB and Simulink for the encouragement and unlimited support they have provided mewith during the production of this text.

    Orchard Publicationswww.orchardpublications.cominfo@orchardpublications.com

  • 8/2/2019 Stateflow Book

    5/38

    Introduction to Stateflow

    with Applicationsi

    Copyright Orchard Publications

    Table of Contents

    1 The Stateflow Chart 111.1 Finite State Machines..............................................................................................111.2 EventDriven Systems.............................................................................................121.3 Construction of FiniteState Machines with Stateflow..........................................121.4 Procedure for Creating a Stateflow Chart .............................................................1111.5 Summary................................................................................................................1701.6 Exercise for the Reader..........................................................................................1781.7 Solution to the EndofChapter Exercise.............................................................179

    2 The Stateflow Truth Table 212.1 Truth Tables in Stateflow........................................................................................21

    2.2 Summary ................................................................................................................2622.3 Exercises.................................................................................................................2642.4 Solution to EndofChapter Exercises..................................................................266

    3 Embedded MATLAB Functions in Stateflow Charts 313.1 Introduction to Embedded MATLAB Functions ....................................................31

    3.2 Building the Model with a Stateflow Embedded MATLAB Function...................32

    3.3 Programming the Stateflow Chart with an Embedded MATLAB Function.........311

    3.4 Simulation of the Matrix Operations Stateflow Chart ..........................................315

    3.5 Summary ...............................................................................................................3353.6 Exercises for the Reader........................................................................................340

    3.7 Solution to the EndofChapter Exercises ...........................................................342

    4 Model Coverage for Embedded MATLAB Functions 414.1 Introduction to Embedded MATLAB Functions ................................................... 41

    4.2 Summary .............................................................................................................. 418

    4.3 Exercises for the Reader....................................................................................... 419

    4.4 Solution to the EndofChapter Exercises........................................................... 420

    5 Graphical Functions 515.1 Introduction to Graphical Functions...................................................................... 515.2 Creating a Graphical Function............................................................................... 515.3 Subcharts .............................................................................................................. 5105.4 Exporting Graphical Functions to Stateflow........................................................ 5175.5 Summary............................................................................................................... 529

  • 8/2/2019 Stateflow Book

    6/38

    iiIntroduction to Stateflow

    with ApplicationsCopyright Orchard Publications

    5.6 Exercise for the Reader .........................................................................................5315.7 Solution to the EndofChapter Exercise............................................................ 532

    6 Connective Junctions 61

    6.1 The Stateflow Connective Junction Tool ..............................................................6

    16.2 Creating a Connective Junction ............................................................................ 626.3 Changing Connective Junction Size ......................................................................6 36.4 Changing Connective Junction Properties............................................................. 666.5 Uses of Connective Junctions ................................................................................ 676.6 Summary .............................................................................................................. 6166.7 Exercise for the Reader ........................................................................................ 6176.8 Solution to the EndofChapter Exercise ........................................................... 618

    7 History Junctions and Transitions 717.1 History Junction Defined....................................................................................... 717.2 The Stateflow History Junction Tool .................................................................... 717.3 Changing the History Junction Size ...................................................................... 727.4 Changing History Junction Properties................................................................... 757.5 Entering a State ..................................................................................................... 797.6 Executing an Active State ................................................................................... 7107.7 Exiting an Active State........................................................................................ 7117.8 Execution Order for Parallel States ..................................................................... 7137.9 Transitions ........................................................................................................... 715

    7.10 Transition Connections....................................................................................... 7197.11 Inner Transitions ................................................................................................. 7227.12 Summary .............................................................................................................. 7257.13 Exercise for the Reader ........................................................................................ 7277.14 Solution to the EndofChapter Exercise........................................................... 728

    8 Boxes in Stateflow 818.1 Creating a Box.......................................................................................................... 818.2 Changing a State to a Box ....................................................................................... 82

    8.3 Using Boxes in Stateflow.......................................................................................... 8

    48.4 Summary .................................................................................................................. 86

  • 8/2/2019 Stateflow Book

    7/38

    Introduction to Stateflow

    with Applicationsiii

    Copyright Orchard Publications

    9 Mealy and Moore Charts in Stateflow 919.1 Mealy Machine Defined...........................................................................................919.2 Moore Machine Defined..........................................................................................939.3 Mealy and Moore Machines in Stateflow ................................................................949.4 Creating a Mealy Chart............................................................................................969.5 Creating a Moore Chart.........................................................................................9109.6 Changing Chart Type.............................................................................................9179.7 Debugging Mealy and Moore Charts .....................................................................9179.8 Summary.................................................................................................................9209.9 Exercises for the Reader .........................................................................................9219.10 Solution to the EndofChapter Exercises............................................................922

    A Introduction to MATLAB A1A.1 MATLAB and Simulink................................................................................A1

    A.2 Command Window .............................................................................................A1A.3 Roots of Polynomials ...........................................................................................A3A.4 Polynomial Construction from Known Roots......................................................A4A.5 Evaluation of a Polynomial at Specified Values ..................................................A6A.6 Rational Polynomials ...........................................................................................A8A.7 Using MATLAB to Make Plots .........................................................................A10A.8 Subplots..............................................................................................................A18A.9 Multiplication, Division, and Exponentiation ...................................................A18A.10 Script and Function Files...................................................................................A26

    A.11 Display Formats .................................................................................................A

    31

    B Introduction to Simulink B1B.1 Simulink and its Relation to MATLAB ............................................................... B1B.2 Simulink Demos ................................................................................................. B20

    C Masked Subsystems C1C.1 Masks Defined........................................................................................................C1C.2 Advantages Using Masked Subsystems.................................................................. C1C.3 Mask Features.........................................................................................................C1C.4 Creating a Masked Subsystem................................................................................ C2

    References R1

    Index IN1

  • 8/2/2019 Stateflow Book

    8/38

    Introduction to Stateflowwith Applications 11Copyright Orchard Publications

    Chapter 1

    The Stateflow Chart

    his chapter describes the basic workflow for building Stateflow charts that are used tomodel eventdriven systems, and how they work with Simulink blocks. It begins with defi-nitions that are essential in understanding Stateflow and its relation to Simulink and MAT-

    LAB. It continues with the description of a demo model provided by The MathWorks, andconcludes with an example with stepbystep procedures.

    1.1 Finite State Machines

    Afinite state machine is a model describing the behavior of a finite number of states, the transi-tions between those states, and actions.

    A state represents an operating mode of a machine, for instance, a typical household portablespace heater has four states, off, low, medium, and high.The on state is omitted because themachine (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 anentry action which is performed when entering the state, an exit action which is performed whenexiting 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 statetransition table shown as Table 1.1.

    Figure 1.1. State transition diagram for a typical finite state machine

    Off

    Low

    Medium

    High

    State

    Transition

  • 8/2/2019 Stateflow Book

    9/38

    Introduction to Stateflowwith Applications 111Copyright Orchard Publications

    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 State-flow logic block. When we doubleclick on this block, we obtain the Stateflow chart shown asFigure 1.18 below.

    Figure 1.18. The shift_logic Stateflow logic block

    The two dashed rectangles represent two independent modes of operation and are normallyreferred to as Parallel (AND) states, and the numbers 1 and 2 indicate the execution order. Thesolid rectangles within the parallel states 1 and 2 represent mutually exclusive modes of opera-tion and are normally referred to asExclusive (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 wewill follow the procedure recommended by The MathWorks illustrated in the functional blockdiagram shown in Figure 1.19 below.

  • 8/2/2019 Stateflow Book

    10/38

    Chapter 1 The Stateflow Chart

    158 Introduction to Stateflowwith ApplicationsCopyrightOrchard Publications

    Figure 1.70. The Scope block displaying the EndingBalanceoutput

    Step 7: Debugging the Stateflow Chart

    In Step (a) below we will illustrate a procedure for debugging a state inconsistency error, andin Step (b) a procedure for debugging data range violations.

    a. We save the model as Example_1_1_Debug in the same directory, we doubleclick the

    Transfer Controller to open the Stateflow chart, and we delete the default transitions toOverdraft 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 thathas exclusive (OR) decomposition, and thus removing the default transition will cause astate inconsistency error. With both default transitions in state TransferOn, our StateflowEditor window now appears as shown in Figure 1.71.

  • 8/2/2019 Stateflow Book

    11/38

    Introduction to Stateflowwith Applications 159Copyright 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 StateInconsistency is checked in theError checking options panel as shown in Figure 1.72.

  • 8/2/2019 Stateflow Book

    12/38

    Chapter 1 The Stateflow Chart

    160 Introduction to Stateflowwith ApplicationsCopyrightOrchard Publications

    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 observethat Stateflow has generated two coder warnings indicated by gray bullets. These warningsindicate that two states identified by numbers #21and #22 have no unconditional path toa 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 doubleclickthe coder warnings text or we can click the link to the state numbers in the status panel atthe bottom of the Stateflow Builder dialog box in Figure 1.73. Thus, if we doubleclick#21, Stateflow highlights the Overdraft state in the Stateflow Editor chart as shown in Fig-

    ure 1.74. Likewise, if we double

    click #22, Stateflow highlights the Savings state in theStateflow Editor chart.

    We add the default transitions to the Overdraft state and to the Savings state in theStateflow Editor chart, we build the chart again, and we observe that the chart builds suc-cessfully without parser or code generation errors as shown in Figure 1.75.

  • 8/2/2019 Stateflow Book

    13/38

    Chapter 1 The Stateflow Chart

    1120 Introduction to Stateflowwith ApplicationsCopyrightOrchard Publications

    We can speed through the rest of the simulation by unchecking all breakpoints, change the Ani-mation Delay to 0 and click the Continue button repeatedly. We observe that when the simula-tion time reaches 25.5 seconds, the Stateflow Debugger window indicates that the number ofboards produced is 6,870, and that the production has changed from 0 to 1. At this time, theAddShift.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 upperpart of the Stateflow Debugger window indicates Simulink Time:50.000000. At this time theSWITCH signal from theFunction Builder block returns to 0 and the AddShiftOff state becomesactive while the AddShiftOn state becomes inactive as shown below.

  • 8/2/2019 Stateflow Book

    14/38

    Introduction to Stateflowwith Applications 21Copyright Orchard Publications

    Chapter 2

    The Stateflow Truth Table

    his chapter describes the basic workflow for building Stateflow truth tables to form deci-sionmaking behavior, and how it works with Simulink blocks. We discuss the TruthTable 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 decisionmaking 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 Tableblock can also be added to a Simulink model to call a truth table function. ATruth Table block consists of a Condition Table column and two or more Decision columnsdenoted as D1, D2, and so on, and an Action Table below the Condition Table with a Descrip-tion column and Action columns as shown in Table 2.1 below.

    The table above implements the function

    In Table 2.1 above, each of the conditions entered in the Condition column must evaluate totrue (nonzero value) or false (zero value). Outcomes for each condition are specified as T (true),

    TABLE 2.1 Truth Table arrangement in Stateflow

    Condition Table

    Description Condition D1 D2 D3 D4 ...... DN

    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

    t=2

    t=3

    t=4

    .......

    t ttable A B C D, , ,( )=

  • 8/2/2019 Stateflow Book

    15/38

  • 8/2/2019 Stateflow Book

    16/38

    Introduction to Stateflowwith Applications 29

    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. Weobserve that the actions X0 through X10 are those appearing in the last row of the Condi-tion 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 onEditData/Ports from the Add drop menu, and the Ports and Data Manager window appearsas shown in Figure 2.9.

  • 8/2/2019 Stateflow Book

    17/38

    Chapter 2 The Stateflow Truth Table

    274 Introduction to Stateflowwith ApplicationsCopyright Orchard Publications

    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.

  • 8/2/2019 Stateflow Book

    18/38

    Chapter 2 The Stateflow Truth Table

    290 Introduction to Stateflowwith ApplicationsCopyright Orchard Publications

    2. We repeat step (g).1 above for the Truth Table Editor toolbar ofttable2, and again weare 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 Simulinkmodel now is as shown below. We save the model asFullAdder.

    5. We continue stepping through the simulation by changing the values of X, Y, and Cinin accordance with the generic truth table of the Full adder to verify that the modeloutputs the correct values for the Sum and Cout outputs.

  • 8/2/2019 Stateflow Book

    19/38

    Introduction to Stateflowwith Applications 291

    Copyright Orchard Publications

    Solution to EndofChapter 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 withScope blocks as shown below.

    7. The waveforms of the Pulse Generator blocks and the waveforms for Sum and Cout

    are shown below.

  • 8/2/2019 Stateflow Book

    20/38

    Chapter 2 The Stateflow Truth Table

    292 Introduction to Stateflowwith ApplicationsCopyright Orchard Publications

  • 8/2/2019 Stateflow Book

    21/38

    Introduction to Stateflowwith Applications 31Copyright Orchard Publications

    Chapter 3

    Embedded MATLAB Functions in Stateflow Charts

    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 MAT-LAB 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 func-tion 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

  • 8/2/2019 Stateflow Book

    22/38

    Introduction to Stateflowwith Applications 315

    Copyright Orchard Publications

    Simulation of the Matrix Operations Stateflow Chart

    The functions det(A) and inv(A) are defined in MATLAB but are not included in the Embed-ded MATLAB RunTime 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 StateflowChart block Matrix Operations, and we have stretched the Display 2 block to accommodatethe nine elements of the inverse matrix after the simulation command is issued. The value of thedeterminant 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 doubleclick the Matrix Operations Stateflow chart in Fig-ure 3.18, in the Stateflow Editor window from the Simulation drop menu we select Configura-

    tion Parameters, we click Solver in the left Select pane, and in the Simulation time and Solveroptions 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

  • 8/2/2019 Stateflow Book

    23/38

    Introduction to Stateflowwith Applications 321

    Copyright Orchard Publications

    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 but-ton. We observe that Stateflow displays a Block Error message for the Constant block as indi-cated in Figure 3.26. This is because we failed to define the elements of the matrix A in theMATLAB Command Window before starting the simulation. Therefore, we open the MATLAB

    Command Window and we enter the elements of matrix A asA=[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 weobserve that it is changed to a Continue button as shown in Figure 3.27. We also observe thattheBrowse 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 .

  • 8/2/2019 Stateflow Book

    24/38

    Introduction to Stateflowwith Applications 323

    Copyright Orchard Publications

    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 theEnter key atthe command prompt and MATLAB displays

    debug>>

    and at the command prompt we type det and MATLAB displays the value of the determinant atthe start of the simulation.

    det =

    0

    To see the value of the inverse of the matrix, at the MATLAB Command Window we type invand MATLAB displaysinv =

    0 0 0

    0 0 0

    0 0 0

  • 8/2/2019 Stateflow Book

    25/38

    Introduction to Stateflowwith Applications 41

    Copyright Orchard Publications

    Chapter 4

    Model Coverage for Embedded MATLAB Functions

    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 Cover-age 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

  • 8/2/2019 Stateflow Book

    26/38

    Introduction to Stateflowwith Applications 51Copyright Orchard Publications

    Chapter 5

    Graphical Functions

    his chapter describes the procedure for creating graphical functions. It begins with an intro-

    duction to graphical functions followed by procedures for building a Simulink model todefine graphical functions and includes illustrative examples.

    5.1 Introduction to Graphical Functions

    Stateflow defines three types of functions: truth table, Embedded MATLAB, and graphical. Wedescribed truth table and Embedded MATLAB functions in the previous chapters. In this chap-ter we will discuss graphical functions.

    Like the truth table and Embedded MATLAB functions, a graphical function is an extension ofStateflow actions. We define a program once in a function, and we can call it as many times as weneed 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 clickto place it near the top of the empty area. The graphical function now appears as an unnamedobject in the Stateflow Editor with a flashing text cursor as shown in Figure 5.1 below. We savethis function as graph_func_stateflow.

    2. The syntax of a typical graphical function has a signature of the following form:

    Accordingly, in the Stateflow Editor window we define our function as

    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 andthis function now appears in the Model Explorer window shown in Figure 5.3.

    y f x1 x2 xn, , ,( )=

    w f x y z, ,( )=

  • 8/2/2019 Stateflow Book

    27/38

    Chapter 5 Graphical Functions

    56 Introduction to Stateflowwith ApplicationsCopyright Orchard Publications

    In the graphical function rectangle shown in Figure 5.6, we enter the condition action of thefunction signature Z=f(R,XL,XC), a default transition with a terminating junction, the equation

    for the impedance , and the default transition for the function argu-

    ment . We save this function as impedance_stateflow, and the State-

    flow 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 inFigure 5.8 where with the Chart highlighted in the Model Hierarchy pane (left), the Contents

    pane (right) shows the function arguments , , and as inputs, and the return valueas the output.

    Z sqrt R^2+(XL-XC( )^2)=

    Zout f Rin XLin XCin,,( )=

    Rin XL XC

    Zout

  • 8/2/2019 Stateflow Book

    28/38

    Chapter 5 Graphical Functions

    532 Introduction to Stateflowwith ApplicationsCopyright Orchard Publications

    5.7 Solution to the End-of-Chapter Exercise

    As a first approximation, we use the MATLAB plot command to plot versus .

    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 , and this can be easily verified by inspection of

    the given function. The second root is near the vicinity , and the third near the vicinity

    . 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 Displayblocks from the Sinks Library. Our model is as shown below.

    y x

    x 0=

    x 1.3=

    x 2.2=

  • 8/2/2019 Stateflow Book

    29/38

    Chapter 6 Connective Junctions

    610 Introduction to Stateflowwith ApplicationsCopyright Orchard Publications

    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 wedid 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 selfloop.

    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 aselfloop 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] ismet, 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 selfloop transition, the sys-tem exits and reenters state A, and executes action a2.

    In the equivalent representation on the right, the use of a connective junction makes it unneces-sary to specify the implied condition [~c1] explicitly.

  • 8/2/2019 Stateflow Book

    30/38

    Introduction to Stateflowwith Applications 611

    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.Selfloop 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, butdoes have a condition action {i=0}, and this condition action is executed. The condition on theselfloop transition is evaluated as true and the condition actions{i++;func1()} execute. Thecondition actions execute until the condition [i

  • 8/2/2019 Stateflow Book

    31/38

    Introduction to Stateflowwith Applications 71Copyright Orchard Publications

    Chapter 7

    History Junctions and Transitions

    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 thechapter concludes with a discussion on transitions. For easy reference, the examples pre-

    sented 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 representhistorical 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 historicalstate activity information is used to determine the next state to become active. The history junc-tion 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 theHistory Junction tool .

    2. We move the cursor into the diagram editor.The cursor takes on the shape of a history junc-tion as shown in Figure 7.2. We click to place a connective junction in the desired location inthe drawing area.

    * We recall from Chapter 1 that objects in Stateflow exist in a hierarchy and states can contain other states referred to as sub-states, and can be contained by other states referred to as superstates.

  • 8/2/2019 Stateflow Book

    32/38

    Introduction to Stateflowwith Applications 91Copyright Orchard Publications

    Chapter 9

    Mealy and Moore Charts in Stateflow

    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 illustra-tive examples for each.

    9.1 Mealy Machine Defined

    In the theory of computation, a Mealy machine is a finite state machine that generates an outputbased on its current state and an input. This means that the state diagram will include both aninput 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.

    We can represent the state table above with the timing diagram shown in Figure 9.1 below.

    TABLE 9.1

    Present State Input Next State Output

    0 0 0 0 1 0

    0 0 1 1 1 1

    0 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

    Q1n

    Q0n x Q1

    n 1+Q0

    n 1+ y

  • 8/2/2019 Stateflow Book

    33/38

    Chapter 9 Mealy and Moore Charts in Stateflow

    92 Introduction to Stateflowwith ApplicationsCopyright Orchard Publications

    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 inFigure 9.2 below.

    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 to to to to and

    repeats whenever the input signal is , and counts counterclockwise from to to to

    to and repeats whenever the input signal is .

    CP

    x

    y

    Q1n 1+

    Q0n 1+

    Q1n

    Q0n

    0 0 0 0 0

    0 0 0 0 0

    0 0 0 0 0

    0 000 0 0

    0 0 0 0 0

    0 0 0 0 0

    1 1 1 1

    1 1 1 1

    1 1 1 1

    1 1 1 1

    1 1 1 1

    1 1 1 1

    00

    01

    10

    11

    00 01 10 11 00

    x 0 11 10 01

    00 11 x 1

  • 8/2/2019 Stateflow Book

    34/38

    Introduction to Stateflowwith Applications 93

    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 is

    dependent on the current state, e.g., and the input by expressing the transition from one

    state to another as and placing it near the transition arrow. For example, for the transition

    from state to the arrow in the clockwise direction has the designation , and for the

    transition from state to the arrow in the counterclockwise direction has the designation.

    9.2 Moore Machine Defined

    In contrast to the Mealy machine whose output depends on its current state and input, the out-put 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

    outputs inside the circle. Thus, for a twobit Moore machine, the state is represented as ,

    the output is represented as , and the state and output are separated by a slash (/). For

    instance, in the designation , indicates the state, and indicates the output.

    Example 9.2

    This is a Moore machine example.

    Let us consider the Moore machine shown in Figure 9.3.

    Figure 9.3. Moore machine for Example 9.2

    y

    00 x

    x y

    00 01 0 0

    01 001 1

    Q1nQ0

    n

    y1y0

    10 01 10 01

    10 11

    00 01

    01 1011 00

  • 8/2/2019 Stateflow Book

    35/38

    Introduction to Stateflowwith Applications C1Copyright Orchard Publications

    Appendix C

    Masked Subsystems

    his appendix presents an overview of masked subsystems, and a stepbystep procedure tocreate custom user interfaces, i.e., masks for Simulink subsystems.

    C.1 Masks Defined

    Amask is a custom user interface for a subsystem. Amasked subsystem conceals the subsystem'scontents, 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 amask 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 dialogwith 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 SFunction 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 blockdiagram 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 anyMATLAB drawing command in the icon code.

    Mask Parameters Masked subsystems allow us to define a set of userspecified parameters.Simulink stores the values of these parameters in the mask workspace as thevalue of a variable whose name you specify. These associated variables allowus to link mask parameters to specific parameters of blocks inside a maskedsubsystem.

  • 8/2/2019 Stateflow Book

    36/38

    Introduction to Stateflow

    with Applications C9Copyright Orchard Publications

    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

    and the roots of this equation are and . 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 commandsthat initialize the masked subsystem, and the Documentation tab that lets us define or modify thetype description and help text for a masked subsystem. These tabs are shown in Figures C.11 andC.12, and are not used in this example.

    y x2

    5x 6+=

    x1 2= x2 3=

  • 8/2/2019 Stateflow Book

    37/38

    IndexSymbols D exit in MATLAB A-2

    exit action 1-1

    % (percent) symbol in MATLAB A-2 data icon 3-6 exiting an Active State 7-11

    data points in MATLAB A-14 explicit ordering 1-29

    A data range 1-64 explicit ordering of parallel states 7-14

    data range violation 1-58 exporting graphical functions

    abs(z) in MATLAB A-23 Debug tool 1-48, 3-18 to Stateflow 5-17

    action 1-1 decibels A-13

    action table 2-1 decision 2-1, 2-2 F

    actions 2-1 decision columns 2-1, 2-2

    algebraic constrain blocks in Simulink B-18 decision coverage 4-2 figure window in MATLAB A-13

    All Data (Current Chart) in Simulink 3-22 decomposition 1-26 finite state machine 1-10

    angle(z) in MATLAB A-23 deconv in MATLAB A-6 Flip Block command in Simulink B-11

    animation in Simulink 3-16 default A-12 for 4-18

    animation delay 1-55 default color A-15 for loops 6-11

    animation of Stateflow charts 1-47 default decision 2-2 format A-31

    autoscale icon in Simulink B-12 default decision column 2-8 fplot in MATLAB A-27

    axis in MATLAB A-16 default line in MATLAB A-15 function block parameters B-10

    default marker in MATLAB A-15 function file in MATLAB A-26

    B default transition 1-14, 7-16 function header 4-18

    default transition 7-16 fzero in MATLAB A-26

    backtracking behavior 6-14 Default Transition tool 1-37, 3-4

    block error 1-67 default transitions 1-37 G

    blocking 3-40 delay 3-18

    box in Stateflow 8-1 demo in MATLAB A-2 Gain block in Simulink B-18

    box in MATLAB A-12 description 2-1 graphical functions 5-1

    box tool in Stateflow 8-1 Disable all field 3-24 graphical tool function 5-1

    breakpoints 1-49, 3-19 Display block in Simulink B-18 grid in MATLAB A-12

    Browse Data 1-50, 3-19 display formats in MATLAB A-31 gtext in MATLAB A-13

    Build tool 1-60 dot multiplication operator in MATLAB A-20 guarding a transition 1-39

    during action 1-14

    C H

    E

    changing a box to a state 8-1 history junction 7-1

    changing a state to a box 8-1 Editor window in MATLAB A-1 History Junction tool 7-1

    Chart Entry 1-49, 3-19 Editor/Debugger in MATLAB A-1

    Chart Entry 3-19 electric field strength example 3-40 IClassic Machine in Stateflow 9-4 element-by-element division and

    clc in MATLAB A-2 exponentiation in MATLAB A-21 If 4-18

    clear in MATLAB A-2 element-by-element multiplication if-then-else 6-13

    code generation errors 1-60 in MATLAB A-18, A-20 imag(z) in MATLAB A-23

    Coder Options 1-48, 3-18 eM functions 3-4 implicit ordering 1-29

    column vector A-19 Embedded MATLAB Editor 3-7 increments between points in MATLAB A-14

    command screen in MATLAB A-1 Embedded MATLAB function 3-1 inner transition 7-22

    Command Window in MATLAB A-1 Embedded MATLAB Function tool 3-3 input argument 3-6

    commas in MATLAB A-8 Entering a State 7-9

    comment line in MATLAB A-2 entry action 1-1, 1-14 L

    Commonly Used Blocks in Simulink B-7 eps in MATLAB A-22

    complex conjugate A-4 Erlang 3-40 Launch Model Explorer tool 1-68

    complex numbers in MATLAB A-3 Erlang B 3-40 lims = in MATLAB A-27

    condition 1-2, 1-14, 7-18 Erlang B model 3-41 linspace in MATLAB A-14condition action 7-18 Erlang C 3-40 local data 9-7

    condition table 2-1 Erlang C model 3-41 log in MATLAB A-13

    conditions 2-1 error checking options 1-59 log(x) A-13

    configuration parameters 1-46, 3-15, B-12 event 1-2, 1-14, 7-17 log10(x) in MATLAB A-13

    Connective Junction 6-1 event driven systems 1-2 log2(x) in MATLAB A-13

    Contents pane 3-6, B-7 event properties dialog box 1-44 loglog in MATLAB A-13

    Continue button 1-56, 3-21 event trigger 7-17 loglog(x,y) in MATLAB A-13

    Continue Debugging 3-33 exclusive (OR) state 1-12

    conv in MATLAB A-6 executing an Active State 7-10 M

    Creating a Mealy Chart 9-6 execution order 1-12, 1-27

    Creating a Moore Chart 9-10 execution Order for Parallel States 7-13 mask C-1

    IN1

  • 8/2/2019 Stateflow Book

    38/38