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:
[email protected] 1-9 934404-0 08-9 9 ISBN-13: 978-1 934404-0 08-X X ISBN-10: 1-9
$60.00 U.S.A.
Introduction to Stateflow® with Applications Steven T. Karris
Orchard Publications www.orchardpublications.com
Introduction to Stateflow ® with Applications Copyright ©2007 Orchard Publications. All rights reserved. Printed in the United States of America. No part of this publication may be reproduced or distributed in any form or by any means, or stored in a data base or retrieval system, without the prior written permission of the publisher. Direct all inquiries to Orchard Publications,
[email protected] Product and corporate names are trademarks or registered trademarks of The MathWorks™, Inc. They are used only for identification and explanation, without intent to infringe.
Library of Congress Cataloging-in-Publication Data Library of Congress Control Number 2007934492
ISBN-10: 1-934404-08-X ISBN-13: 978-1-934404-08-9
Disclaimer The author has made every effort to make this text as complete and accurate as possible, but no warranty is implied. The author and publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this text.
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
[email protected] 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
NOTES:
iv
Introduction to Stateflow®with Applications Copyright © Orchard Publications
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
Chapter 1 The Stateflow Chart TABLE 1.1 Typical state transition table for a finite state machine Present State / Condition Condition 1 Condition 2 ................... Condition N
State A (Off) 1 0 ..... 0
State B (Low) 0 1 ..... 0
State C (Medium) 0 0 ..... 0
State D (High) 0 0 ..... 1
A condition is a Boolean expression that can be true (logic 1) or false (logic 0). In Stateflow, conditions are enclosed in square brackets.
1.2 Event−Driven Systems An event is an action that can trigger a variety of activities. For example, in a typical household space heater a switch allows a transition to occur between medium state and high state. Thus, event driven systems allow the transition from one operating mode to another in response to events and conditions. Event−driven systems can be implemented as finite−state machines.
1.3 Construction of Finite−State Machines with Stateflow Stateflow provides us the necessary graphical objects to construct finite−state machines. Like Simulink, we can drag and drop objects to create state−transition charts in which a series of transitions directs a flow of logic from one state to another. Let us examine the example of a Stateflow chart provided with the Stateflow Toolbox. This example illustrates the logic required to shift gears in an automatic transmission system of a car. It is assumed that MATLAB, Simulink, and Stateflow are all installed in your system. For installation procedures, please refer to The MathWorks documentation. We begin by invoking MATLAB, and at the command prompt we type sf_car. The Simulink model of Figure 1.2 is then displayed.
1−2
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Construction of Finite−State Machines with Stateflow
Figure 1.2. The sf_car model in Simulink
The left−most block in Figure 1.2 is the familiar Signal Builder block and provides the signals shown in Figures 1.3 through 1.6. For the construction of a signal builder block, please refer to Introduction to Simulink with Engineering Applications, ISBN 0−9744239−7−1, or to the Simulink documentation.
Figure 1.3. The passing maneuver state in the Signal Builder block of Figure 1.2
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−3
Chapter 1 The Stateflow Chart
Figure 1.4. The gradual acceleration state in the Signal Builder block of Figure 1.2
Figure 1.5. The hard braking state in the Signal Builder block of Figure 1.2
Figure 1.6. The coasting state in the Signal Builder block of Figure 1.2
1−4
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Construction of Finite−State Machines with Stateflow When this model is simulated, the Scope blocks in Figure 1.2 will display the engine RPM, vehicle MPH and throttle percentage signals depending on the selection of the applied signals shown in Figures 1.3 through 1.6. Thus, when the Actual Acceleration mode is selected, the engine RPM Scope block and the vehicle MPH and throttle percentage will display the signals shown in Figures 1.7 and 1.8 respectively.
Figure 1.7. The engine RPM signal when the Actual Acceleration mode is selected in Figure 1.2
Figure 1.8. The vehicle MPH and throttle % signals when the Actual Acceleration mode is selected in Figure 1.2
The internal blocks and their interconnection for the subsystem Engine in Figure 1.2 are shown in Figure 1.9 below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−5
Chapter 1 The Stateflow Chart
Figure 1.9. The blocks for the engine subsystem of Figure 1.2
In Figure 1.9 the engine torque* block is a Lookup Table (2−D) block whose inputs are the vector thvec (first input) representing the throttle signal in Figure 1.4, and the vector nevec (second input) representing the engine RPM value at the end of the simulation time. The elements of these vectors can be seen by typing thvect and nevect in MATLAB’s command prompt. The signal at the minus (−) input of the Sum block in Figure 1.9, denoted as Ti, represents the impeller torque as we can see from Figure 1.2. A typical value for term lei in the Gain block denoted as engine + impeller† inertia‡ is 0.02 and in this model the constant value 0.022 is being used. The Integrator block in Figure 1.9 is configured with Initial condition set at 1000, Limit output checked, Upper saturation limit at 6000, and Lower saturation limit at 600. To see how the values change with simulation time, we add Display blocks as shown in Figure 1.10.
Torque is the product of force and lever−arm distance, which tends to produce rotation. The SI derived unit commonly use for torque is the newton metre (joule). Torque has the same units as energy or work. † An impeller is a rotating component of a pump, usually made of iron, steel, aluminum or plastic, which transfers energy from the motor that drives a pump to the fluid being pumped by forcing the fluid outwards from the centre of rotation. Impellers are usually short cylinders with protrusions forming paddles to push the fluid and a splined center to accept a driveshaft. ‡ When a large force is required to speed up a body, slow it down, or deviated sidewise if it is moving, the mass of the body is large, and thus we say that the body has a large inertia. If only a small force is needed per unit of acceleration, the mass is small and the inertia is small. *
1−6
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Construction of Finite−State Machines with Stateflow
Figure 1.10. The engine subsystem of Figure 1.2 with values at simulation time T=30
The engine RPM block in Figure 1.10 displays the waveform shown in Figure 1.11.
Figure 1.11. The engine RPM waveform displayed on the Scope block of Figure 1.10
The components of the transmission subsystem block of Figure 1.2 are shown in Figure 1.12 below.
transmission ratio
Figure 1.12. The components of the transmission subsystem in Figure 1.2
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−7
Chapter 1 The Stateflow Chart The Torque Converter* subsystem in Figure 1.12 is a masked subsystem with a mask icon. An introduction to Masked Subsystems is provided in Appendix C. To unveil its components we choose Look Under Mask from the Edit menu, and the subsystem components are shown in Figure 1.13. Both lookup tables in Figure 1.13 perform 1−D interpolation.
Figure 1.13. The components of the torque converter subsystem in Figure 1.12
The components of the transmission ratio subsystem in Figure 1.12 are shown in Figure 1.14. The lookup table in Figure 1.14 performs 1−D interpolation for the gear ratios in the transmission system. A typical four−speed manual transmission has the following gear ratios: Gear Ratio
1st 2.97:1
2nd 2.07:1
3rd 1.43:1
4th 1.00:1
Reverse 3.28:1
Figure 1.14. The components of transmission ratio subsystem in Figure 1.12 * A torque converter is modified form of a hydrodynamic fluid coupling (a device used to transmit rotating mechanical power), and like the fluid coupling, is used to transfer rotating power from a prime mover, such as an internal combustion engine or electric motor, to a rotating driven load. As with the fluid coupling, the torque converter takes the place of a mechanical clutch. Unlike a fluid coupling, however, a torque converter is able to multiply torque when there is a substantial difference between input and output rotational speed, thus providing the equivalent of a reduction gear.
1−8
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Construction of Finite−State Machines with Stateflow As seen in the table on the previous page, in 1st gear, the engine makes 2.97 revolutions for every revolution of the transmission’s output. In 4th gear, the gear ratio of 1:1 means that the engine and the transmission’s output are moving at the same speed. * The model of Figure 1.2 uses the gear ratios 2.393:1, 1.450:1, 1.000:1, and 0.667:1. These values can be seen in Function Block Parameters of Figure 1.15 for the Look−Up Table block in Figure 1.14.
Figure 1.15. Function Block Parameters for the Look−Up Table block in Figure 1.15
The vehicle subsystem in Figure 1.2 is another masked subsystem. As before, to view the components of this subsystem we choose Look Under Mask from the Edit menu, and the subsystem components are shown in Figure 1.16.
* Some automobiles are equipped with 5th and 6th gears and typical gear ratios for these are 0.84:1 and 0.56:1 respectively. These are referred to as overdrive gears in which the output of the transmission is revolving faster than the engine. The differential ratio is a measure of the number of revolutions of the transmission to the revolutions of the wheels of the automobile. Thus, a differential ratio of 3.45 indicates that for every 3.45 revolutions of the transmission, the wheels complete one revolution. Multiplication of the differential ratio by the gear ratio in the transmission produces the number of revolutions in the engine per one revolution of the wheels. Thus, using the gear ratio in the 1st gear in Table 1.2 and a differential ratio of 3.45, we obtain 2.97 x 3.45 = 10.25 revolutions for every revolution the wheels make.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−9
Chapter 1 The Stateflow Chart
Figure 1.16. The vehicle block subsystem shown in Figure 1.2
It is beyond the scope of this text to provide details for every block in Figure 1.16 above. The block above the road load block in Figure 1.16 above, is a user−defined function block and represents the signum function* whose value is – 1 for all negative inputs, and +1 for all positive inputs. The components of the Threshold Calculation subsystem block in Figure 1.2 are shown in Figure 1.17 below. We observe that includes a Function−Call Generator block. We recall† that this block can be placed in a subsystem to create a triggered subsystem.
Figure 1.17. The components of Threshold Calculation subsystem block shown in Figure 1.2
The interp_up and interp_down blocks in Figure 1.17 are both Look−up 2D tables. To see the values assigned to them, at the MATLAB command prompt we type upth, downth, uptab, and downtab.
* †
The signum function is described in detail in Signals and Systems with MATLAB Computing and Simulink Modeling, ISBN−13: 978−0−9744239−9−9. It is very useful in deriving the Fourier transform of the unit step function. For an example, please refer to Page 11−34, Introduction to Simulink with Engineering Applications, ISBN−13: 978−0− 9744239−7−1
1−10
Introduction to Stateflow®with Applications Copyright©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 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 2. Define the states for modeling each mode of operation
6. Simulate the Chart
1. Define the Stateflow 3. Define state actions and variables Interface to Simulink
5. Choose triggering method
7. Debug the Chart
4. Define the transitions between states
Figure 1.19. Recommended procedure for creating a Simulink model with a Stateflow Chart block
Example 1.1 ABC Company maintains checking and savings accounts with a local bank. The initial deposit in the checking account is $10,000 and the fixed amount of $10,000 is deposited in the savings account. The company has also established an overdraft protection for up to $50,000, and has made an agreement with the bank that if payments by the bank exceed the overdraft protection, the bank will deduct the excess amount from the savings account. There will be no fees imposed as long as payments do not exceed present checking account balance and interest at 0.5% will be earned. A fee of 5% will be imposed for overdrafts, and 1% fee will be charged if it becomes necessary to draw monies from the savings account. To simplify the model, we will assume that no deposits to the checking account are made during the assumed time of payment transactions. When completed, the Stateflow chart will appear as shown in Figure 1.20. This example is similar to the sf_aircontrol model provided by The MathWork’s Stateflow documentation. The Stateflow Editor chart in Figure 1.20 contains six Exclusive (OR) states represented graphically by solid rectangles. These states are shown as Transfer On, Overdraft On, Overdraft Off, Savings On, Savings Off, and TransferOff. No two or more Exclusive (OR) states can be active or execute at the same time. The Stateflow Editor chart in Figure 1.20 contains also three Parallel (AND) states represented graphically by dashed rectangles with a number in the upper right corner. These are shown as Overdraft (Number 1), Savings (Number 2), and DollarValue (Number 3). The numbers indicate the execution order. Two or more parallel (AND) states at the same hierarchical level can be active at the same time but will execute in serial fashion.
1−12
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.20. The Stateflow Editor window for Example 1.1
The unidirectional arrows represent transitions from one state to another and specify the direction of the flow. The Stateflow chart in Figure 1.20 contains six transitions, i.e., Overdraft On to Overdraft Off, Overdraft Off to Overdraft On, Savings On to Savings Off, Savings Off to Savings On, TransferOn to TransferOff, and TransferOff to TransferOn. Referring again to the Stateflow Editor chart in Figure 1.20, we observe that an arrow with a solid dot tail is directed towards the Overdraft Off, Savings Off, and TransferOff solid rectangles and as mentioned earlier, these represent exclusive (OR) states and as such cannot be active or execute at the same time. The Overdraft On, Savings On, and TransferOn solid rectanIntroduction to Stateflow®with Applications Copyright © Orchard Publications
1−13
Chapter 1 The Stateflow Chart gles also represent exclusive (OR) states and since the On and Off states are on the same hierarchical level, we must specify which is the default state, On or Off. For this example, the default states are Off and we use this arrow, referred to as the Default transition, for this purpose. When the Stateflow chart is inactive, it is in a dormant state, and when the chart is first activated, the default transition, e.g., TransferOff, makes the chart active. As we will see soon, we will use a clock signals to “wake up” the chart. A State Action is an action whose execution is based on the status of the state. The chart in Figure 1.20 contains an entry action and a during action. Entry actions are executed when the state is entered, i.e., when it first becomes active. The entry in the TransferOff state is an entry action. During actions are executed while a state is active and no transition to another state exists. The during in the TransferOn state is a during action. We can abbreviate the word during as du. A Condition is a Boolean expression that allows a transition to occur when the expression is true. A Condition is a text label for the transition and it is enclosed in square brackets ([ ]). The chart in Figure 1.20 provides four conditions on the transitions between Overdraft and Savings, i.e., [EndingBalance < 0], [EndingBalance >= 50000], [EndingBalance < −50000], and [EndingBalance >= −50000]. An Event is an object that can initiate several activities such as “waking up” a Stateflow chart, transitions to occur from one state to another, and executions of actions. When our model is complete, it will appear as shown in Figure 1.21 below.
Figure 1.21. The model for Example 1.1
1−14
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart The model in Figure 1.21 contains two edge−triggered events, the CLOCK that is used to “wake up” the Stateflow chart at each rising or falling edge of a square wave signal, and the TRANSFERS that is used to allow transitions to occur between TransferOff and TransferOn at each rising or falling edge of a pulse signal. The contents of the Financial Operations subsystem in Figure 1.21 are shown in Figure 1.22, and the signals in the Signal Builder block are shown in Figure 1.23.
Figure 1.22. The components of the Financial Operations subsystem in Figure 1.21
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−15
Chapter 1 The Stateflow Chart
Figure 1.23. Waveforms provided by the Signal Builder block
We will now create the model with the following step−by−step procedure. Step 1: We define the Interface to Simulink a. We invoke MATLAB and from the main window shown in Figure 1.24 below we select Simulink by clicking on the Simulink icon window shown in Figure 1.25.
. This opens the Simulink Library Browser
Figure 1.24. The MATLAB main window
1−16
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.25. The Simulink Library Browser window
b. In the Simulink Library Browser window shown in Figure 1.25 we click the Create a new model icon
and a new empty model appears as shown in Figure 1.26.
Figure 1.26. Empty Simulink model for Example 1.1
c. From the Simulink Library Browser window shown in Figure 1.25, we click and drag the following Simulink blocks into the empty Simulink model in Figure 1.26. Three Constant blocks, a Product block, a Gain block, an Integrator block, two Inport blocks and an Outport block from the Commonly Used Blocks Library, and a Multiport
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−17
Chapter 1 The Stateflow Chart Switch from the Signal Routing Library. The Constant blocks and the Gain block perform the functions described by the annotations, to the Limit Inport block we will assign the value of – 60000 to represent the negative sum of the initial deposit of 10000 and the maximum Overdraft amount of 50000 . The Integrator block performs the integration EndingBalance =
t
∫0 En dingBalance_Change + 10000
where 10000 is the initial condition* representing the initial deposit of 10000 into the checking account. We interconnect these blocks as shown in Figure 1.27.
Figure 1.27. The blocks for the subsystem
d. To create a subsystem, we enclose all blocks, except the Inport and Outport blocks, within a bounding box, from the Edit drop menu we choose Create Subsystem, and we label it as Financial Operations.
* The initial condition is specified in the Function Block Parameters dialog box for the Integrator block.
1−18
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart e. We stretch the window of the model in Figure 1.26 and we add the following blocks: A Signal Builder block from the Sources Library. A Mux block (heavy vertical bar) from the Commonly Used Blocks Library A Scope block from the Commonly Used Blocks Library A Constant block from the Commonly Used Blocks Library A Chart block from the Stateflow subnode under the Simulink Extras Library The model now appears as shown in Figure 1.28.
Figure 1.28. The blocks for the model of Example 1.1
f. We double−click the Signal Builder block and the waveform shown in Figure 1.29 appears.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−19
Chapter 1 The Stateflow Chart
Figure 1.29.
g. From the Axes drop menu we select Change Time Range, we set Min time to 0, Max time to 300, we change the name field from Signal 1 to TRANSFERS, we click on the rising (left) edge of the waveform to select it,* in the T: field under Left Point we enter 10, we click the falling (right) edge of the waveform to select it, in the T: field under Left Point we enter 290, and we click OK to accept it. The waveform of the Signal Builder block is now as shown in Figure 1.30.
* When properly selected, it appears as a heavy red line and the fields in the lower part of the window become active
1−20
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.30. The TRANSFERS waveform for Example 1.1
h. From the Signal drop menu in the Signal Builder window of Figure 1.30 we select New and from it we choose Square Wave. In the Square Wave dialog box in Figure 1.31 below we enter the parameters shown.
Figure 1.31. Parameters for the square waveform of the Signal Builder block
i. We change the name field to CLOCK, we click OK to accept these values, and the Signal Builder block now appears as shown in Figure 1.32.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−21
Chapter 1 The Stateflow Chart
Figure 1.32. The TRANSFERS and CLOCK waveforms of the Signal Builder block
j. As we will discuss shortly, in Figure 1.32 the TRANSFERS signal will be used to allow transitions to occur between TransferOff and TransferOn at each rising or falling edge of a pulse signal, and the CLOCK is used to “wake up” the Stateflow chart at each rising or falling edge of a square wave signal. k. To define the input of the Stateflow Chart block in Figure 1.28, we double−click this block, and we observe that the Stateflow Editor window appears as shown in Figure 1.33. From the Add drop menu we select Data>Input from Simulink, and this opens the Data window shown in Figure 1.34. In the Name field that appears under the General tab, we change the name to EndingBalance and we leave other fields in their default values. We select the Value Attributes tab and we check the Watch in debugger box. This will allow us to observe the value of EndingBalance at breakpoints during simulation.
1−22
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart l. To define the output of the Stateflow Chart block in Figure 1.28, we double−click this block, and we observe that the Stateflow Editor window appears as shown in Figure 1.33. From the Add drop menu we select Data>Output to Simulink, and this opens the Data window shown in Figure 1.34.
Figure 1.33. The Stateflow Editor window
Figure 1.34. The Data window dialog box for defining the input and output to the Stateflow Chart
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−23
Chapter 1 The Stateflow Chart m. In the Name field that appears under the General tab in the Data dialog box in Figure 1.34, we change the name to Payments and we leave other fields in their default values. We select the Value Attributes tab, for the Limit range we specify 0 for Minimum and 2 for Maximum, where 0 represents no transfer, 1 indicates Overdraft transfer On, and 2 indicates Savings transfer On. We also check the Watch in debugger box to allow us to observe the value of Payments at breakpoints during simulation. n. Our Simulink model should now look like that shown in Figure 1.35 where we have renamed the Stateflow Chart block Transfer Controller.
Figure 1.35. Defined input and output for the Stateflow Chart
Step 2: We define the States for each Mode of Operation a. In the Simulink model of Figure 1.35 we double−click the Transfer Controller block and the Stateflow Editor window appears as shown in Figure 1.36. From the object palette on the left side of the Stateflow Editor window we click the State tool , we move it to the drawing area, and we observe that it changes to a rectangle with rounded corners and with a flashing text cursor on the upper left corner as shown in Figure 1.37. This is a solid rectangle and as we know, it represents an exclusive (OR) state.
1−24
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.36. The empty Stateflow Editor window
Figure 1.37. The Stateflow Editor window with the first exclusive (OR) state
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−25
Chapter 1 The Stateflow Chart b. At the flashing text cursor we enter TransferOn to name this state,* and we stretch the rectangle. The Stateflow editor window now appears as shown in Figure 1.38.
Figure 1.38. The TransferOn exclusive (OR) state
c. We click the State tool again and we draw a smaller state below the TransferOn state, and we name it TransferOff. The Stateflow editor window now appears as shown in Figure 1.39. d. In the Stateflow Editor in Figure 1.39 we right−click inside the TransferOn state and from the pop−up menu in Figure 1.40 we select Decomposition> Parallel (AND).
* We can change the text size by choosing the Set Font Size from the Edit drop menu.
1−26
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.39. The TransferOn and TransferOff exclusive (OR) states
e. We left−click the State tool in the Stateflow Editor in Figure 1.39 and we place two states inside the TransferOn state. We observe that these two states appear as rectangles with rounded corners and dashed lines indicating that they are parallel (AND) states. We also observe that these parallel states display numbers in their upper right corners. These numbers specify the order of execution during simulation. We name these parallel states as Overdraft and Savings, and the Stateflow Editor window now appears as shown in Figure 1.41.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−27
Chapter 1 The Stateflow Chart
Figure 1.40. Submenu for selecting the parallel (AND) states decomposition
f. We now need to add an observer state whose purpose will be to monitor the status of the Overdraft and Savings states. We left− click the State tool again and we place another substate within the TransferOn state under the Overdraft and Savings states. We name this substate DollarValue and the Stateflow Editor appears as shown in Figure 1.42.
1−28
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.41. The addition of the Overdraft and Savings parallel (AND) states
g. By default, Stateflow execution order is based on implicit ordering. This means that the execution order of parallel states depends on their location on the chart. The priority is from top to bottom and then left to right. Thus, if for some reason the Savings substate is moved to the left and the Overdraft substate is moved to its right, the Savings substate attains the highest priority, the execution order is changed, and the simulation results will be altered and probably meaningless. But it is possible to override the default and the execution order will be based on explicit ordering. We will do this with the next step.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−29
Chapter 1 The Stateflow Chart
Figure 1.42. The addition of the DollarValue parallel (AND) state
h. We right−click inside the Overdraft parallel state within the TransferOn main state to call the state priorities pop−up menu shown in Figure 1.40, we select Execution Order, and in the Chart window that appears we check the User specified state/transition execution order field as shown in Figure 1.43. We click OK to accept these settings.
1−30
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.43. The Chart dialog box for specifying User specified state/transition execution order
i. We right−click again and from the Execution Order we choose the assignment order shown in Figure 1.44. j. We repeat steps (h) and (i) for the Savings and DollarValue parallel states.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−31
Chapter 1 The Stateflow Chart
Figure 1.44. The submenu for User specified state/transition execution order
k. Using the State tool we add two exclusive (OR) substates inside the Overdraft and Savings parallel (AND) states. Inside the parallel Overdraft and Savings states we name one of the exclusive states On and the other Off. The Stateflow chart now appears as shown in Figure 1.45.
1−32
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.45. The addition of On and Off exclusive (OR) states inside the Overdraft and Savings parallel states
Step 3: We define State Actions and Variables a. States perform actions at different phases of their execution cycle from the time they enter the active phase to the time they re − enter the inactive phase. The three basic state actions are listed in Table 1.2 below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−33
Chapter 1 The Stateflow Chart TABLE 1.2 Type
When Executed
Frequency of Execution
while State is Active
Entry
When state becomes active
Once (to initialize data)
During
While the state is active and no valid transition to another state is available
At every time step (to update data)
Exit
Before transition to another state
Once (to re−configure data for the next transition)
b. We left−click inside the TransferOff state after the last letter of its name to cause a blinking text cursor to appear. We press the Enter key and we type entry: Payments=0; The Stateflow Editor now appears as shown in Figure 1.46.
Figure 1.46. The addition of entry: Payments=0; entry state action
c. We need to add a during action for DollarValue in the third parallel state within the TransferOn state, that is, a Boolean expression to specify whether no Savings and no Overdraft
1−34
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart has occurred, or only Overdraft has occurred, or both Overdraft and Savings have occurred. We click inside the DollarValue state after the last letter of its name to cause a blinking text cursor to appear. We press the Enter key and we type during: Payments=in(Overdraft.On)+in(Savings.On);
The Boolean expression in(Overdraft.On) can be true or false. If true, its value is 1 and Overdraft is active. If false, its value is 0 and Overdraft is inactive. Likewise, the Boolean expression in(Savings.On) can be true or false. Accordingly, the sum of these Boolean expressions indicates whether no Savings and no Overdraft has occurred, or only Overdraft has occurred, or both Overdraft and Savings have occurred. The Stateflow Editor now appears as shown in Figure 1.47.
Figure 1.47. The addition of during: Payments=in(Overdraft.On)+in(Savings.On); during state action
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−35
Chapter 1 The Stateflow Chart Step 4: We define Transitions Between States a. In Stateflow, transitions are added to establish logic flow paths from one state, say A, to another, say B, in a system. If state A is active and state B is inactive, and a transition from state A to state B occurs, state A becomes inactive and state B becomes active. Transitions are unidirectional and are represented by lines with arrowheads. As indicated earlier in this chapter, the unidirectional arrows represent transitions from one state to another and specify the direction of the flow. We recall that two exclusive (OR) states cannot be active at the same time and therefore we must use transitions. However, parallel (AND) states normally execute concurrently and thus we need not add transitions. b. We need to add a transition from the TransferOff to the TransferOn state. To do this, we move the cursor over the top edge of TransferOff and we observe that the cursor shape changes to crosshairs. We hold down the left mouse button, we drag the cursor to the bottom edge of the TransferOn state, we release the mouse, and a transition pointing from the TransferOff to the TransferOn state is formed. We follow the same procedure to create a transition from the TransferOn to the TransferOff state and the Stateflow Editor window now appears as shown in Figure 1.48.
1−36
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.48. The addition of transitions between the TransferOff and the TransferOn states
c. Following the procedure in step (b) above we add transitions between the Off and On states for the Overdraft and Savings states, and the Stateflow Editor appears as shown in Figure 1.49. d. We also need to add default transitions. As stated earlier, since the On and Off states are on the same hierarchical level, we must specify which is the default state, On or Off. For this example, we declare that the default states are Off. To add the default transitions we left− click the Default Transition tool , we move the cursor into the drawing area, and we observe that it changes to a diagonal arrow.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−37
Chapter 1 The Stateflow Chart
Figure 1.49. The addition of transitions On and Off inside the Overdraft and the Savings states
We place the cursor a the left edge of the TransferOff state and when the arrow assumes an horizontal direction, we release the mouse. The default transition is now attached to the TransferOff state and appears as a directed line with an arrow at its head and a small filled−in circle at its tail as shown in Figure 1.50.* Using the same procedure we add default transitions at the top edges of Overdraft.Off and Savings.Off states as shown in Figure 1.50.
* The entire default transition arrow must be placed inside the state that it activates.
1−38
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.50. The addition of default transitions
e. Next, we must specify a condition, action, or event that will allow the transition from one state to another to occur. This is referred to as guarding a transition, and for our example the requirements for guarding the transitions from one exclusive state to another are listed in Table 1.3 below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−39
Chapter 1 The Stateflow Chart TABLE 1.3 Transition
Occurrence
TransferOff to TransferOn
At regular time intervals
TransferOn to TransferOff
At regular time intervals
Guarding Specify an edge−triggered event
Overdraft.Off to Overdraft.On When the ending balance at any time is less than zero
Specify a condition based on the balance dollar amount
Overdraft.On to Overdraft.Off When the ending balance at any time is greater or equal to $50,000 Savings.Off to Savings.On
When the ending balance at any time is less than −50,000
Savings.On to Savings.Off
When the ending balance at any time is greater or equal to −50,000
f.
In the Stateflow Editor window in Figure 1.50, we click the transition from Overdraft.Off to Overdraft.On and we observe that the transition appears highlighted and displays the question mark (?) character. We click the question mark and where a blinking text cursor appears we type the expression [EndingBalance < 0].* Using the same procedure we add the following conditions to the other transitions in Overdraft and Savings. Transition
Condition
Overdraft.On to Overdraft.Off
[EndingBalance >= 50000]
Savings.Off to Savings.On
[EndingBalance < −50000]
Savings.On to Savings.Off
[EndingBalance >= −50000]
The Stateflow Editor now appears as shown in Figure 1.51.
* For readability, it may be necessary to reposition the condition. We do this by clicking outside the condition, then we left− click and drag the condition expression to a new position. Also, as stated earlier, we can change the text size by choosing the Set Font Size from the Edit drop menu.
1−40
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.51. The addition of guarding the transitions
g. In the Stateflow Editor window in Figure 1.51, the TransferOn and TransferOff exclusive (OR) states must change from active to inactive at regular intervals and for this to happen we must define an event that occurs at the rising or falling edge of an input signal. We recall that an event is an non−graphical object that triggers activities during the execution of a Stateflow chart. We add an input event from the Add drop menu by selecting Event>Input from Simulink in the Stateflow Editor in Figure 1.51, and this opens the Event properties dialog window shown in Figure 1.52.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−41
Chapter 1 The Stateflow Chart
Figure 1.52. The Event dialog box
We change the Name field from event to TRANSFERS, we select Port 1, and the Trigger field from Rising to Either. The dialog box now appears as shown in Figure 1.53.
Figure 1.53. The Event dialog box for event TRANSFERS
We click OK to accept these changes and the dialog box closes. Our Simulink model now appears as shown in Figure 1.54 where we observe that a trigger port appears on top of the Stateflow block.
1−42
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.54. The addition of Trigger input to the Transfer Controller Stateflow Chart
h. The next step is to associate the input event TRANSFERS with the transitions. We open the Stateflow Editor, we click the transition from the TransferOff state to the TransferOn state, we click the question mark to obtain a text editor, and we type the name TRANSFERS. We repeat this step to add the same event, i.e., TRANSFERS to the transition from TransferOn to TransferOff. The event TRANSFERS will alternate every time the Stateflow chart detects a rising or falling signal edge. The complete Stateflow Editor window appears as shown in Figure 1.55. Step 5: Adding Triggering Capability to “wake up” the Stateflow Chart a. As stated earlier, we must provide some means to “wake up” a Stateflow chart. This can be achieved by sampling the chart at a specified or inherited rate, using a signal as a trigger, or using one Stateflow chart to activate another. As we’ve learned in Step (g).4 above, the event TRANSFERS controls the transitions from the TransferOff state to the TransferOn state, and vice versa. For this example, we need an edge trigger* to “wake up” the chart at regular and very frequent time intervals. In the next step, we will define a second edge−triggered input event which we will name CLOCK, to “wake up” the Stateflow chart.
* When using edge triggers there can be a delay from the time the trigger occurs to the time the chart begins executing. Thus, an edge trigger causes the chart to execute at the beginning of the next simulation time.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−43
Chapter 1 The Stateflow Chart
Figure 1.55. The complete Stateflow Editor window
b. We define the CLOCK event by double−clicking the Transfer Controller Stateflow block in Figure 1.54, in the Stateflow Editor from the Add drop menu we add an input event by selecting Event>Input from Simulink, in the Event properties dialog box we change the Name field to CLOCK, the Port field to 2, the Trigger field to Either, and the Event dialog box now appears as shown in Figure 1.56. We click OK to accept these settings.
1−44
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.56. Event dialog box for the CLOCK signal
c. We may ponder why only one trigger port appears on top of the Stateflow chart while we have defined two trigger ports, one for the TRANSFERS, Port 1, and the second for CLOCK, Port 2. This poses no problem; the Mux block in the model in Figure 1.54 solves* this problem by providing the necessary indexing into an array. d. We connect the Mux block output to the trigger port of the Stateflow chart, we connect the output of the Financial Operations subsystem to the input of the Stateflow chart, and the output of the Stateflow chart to the top input of the Financial Operations subsystem. Our model is now complete and it is named Example_1_1 as shown in Figure 1.57.
* When the Mux block is connected to the trigger port on top of the Stateflow chart, the index of the signals in the array is associated with the numbered ports. Thus, the TRANSFERS signal at the top input port of the Mux block triggers the event TRANSFERS on trigger Port 1 of the Stateflow chart block, and the CLOCK signal at the second input port of the Mux block triggers the event CLOCK on trigger port 2 of the Stateflow chart block.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−45
Chapter 1 The Stateflow Chart
Figure 1.57. The complete model for Example 1.1
Step 6: Simulation of the Stateflow Chart a. Before starting the simulation, it is recommended that we make sure there is a default transition at every level of the Stateflow hierarchy that contains exclusive (OR) states, that whenever possible, the input data objects inherit properties from the associated Simulink signal, and that output data objects do not inherit types and sizes because the values are back propagated from Simulink and may be unpredictable. b. To set the simulation parameters, we double−click the Transfer Controller block in Figure 1.57, 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 1.58, and we make changes if necessary. We click OK to accept these values.
1−46
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.58. The Configuration Parameters dialog box
c. When a Simulink model that contains a Stateflow Chart block is simulated, we can animate the Stateflow Chart to highlight the states and the transitions as they occur, and this feature provides visual verification that our chart behaves as expected. Animation is enabled by default but we need to specify the speed. To make sure that the animation has been enabled, in the Stateflow Editor window in Figure 1.55 from the Tools drop menu we select Open Simulation Target, and this opens the Stateflow Target Builder dialog box* shown in Figure 1.59.
* A target is a program that executes a Stateflow chart or a Simulink model that contains a Stateflow chart, and the Stateflow Target Builder dialog box in Figure 1.59 is used to configure Stateflow for building targets. Stateflow then builds a simulation target (sfun) file that allows us to simulate our Stateflow application in Simulink.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−47
Chapter 1 The Stateflow Chart
Figure 1.59. The Target Builder window for selecting Target Options and Coder Options
d. In the Stateflow Target Builder dialog box in Figure 1.59, we click the Coder Options button, and the Stateflow sfun Coder Options dialog box appears as shown in Figure 1.60, where we observe that Enable debugging/animation is checked.
Figure 1.60. The Coder Options window to Enable debugging/animation
e. To set the animation speed, from the Stateflow Editor window in Figure 1.55 we click the Debug tool and the Stateflow Debugging window appears as shown in Figure 1.61 where the Delay (sec) has been set to 1 sec so that the animation will proceed at the slowest speed.
1−48
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.61. The Stateflow Debugging window to start simulation with breakpoints
f.
To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the debugger to pause simulation during run−time activities. Breakpoints that can set are listed below. Breakpoint
Description
Chart Entry
Simulation halts when Stateflow chart “wakes up”
Event Broadcasta
Simulation halts when an event such as TRANSFERS and / or CLOCK occurs.
State Entry
Simulation halts when a state becomes active
a. To keep simulation running at a reasonable pace, we will not use Event Broadcast. Otherwise, simulation would pause at every rising or falling edge of the TRANSFERS and CLOCK signals.
g. In the Stateflow Debugging window in Figure 1.61, we check Chart Entry and State Entry as breakpoints and this window now appears as shown in Figure 1.62.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−49
Chapter 1 The Stateflow Chart
Figure 1.62. The Stateflow Debugging window with selected breakpoints
The option Browse Data in Figure 1.62 is a menu for observing data when simulation pauses at a breakpoint. In the window of Figure 1.62 the Browse Data is inactive but it will become active when simulation begins and halts at a breakpoint. h. Before simulation begins, Stateflow builds the simulation target by performing the following actions: • Parses the Stateflow chart for errors such as no default transition at every level of the Stateflow hierarchy that contains exclusive (OR) states, input data objects do not inherit properties from the associated Simulink signal, and output data objects do inherit types and sizes. • Generates C code that represents the behavior of the Stateflow chart • Builds the generated code into an executable program for the simulation target, referred to as sfun target. • Creates a directory referred to as sfprj in the directory where the chart resides to store the generated files that make up the sfun target. • Creates a MEX (MATLAB executable) file that corresponds to the C source file During each of these processes, status messages are displayed at the MATLAB Command Window.
1−50
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart i. We are now ready to begin simulation but before we issue the Start command in the Stateflow Debugging window, we open the Scope block in the model of Figure 1.57, Page 1−46. We position the Scope block, the Stateflow Editor window, and the Stateflow Debugger window so that all are visible as shown in Figure 1.63.
Figure 1.63. The Stateflow Editor, the Scope block, and the Stateflow Debugging windows for data observation
j. In the Stateflow Debugger window in Figure 1.63, we begin simulation by clicking the Start button. We observe that the TransferOff state appears highlighted as part of the animation and it is shown in Figure 1.64. This indicates that the chart is “awaken” by the CLOCK signal and the default transition arrow has activated the TransferOff state.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−51
Chapter 1 The Stateflow Chart
Figure 1.64. First indication that the Stateflow Chart is awaken
We notice also that the status panel at the upper part of the Stateflow Debugger window shows the activities at the first breakpoint and that the Browse Data option is now enabled as shown in Figure 1.65.
1−52
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.65. The Stateflow Debugger for continuing simulation
k. In the Stateflow Debugger window in Figure 1.65, we click the down arrow to the right of the Browse Data option and we select Watched Data (Current Chart) from the drop menu. The Stateflow Debugger window now appears as shown in Figure 1.66 and allows us to view the value of the output of the Stateflow Chart, i.e., Payments.* 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 Payments and MATLAB displays Payments = 0 To view the value of the input of the Stateflow Chart, i.e, EndingBalance, at the command prompt debug>> we type EndingBalance and MATLAB displays EndingBalance = 9.8252e+003 that is, the initial deposit of $10,000 in the checking account is now reduced to $9,825.20. * We recall from Page 1−24, Payments was assigned a minimum value of 0 and a maximum value of 2.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−53
Chapter 1 The Stateflow Chart
Figure 1.66. Browse information for watched data in Stateflow Chart
l. To resume simulation, in the Stateflow Debugger window we uncheck the breakpoint Chart Entry, and we click the Continue button repeatedly until the status panel at the upper part of the Stateflow Debugger window indicates Simulink Time: 10.000000. We click the Continue button one more time and we observe that the TransferOn state is now active while the TransferOff state has returned to the inactive state as shown in Figure 1.67.
1−54
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.67. The activation of the TransferOn state after the rising edge of the TRANSFERS signal
m. 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 eventually both the On states become active as shown in Figure 1.68, and when this occurs, the Stateflow Debugger window indicates the maximum value of the output of the Stateflow Chart, i.e., Payments = 2.*
* As described in Page 1−24, this is the maximum value and represents the condition where Overdraft On and Savings On are both active.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−55
Chapter 1 The Stateflow Chart
Figure 1.68. The Stateflow Editor when both the Overdraft and Savings states are On
n. As we continue clicking the Continue button repeatedly, eventually the status panel at the upper part of the Stateflow Debugger window indicates Simulink Time: 290.000000. At this time the TRANSFERS signal from the Function Builder block returns to 0 and the TransferOff state becomes active while the TransferOn state becomes inactive as shown in Figure 1.69.
1−56
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.69. The deactivation of the TransferOn state after the falling edge of the TRANSFERS signal
o. We continue the simulation until we reach the 300 sec point (end of simulation time) and we observe that the Stateflow chart goes back to “sleep”. At this time the Scope block in the model of Figure 1.57, Page 1−46, displays the waveform shown in Figure 1.70, and this waveform shows how the EndingBalance output of the Stateflow chart changes from the start to the end of the simulation time.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−57
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
Procedure for Creating a Stateflow Chart
Figure 1.73. The Stateflow Builder showing state inconsistencies
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−61
Chapter 1 The Stateflow Chart
Figure 1.74. The Stateflow Editor after double−clicking Coder Warnings
1−62
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.75. The Stateflow Editor after removal of inconsistencies
We save the model as Example_1_1_Debug in preparation for the debugging data range violations below. b. In the Stateflow Editor window in Figure 1.74, we modify the during action in the DollarValue state by adding 1 to it, that is, it now reads as during: Payments=in(Overdraft.On)+in(Savings.On) +1;
as shown in Figure 1.76.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−63
Chapter 1 The Stateflow Chart
Figure 1.76. Stateflow Editor with data range violation
We open the Stateflow debugger by clicking the Debug tool , we uncheck all breakpoints, under Error checking options we check Data Range, and the Stateflow Debugging dialog box now appears as shown in Figure 1.77.
1−64
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.77. Stateflow debugger for detecting data range violations
We save the Stateflow Editor chart, we again build the chart, and the Stateflow Builder window in Figure 1.78 reports no errors.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−65
Chapter 1 The Stateflow Chart
Figure 1.78. Stateflow Builder indicating no parsing errors
We return to the Stateflow Debugging dialog box in Figure 1.77 and we click the Start button to begin simulation. To continue simulation we click the Continue button repeatedly, and after some time simulation pauses and Stateflow generates the Simulation Diagnostics window shown in Figure 1.79.
1−66
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.79. Simulation Diagnostics reporting Multiport Switch block error
To isolate the problem, we double click the Block error red bullet in the Simulation Diagnostics window in Figure 1.79, and this opens the Financial Operations subsystem shown in Figure 1.80.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−67
Chapter 1 The Stateflow Chart
Figure 1.80. Error indication in the Multiport Switch block of the Financial Operations subsystem
In Figure 1.80 we click the Launch Model Explorer tool and this opens the Model Explorer window shown in Figure 1.81 where the properties of DollarValue are shown on the right pane. Because the simulation is still running, this pane is read−only.
1−68
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart
Figure 1.81. Model Explorer window indicating data range violation
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−69
Chapter 1 The Stateflow Chart 1.5 Summary • A finite state machine is a model describing the behavior of a finite number of states, the transitions between those states, and actions. A finite state machine can be represented either by a state diagram or a state transition table. • 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 condition is a Boolean expression that can be true (logic 1) or false (logic 0). In Stateflow, conditions are enclosed in square brackets. • An event is an action that can trigger a variety of activities. For example, in a typical household space heater a switch allows a transition to occur between medium state and high state. Thus, event driven systems allow the transition from one operating mode to another in response to events and conditions. Event−driven systems can be implemented as finite−state machines. • Stateflow provides us the necessary graphical objects to construct finite−state machines. Like Simulink, we can drag and drop objects to create state−transition charts in which a series of transitions directs a flow of logic from one state to another. • Exclusive (OR) states are represented graphically by solid rectangles. No two or more Exclusive (OR) states can be active or execute at the same time. • Parallel (AND) states are represented graphically by dashed rectangles with a number in the upper right corner. The numbers indicate the execution order. Two or more parallel (AND) states at the same hierarchical level can be active at the same time but execute in serial fashion.
• The unidirectional arrows and specify the direction of the flow.
represent transitions from one state to another
• When two or more Exclusive (OR) states that are on the same hierarchical level, we must specify which is the default state. The default state is identified by an arrow with a solid dot tail is directed towards that state. For this purpose this arrow is referred to as the default transition. • When the Stateflow chart is inactive, it is in a dormant state, and when the chart is first activated, the default transition makes the chart active. We usually use a clock signal to “wake up” the chart.
1−70
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Summary • A state action is an action whose execution is based on the status of the state. • Entry actions are executed when the state is entered, i.e., when it first becomes active. The syntax for entry actions is entry: one or more actions; en: one or more actions;
• During actions are executed while a state is active and no transition to another state exists. The syntax for during actions is during: one or more actions; du: one or more actions;
• A condition is a Boolean expression that allows a transition to occur when the expression is true. A condition is a text label for the transition and it is enclosed in square brackets ([ ]). • An event is an object that can initiate several activities such as “waking up” a Stateflow chart, transitions to occur from one state to another, and executions of actions. • The recommended procedure for creating a Simulink model that contains one or more Stateflow charts is as follows: 1. Define the Interface to Simulink a. Invoke MATLAB and from the main window select Simulink by clicking on the Simulink icon
. This opens the Simulink Library Browser window.
b. In the Simulink Library Browser window click the Create a new model icon observe that a new empty model appears.
and
c. From the Simulink Library Browser window click and drag the Simulink blocks comprising the model into the empty Simulink model. d. To create a subsystem, we enclose all blocks except the Inport and Outport blocks within a bounding box, and from the Edit drop menu we choose Create Subsystem. e. From the Simulink Library Browser window we click and drag a Chart block from the Stateflow subnode under the Simulink Extras Library f. To define the input of the Stateflow Chart block, we double−click this block, and from the Stateflow Editor window that appears, from the Add drop menu we select Data>Input from Simulink, and this opens the Data window. In the Name field that appears under the General tab, we change the Name field to an appropriate name and we leave other fields in their default values. We select the Value Attributes tab and we check the Watch in debugger box. This allows us to observe the value of the name that we selected at breakpoints during simulation. Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−71
Chapter 1 The Stateflow Chart g. To define the output of the Stateflow Chart block, we double−click this block, and from the Stateflow Editor window that appears, from the Add drop menu we select Data>Output to Simulink, and this opens the Data window. In the Name field that appears under the General tab, we change the name to an appropriate name and we leave other fields in their default values. We select the Value Attributes tab, for the Limit range we specify appropriate values for Minimum and Maximum. We also check the Watch in debugger box to allow us to observe the value of the name that we selected at breakpoints during simulation. 2. Define the States for each Mode of Operation a. In the Simulink model we double−click the Stateflow Chart block Transfer Controller block and from the Stateflow Editor window that appears, from the object palette on the left side of the Stateflow Editor window we click the State tool , we move it to the drawing area, and we observe that it changes to a rectangle with rounded corners and with a flashing text cursor at the upper left corner. This is a solid rectangle and it represents an exclusive (OR) state. b. At the flashing text cursor we enter a name appropriate for this state, e.g., PowerOn. We click the State tool again and we draw another state below it, and we name it appropriately, e.g., PowerOff. d. In most applications we want to place parallel (AND) states within exclusive (OR) states. To do this, from the Stateflow Editor we right−click inside the exclusive (OR) state and from the submenu of Figure that appears we select Decomposition> Parallel (AND). Then, we left−click the State tool in the Stateflow Editor and we place the desired number of Parallel (AND) states inside the exclusive (OR) state. These states appear as rectangles with rounded corners and dashed lines indicating that they are parallel (AND) states. These parallel (AND) states display numbers in their upper right corners. These numbers specify the order of execution during simulation. We name the parallel (AND) states appropriately. e. We now need to add an observer state whose purpose will be to monitor the status of the parallel (AND) states inside an exclusive (OR) state. To do this, we left−click the State tool again and we place another substate within the exclusive (OR) state and we name it appropriately. f. By default, Stateflow execution order is based on implicit ordering. This means that the execution order of parallel states depends on their location on the chart. The priority is
1−72
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Summary from top to bottom and then left to right. Thus, if for some reason a substate that is originally located below another substate and then is relocated above it, this substate attains the higher priority, the execution order is changed, and the simulation results are altered. But it is possible to override the default and the execution order will be based on explicit ordering. We specify explicit ordering by right−clicking a parallel (AND) state inside an explicit (OR) state, in the state priorities submenu that appears, we select Execution Order, and in the Chart window that appears we check the User specified state/transition execution order field. g. Normally, we add exclusive (OR) substates inside parallel (AND) states. For instance, to add to opposing states, e.g., On and Off, we use the State tool to add two exclusive (OR) substates inside a parallel (AND) state, and we name one of the exclusive states On and the other Off. 3. Define State Actions and Variables States perform actions at different phases of their execution cycle from the time they enter the active phase to the time they re−enter the inactive phase. The three basic state actions are listed in Table 1.3, Page 1−34. 4. Define Transitions Between States a. In Stateflow, transitions are added to establish logic flow paths from one state, say A, to another, say B, in a system. If state A is active and state B is inactive, and a transition from state A to state B occurs, state A becomes inactive and state B becomes active. Transitions are unidirectional and are represented by lines with arrowheads. As indicated earlier in this chapter, the unidirectional arrows represent transitions from one state to another and specify the direction of the flow. We recall that two exclusive (OR) states cannot be active at the same time and therefore we must use transitions. However, parallel (AND) states normally execute concurrently and thus we need not add transitions. b. To add a transition from one exclusive (OR) state to another opposing exclusive (OR) state, e.g., PowerOff state to PowerOn state, we move the cursor over the top edge of PowerOff state and we observe that the cursor shape changes to crosshairs. We hold down the left mouse button, we drag the cursor to the bottom edge of the PowerOn state, we release the mouse, and a transition pointing from the PowerOff to the PowerOn state is formed. We follow the same procedure to create a transition from the PowerOn state to the PowerOff state. c. We also need to add default transitions. As stated earlier, since the On and Off states are on the same hierarchical level, we must specify which is the default state, On or Off. Normally, we declare that the default states are Off. To add the default transitions, we left−
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−73
Chapter 1 The Stateflow Chart click the Default Transition tool , we move the cursor into the drawing area, and we observe that it changes to a diagonal arrow. We place the cursor at the left edge of the Off state and when the arrow assumes an horizontal direction, we release the mouse. The default transition is now attached to the Off state and appears as a directed line with an arrow at its head and a small filled−in circle at its tail. e. We must specify a condition, action, or event that will allow the transition from one state to another to occur. This is referred to as guarding a transition. Typical requirements for guarding the transitions from one exclusive state to another are listed in Table 1.4, Page 1− 40. To add a condition, we click the transition arrow and we observe that the transition appears highlighted and displays the question mark (?) character. We click the question mark and where a blinking text cursor appears we type desired the expression, e.g., [Temperature < 100]. f. Typically, an On state and an Off exclusive (OR) states must change from active to inactive at regular intervals and for this to happen we must define an event that occurs at the rising or falling edge of an input signal. We recall that an event is an non−graphical object that triggers activities during the execution of a Stateflow chart. We add an input event from the Add drop menu in the Stateflow Editor by selecting Event>Input from Simulink and this opens an Event properties dialog window. We change the Name field from event to an appropriate name, we select the Port number, and from the Trigger field we choose Rising, Falling, or Either. g. We need to associate an input event with the transitions. To do this, we open the Stateflow Editor, we click the transition, say from the Off state to the On state, we click the question mark to obtain a text editor, and we type the appropriate name, and this event will alternate every time the Stateflow chart detects a rising, falling, or either signal edge as we have specified in Step 4(f) above. 5. Adding Triggering Capability to “wake up” the Stateflow Chart a. We must provide some means to “wake up” a Stateflow chart at regular and very frequent time intervals. This can be achieved with a CLOCK signal at a specified frequency. b. It is possible to define two or more trigger ports with only one trigger port input on top of a Stateflow chart. This can be done by using a Mux block to provide the necessary indexing. 6. Simulation of the Stateflow Chart a. Before starting the simulation, it is recommended that we make sure there is a default transition at every level of the Stateflow hierarchy that contains exclusive (OR) states, that whenever possible, the input data objects inherit properties from the associated
1−74
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Summary Simulink signal, and that output data objects do not inherit types and sizes because the values are back propagated from Simulink and may be unpredictable. b. To set the simulation parameters, we double−click the Stateflow Chart block, from the Simulation drop menu in the Stateflow Editor window we select Configuration Parameters, we click Solver in the left Select pane, and in the Simulation time and Solver options panes we verify our selections and we make changes if necessary. c. When a Simulink model that contains a Stateflow Chart block is simulated, we can animate the Stateflow Chart to highlight the states and the transitions as they occur, and this feature provides visual verification that our chart behaves as expected. Animation is enabled by default but we need to specify the speed. To make sure that the animation has been enabled, from the Tools drop menu in the Stateflow Editor window we select Open Simulation Target, and this opens the Stateflow Target Builder dialog box. In the Stateflow Target Builder dialog box we click the Coder Options button, and the Stateflow sfun Coder Options dialog box appears where we observe that Enable debugging/animation is checked. d. To set the animation speed, from the Stateflow Editor window we click the Debug tool and the Stateflow Debugging window appears. For the animation to proceed at the slowest speed, we set the Delay (sec) to 1 sec. e. To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the debugger to pause simulation during run−time activities. We set breakpoints as follows: In the Stateflow Debugging window we check Chart Entry and State Entry as breakpoints. The option Browse Data i is a menu for observing data when simulation pauses at a breakpoint. Initially, the Browse Data is inactive but it will become active when simulation begins and halts at a breakpoint. Before simulation begins, Stateflow builds the simulation target parses the Stateflow chart for errors such as no default transition at every level of the Stateflow hierarchy that contains exclusive (OR) states, input data objects do not inherit properties from the associated Simulink signal, and output data objects do inherit types and sizes. Then, it generates C code that represents the behavior of the Stateflow chart and builds the generated code into an executable program for the simulation target, referred to as sfun target. Next, it creates a directory referred to as sfprj in the directory where the chart resides to store the generated files that make up the sfun target. Finally, it creates a MEX (MATLAB executable) file that corresponds to the C source file. During each of these processes, status messages are displayed at the MATLAB Command Window.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−75
Chapter 1 The Stateflow Chart f. With the Stateflow Debugger window visible, we begin simulation by clicking the Start button. We observe that the Off state appears highlighted as part of the animation This indicates that the chart is “awaken” by a CLOCK signal, if present, and the default transition arrow has activated the Off state. We notice that the status panel at the upper part of the Stateflow Debugger window shows the activities at the first breakpoint and that the Browse Data option is now enabled. g. In the Stateflow Debugger window we click the down arrow to the right of the Browse Data option and we select Watched Data (Current Chart) from the drop menu. The Stateflow Debugger window now appears and allows us to view the value of the output of the Stateflow Chart, i.e., the output name that we defined earlier. 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 the output name. To view the value of the input of the Stateflow Chart at the command prompt debug>> we type the input name that we defined earlier. h. To resume simulation, in the Stateflow Debugger window we uncheck the breakpoint Chart Entry, and we click the Continue button. 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 eventually the On state becomes active and when this occurs, the Stateflow Debugger window now indicates the maximum value of the output of the Stateflow Chart. i. As we continue clicking the Continue button repeatedly, eventually the status panel at the upper part of the Stateflow Debugger window indicates the ending time in the Simulink Time field. At this time the signal from the Function Builder block returns to 0 and the Off state becomes active while the On state becomes inactive, and when the simulation time reaches its maximum value, the Stateflow chart goes back to “sleep”. 7. Debugging the Stateflow Chart We can debug a Stateflow chart for errors such as inconsistency errors, and for debugging data range violations. a. To check for inconsistency errors, we open the Stateflow Editor window and we invoke the Stateflow debugger by clicking Debug tool to make sure that State Inconsistency is checked in the Error checking options panel. In the Stateflow Editor window we click the Build tool in the Stateflow Editor, and the Stateflow Builder window opens. If inconsistency errors are present, Stateflow generates coder warnings indicated
1−76
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Summary by gray bullets. These warnings indicate that states identified by some numbers have no unconditional path to one or more substates. To locate the offending states in the Stateflow Builder window chart, we double−click the coder warnings text or we click the link to the state numbers in the status panel at the bottom of the Stateflow Builder dialog box, and Stateflow highlights the offending states in the Stateflow Editor chart. After making the necessary corrections, we build the chart again, to make sure that the chart builds successfully without parser or code generation errors. b. To check for data range violations, we open the Stateflow debugger by clicking the Debug tool , we uncheck all breakpoints, under Error checking options we check Data Range, and the Stateflow Debugging dialog box appears, and the Stateflow Builder window reports no errors. We return to the Stateflow Debugging dialog box in and we click the Start button to begin simulation. To continue simulation we click the Continue button repeatedly, and if a data range violation exists, after some time simulation pauses and Stateflow generates the Simulation Diagnostics window. To isolate the problem, we double click the Block error red bullet in the Simulation Diagnostics window and this opens the offending state, block, or subsystem, and we click the Launch Model Explorer tool . This opens the Model Explorer window and the source of the problem is shown on the right pane. If the simulation is still running, this pane is read−only.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−77
Chapter 1 The Stateflow Chart 1.6 Exercise for the Reader ABC Company manufactures PC boards and these are sold to several computer assembly companies. The daily orders and quantities for boards vary significantly, and for this reason ABC Company maintains three working shifts, first, second, and graveyard shift. Statistics show that, on a weekly basis, the minimum number of boards delivered is 5,000 while the maximum is 15,000. Create a Simulink model that includes a Stateflow chart to schedule the number of shifts based on the quantities shown below so that the company will meet the promised delivery dates to its customers. First shift: Less than 5,000 boards First shift + 2 hours overtime: 5,000 or more but less than 8,000 boards Second shift: 8,000 or more but less than 12,000 boards Graveyard shift: 12,000 or more boards
1−78
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise 1.7 Solution to the End−of−Chapter Exercise Assumptions: 1. The manufacturing plant will be a Simulink subsystem with two inputs and one output as shown by the block diagram below. production boards max Manufacturing Plant
2. The max input represents the maximum number of boards that can be manufactured in a given time period and we will assume a maximum number of 15,000 boards. 3. A provision will be made for manpower. This is a measure of the number of employees expected to be present minus the number of employees absent, e.g., on vacation or sick leave. We will represent manpower with a Gain block that provides a constant multiplier that is used in computing the actual number of employees in the manufacturing plant over a given period. For this constant multiplier we will assume a value of 0.025. 4. Normally, the first shift is considered to be the most productive while the graveyard shift is the least productive. For productivity we will be using a constant multiplier derived from the value of production that will be the output from the Stateflow Chart block, and the Stateflow Chart will assign one of four productivity factors each with a value that will serve as an index into a Multiport Switch block. Using this index, the Multiport Switch block will select a productivity multiplier that is directly proportional to the productivity factor. The productivity multiplier for each shift is shown in the table below. Productivity by Shift
Productivity Number
Productivity Multiplier
First Shift ON − No Overtime
0
0.00
First Shift ON 2−hr Overtime The number of the Boards produced is lowered by the productivity multiplier −0.05
1
−0.05
Second Shift ON The number of the Boards produced is lowered by the productivity multiplier −0.10
2
−0.10
Graveyard Shift ON The number of the Boards produced is lowered by the productivity multiplier −0.02
3
−0.02
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−79
Chapter 1 The Stateflow Chart 5. The manufacturing plant computes the number of manufactured boards taking into consideration the manpower multiplier and the productivity multiplier. The output boards of the manufacturing plant changes with time and we represent this change as board_change where its value is computed from the expression boards_change = [ ( max – boards ) × manpower multiplier ] + [ ( max – boards ) × productivity multiplier ]
and the summation of those changes will be performed with an Integrator block with an assumed initial value 2,000, that is, boards ( t ) =
t
∫t ( boards_change ) dt + 2000 0
6. Simulation time will be 300 sec. 7. The Stateflow Chart needs to monitor the number of boards produced by the manufacturing plant at regular intervals. Therefore, we will use a CLOCK signal that will be provided by a Signal Builder block and the Stateflow Chart will include an edge trigger event that will “wake−up” the chart at the rising or falling edge of the clock. The Signal Builder block will also provide a pulse signal named SWITCH to activate the Stateflow Chart to On and Off. The CLOCK signal will be a square wave with the following settings: Frequency: 1.0 Amplitude: 1.0 Offset: 1.0 % Duty cycle: 50%
The SWITCH signal will be a pulse of duration 25 sec with rising edge at 25 sec and falling edge at 50 sec. We begin by typing sfnew* at the MATLAB Command prompt, and we observe that a new untitled Simulink model opens with a Stateflow chart. We invoke the Simulink Library Browser window and we click and drag the following Simulink blocks into the empty Simulink model with the Stateflow chart: Four Constant blocks, a Product block, a Gain block, an Integrator block, two Inport blocks and an Outport block from the Commonly Used Blocks Library, and a Multiport Switch from the Signal Routing Library. The Constant blocks and the Gain block perform the functions described by the annotations. We click the Integrator block and we specify the initial condition as 0 . We interconnect these blocks as shown below. * This is a shortcut for adding a Stateflow block to a new Simulink model.
1−80
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
To create a subsystem, we enclose all blocks, except the Inport and Outport blocks, within a bounding box, from the Edit drop menu we choose Create Subsystem, we reshape the interconnecting lines, and we label it as Manufacturing Plant. We double−click the subsystem block and we rename the Inport and Outport blocks as production, max, and boards, and the components of the subsystem appear as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−81
Chapter 1 The Stateflow Chart
Our Simulink model now appears as shown below.
We stretch the window of the model above and we add the following blocks:
1−82
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise A Signal Builder block from the Sources Library. A Mux block (heavy vertical bar) from the Commonly Used Blocks Library A Scope block from the Commonly Used Blocks Library A Constant block from the Commonly Used Blocks Library The model now appears as shown below.
We double−click the Signal Builder block and the waveform shown below appears.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−83
Chapter 1 The Stateflow Chart
g. From the Axes drop menu we select Change Time Range, we set Min time to 0, Max time to 300, we change the name field from Signal 1 to SWITCH, we click on the rising (left) edge of the waveform to select it,* in the T: field under Left Point we enter 10, we click the falling (right) edge of the waveform to select it, in the T: field under Left Point we enter 290, and we click OK to accept it. The waveform of the Signal Builder block is now as shown below.
* When properly selected, it appears as a heavy red line and the fields in the lower part of the window become active
1−84
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
From the Signal drop menu in the Signal Builder window above we select New and from it we choose Square Wave. In the Square Wave dialog box below we enter the parameters shown.
We change the name field to CLOCK, we click OK to accept these values, and the Signal Builder block now appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−85
Chapter 1 The Stateflow Chart
The SWITCH signal is used to allow transitions to occur between the states AddShiftOff and AddShiftOn (to be defined shortly), at each rising or falling edge of a pulse signal, and the CLOCK is used to “wake up” the Stateflow chart at each rising or falling edge of a square wave signal. To define the input of the Stateflow Chart block in the model shown on Page 1−83, we double− click this block, and we observe that the Stateflow Editor window appears as shown below.
1−86
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
From the Add drop menu of the Stateflow Editor above, we select Data>Input from Simulink, and this opens the Data window shown below.
In the Name field that appears under the General tab of the Data dialog box above, we change the name to boards and we leave other fields in their default values. We select the Value Attributes tab and we check the Watch in debugger box. This will allow us to observe the value of boards at breakpoints during simulation.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−87
Chapter 1 The Stateflow Chart To define the output of the Stateflow Chart block in the model shown on Page 1−83, we double− click this block, and we observe that the Stateflow Editor window appears as shown in the previous page. From the Add drop menu we select Data>Output to Simulink, and this opens the Data window shown in the previous page. In the Name field that appears under the General tab, we change the name to production and we leave other fields in their default values. We select the Value Attributes tab, for the Limit range we specify 0 for Minimum and 3 for Maximum, where 0 will represents first shift−no overtime, 1 will represent first shift 2−hr overtime On, 2 will represent second shift On, and 3 will represent graveyard shift On. We also check the Watch in debugger box to allow us to observe the value of production at breakpoints during simulation. Our Simulink model should now look like that shown below where we have renamed the Stateflow Chart block Shift Controller.
In the Simulink model above, we double−click the Shift Controller block and the Stateflow Editor window appears as shown below.
1−88
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
From the object palette on the left side of the Stateflow Editor window above we click the State tool , we move it to the drawing area, and we observe that it changes to a rectangle with rounded corners and with a flashing text cursor on the upper left corner as shown below. This is a solid rectangle and it represents an exclusive (OR) state.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−89
Chapter 1 The Stateflow Chart At the flashing text cursor we enter AddShiftOn to name this state,* and we stretch the rectangle. The Stateflow editor window now appears as shown below.
We click the State tool again and we draw a smaller state below the AddShiftOn state, and we name it AddShiftOff. The Stateflow Editor window now appears as shown below.
* We can change the text size by choosing the Set Font Size from the Edit drop menu.
1−90
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
In the Stateflow Editor window above we right−click inside the AddShiftOn state and from the pop−up menu below we select Decomposition> Parallel (AND).
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−91
Chapter 1 The Stateflow Chart
We left−click the State tool in the Stateflow Editor window in the previous page and we place three states inside the AddShiftOn state. We observe that these three states appear as rectangles with rounded corners and dashed lines indicating that they are parallel (AND) states. We also observe that these parallel states display numbers in their upper right corners. These numbers specify the order of execution during simulation. We name these parallel states Overtime, Second, and Graveyard, and the Stateflow Editor window now appears as shown below.
1−92
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
We now need to add an observer state whose purpose will be to monitor the status of the Overtime, Second, and Graveyard states. and we place another parallel (AND) substate within the We left−click the State tool AddShiftOn state under the Overtime, Second, and Graveyard states. We name this substate BoardNumber and the Stateflow Editor appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−93
Chapter 1 The Stateflow Chart
We recall that, by default, Stateflow execution order is based on implicit ordering. This means that the execution order of parallel states depends on their location on the chart. The priority is from top to bottom and then left to right. Thus, if for some reason the Savings substate is moved to the left and the Overdraft substate is moved to its right, the Savings substate attains the highest priority, the execution order is changed, and the simulation results are altered. But it is possible to override the default and the execution order will be based on explicit ordering. We will do this with the next step. We right−click inside the Overtime parallel state within the AddShiftOn exclusive (OR) main state to call the state priorities pop−up menu below, we select Execution Order.
1−94
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
In the Chart window that appears below we check the User specified state/transition execution order field as shown. We click OK to accept these settings.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−95
Chapter 1 The Stateflow Chart
We right−click again and from the Execution Order we choose the assignment order shown in below. We repeat these steps for the Second, Graveyard, and BoardNumber parallel states.
1−96
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
Using the State tool we add two exclusive (OR) substates inside the Overtime, Second, and Graveyard states. Inside the parallel Overtime, Second, and Graveyard states, we name one of the exclusive states On and the other Off. The Stateflow chart now appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−97
Chapter 1 The Stateflow Chart
We recall that states perform actions at different phases of their execution cycle from the time they enter the active phase to the time they re−enter the inactive phase. For convenience, the three basic state actions are repeated in the table below. Type
When Executed
Frequency of Execution
while State is Active
Entry
When state becomes active
Once (to initialize data)
During
While the state is active and no valid transition to another state is available
At every time step (to update data)
Exit
Before transition to another state
Once (to re−configure data for the next transition)
We left−click inside the AddShiftOff state after the last letter of its name to cause a blinking text cursor to appear. We press the Enter key and we type
1−98
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise entry: production=0;
The Stateflow Editor now appears as shown below.
We also need to add a during action for BoardNumber in the fourth parallel state within the AddShiftOn state, that is, a Boolean expression to specify whether no Graveyard, no Second, and no Overtime has occurred, or only Overtime has occurred, or Overtime and Second have occurred, or all three Overtime, Second, and Graveyard have occurred. We click inside the BoardNumber state after the last letter of its name to cause a blinking text cursor to appear. We press the Enter key and we type during: production = in(Overtime.On) + in(Second.On) + in(Graveyard.On);
The Boolean expression in(Overtime.On) can be true or false. If true, its value is 1 and Overtime is active. If false, its value is 0 and Overtime is inactive. Likewise, the Boolean expressions in(Second.On) and in(Graveyard.On) can be true or false. Accordingly, the sum of these Boolean expressions indicates whether no Graveyard, no Second, and no Overtime has occurred, or only
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−99
Chapter 1 The Stateflow Chart Overtime has occurred, or Overtime and Second have occurred, or all three Overtime, Second, and Graveyard have occurred. The Stateflow Editor window now appears as shown below.
We need to add a transition from the AddShiftOff to the AddShiftOn state. To do this, we move the cursor over the top edge of AddShiftOff and we observe that the cursor shape changes to crosshairs. We hold down the left mouse button, we drag the cursor to the bottom edge of the AddShiftOn state, we release the mouse, and a transition pointing from the AddShiftOff to the AddShiftOn state is formed. We follow the same procedure to create a transition from the AddShiftOn to the AddShiftOff state and the Stateflow Editor window now appears as shown below.
1−100
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
Following the procedure above we add transitions between the Off and On states for the Overtime, Second, and Graveyard states, and the Stateflow Editor window appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−101
Chapter 1 The Stateflow Chart
We also need to add default transitions. As stated earlier, since the On and Off states are on the same hierarchical level, we must specify which is the default state, On or Off. For this exercise, we declare that the default states are Off. To add the default transitions we left−click the Default Transition tool , we move the cursor into the drawing area, and we observe that it changes to a diagonal arrow. We place the cursor a the left edge of the AddShiftOff state and when the arrow assumes an horizontal direction, we release the mouse. The default transition is now attached to the AddShiftOff state and appears as a directed line with an arrow at its head and a small filled−in circle at its tail.* Using the same procedure we add default transitions at the top edges of Overtime.Off, Second.Off, and Graveyard.Off states as shown below.
* The entire default transition arrow must be placed inside the state that it activates.
1−102
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
Next, we must specify a condition, action, or event that will allow the transition from one state to another to occur. This is referred to as guarding a transition, and for our example the requirements for guarding the transitions from one exclusive state to another are listed in the table below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−103
Chapter 1 The Stateflow Chart Transition
Occurrence
Guarding
AddShiftOff to AddShiftOn
At regular time intervals
AddShiftOn to AddShiftOff
At regular time intervals
Overtime.Off to Overtime.On
When the orders are for 5000 or more boards
Overtime.On to Overtime.Off
When the orders are for less than 5000 boards
Second.Off to Second.On
When the orders are for 8000 or more boards
Second.On to Second.Off
When the orders are for less than 8000 boards
Graveyard.Off to Graveyard.On
When the orders are for 12000 or more boards
Graveyard.On to Graveyard.Off
When the orders are for less than 12000 boards
Specify an edge−triggered event Specify a condition based on the number of boards ordered
In the Stateflow Editor window, we click the transition from Overtime.Off to Overtime.On and we observe that the transition appears highlighted and displays the question mark (?) character. We click the question mark and where a blinking text cursor appears we type the expression [boards >= 5000].* Using the same procedure we add the following conditions to the other transitions in Second and Graveyard. Transition
Condition
Overtime.On to Overtime.Off
[boards < 5000]
Second.On to Second.Off
[boards < 8000]
Second.Off to Second.On
[boards > = 8000]
Graveyard.On to Graveyard.Off
[boards < 12000]
Graveyard.Off to Graveyard.On
[boards > = 12000]
The Stateflow Editor window now appears as shown below.
* For readability, it may be necessary to reposition the condition. We do this by clicking outside the condition, then we left− click and drag the condition expression to a new position. Also, as stated earlier, we can change the text size by choosing the Set Font Size from the Edit drop menu.
1−104
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
In the Stateflow Editor window above, the AddShiftOn and AddShiftOff exclusive (OR) states must change from active to inactive at regular intervals and for this to happen we must define an event that occurs at the rising or falling edge of an input signal. We recall that an event is an non−graphical object that triggers activities during the execution of a Stateflow chart. We add an input event from the Add drop menu by selecting Event>Input from Simulink in the Stateflow Editor window above and this opens the Event properties dialog window shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−105
Chapter 1 The Stateflow Chart
We change the Name field from event to SWITCH, we select Port 1, and the Trigger field from Rising to Either. The updated Event dialog box now appears as shown below.
We click OK to accept these changes and the dialog box closes. Our Simulink model now appears as shown below where we observe that a trigger port appears on top of the Stateflow block as shown in the model below. We save this model as Exercise_1_1.
1−106
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
The next step is to associate the input event SWITCH with the transitions. We double−click the Shift Controller Stateflow chart in the model above to open the Stateflow Editor window, we click the transition from the AddShiftOff state to the AddShiftOn state, we click the question mark to obtain a text editor, and we type the name SWITCH. We repeat this step to add the same event, i.e., SWITCH to the transition from AddShiftOn state to TransferOff state. The event SWITCH will alternate every time the Stateflow chart detects a rising or falling signal edge. The completed Stateflow Editor window appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−107
Chapter 1 The Stateflow Chart
The final step to complete our model is to provide some means to “wake up” the Stateflow chart. This can be achieved by sampling the chart at a specified or inherited rate, using a signal as a trigger, or using one Stateflow chart to activate another. As we’ve learned in Step(g).4 above, the event SWITCH controls the transitions from the AddShiftOff state to the AddShiftOn state, and vice versa. For this example, we need an edge trigger* to “wake up” the chart at regular and very frequent time intervals. In the next step, we will define a second edge−triggered input event which we will name CLOCK, to “wake up” the Stateflow chart. We define the CLOCK event by double−clicking the Shift Controller Stateflow block in the model of in the previous page, in the Stateflow Editor from the Add drop menu we add an input event by selecting Event>Input from Simulink, in the Event properties dialog box we change the Name field to CLOCK, the Port field to 2, the Trigger field to Either, and the Event dialog box now appears as shown below. We click OK to accept these settings. * When using edge triggers there can be a delay from the time the trigger occurs to the time the chart begins executing. Thus, an edge trigger causes the chart to execute at the beginning of the next simulation time.
1−108
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
We connect the Mux block output to the trigger port of the Stateflow chart, we connect the output of the Manufacturing Plant subsystem to the input of the Stateflow chart, and the output of the Stateflow chart to the top input of the Manufacturing Plant subsystem. Our model is now complete and it is named Example_1_1 as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−109
Chapter 1 The Stateflow Chart Before starting the simulation, it is recommended that we make sure there is a default transition at every level of the Stateflow hierarchy that contains exclusive (OR) states, that whenever possible, the input data objects inherit properties from the associated Simulink signal, and that output data objects do not inherit types and sizes because the values are back propagated from Simulink and may be unpredictable. To set the simulation parameters, we double−click the Shift Controller block in the model of the previous page, 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 below, and we make changes if necessary. We click OK to accept these values.
When a Simulink model that contains a Stateflow Chart block is simulated, we can animate the Stateflow Chart to highlight the states and the transitions as they occur, and this feature provides visual verification that our chart behaves as expected. Animation is enabled by default but we need to specify the speed. To make sure that the animation has been enabled, in the Stateflow Editor window from the Tools drop menu we select Open Simulation Target, and this opens the Stateflow Target Builder dialog box shown below.
1−110
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
In the Stateflow Target Builder dialog box above, we click the Coder Options button, and the Stateflow sfun Coder Options dialog box appears as shown below, where we observe that Enable debugging/animation is checked.
To set the animation speed, from the Stateflow Editor window we click the Debug tool and the Stateflow Debugging window appears as shown below where the Delay (sec) field has been set to 1 sec so that the animation will proceed at the slowest speed.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−111
Chapter 1 The Stateflow Chart
To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the debugger to pause simulation during run−time activities. Breakpoints that can set are listed below. Breakpoint
Description
Chart Entry
Simulation halts when Stateflow chart “wakes up”
Event Broadcasta
Simulation halts when an event such as TRANSFERS and / or CLOCK occurs.
State Entry
Simulation halts when a state becomes active
a. To keep simulation running at a reasonable pace, we will not use Event Broadcast. Otherwise, simulation would pause at every rising or falling edge of the TRANSFERS and CLOCK signals.
In the Stateflow Debugging window above, we check Chart Entry and State Entry as breakpoints and this window now appears as shown below.
1−112
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
The option Browse Data in the Stateflow Debugging window above is a menu for observing data when simulation pauses at a breakpoint. In the window above, the Browse Data is inactive but it will become active when simulation begins and halts at a breakpoint. We recall that before simulation begins, Stateflow builds the simulation target by performing the following actions: • Parses the Stateflow chart for errors such as no default transition at every level of the Stateflow hierarchy that contains exclusive (OR) states, input data objects do not inherit properties from the associated Simulink signal, and output data objects do inherit types and sizes. • Generates C code that represents the behavior of the Stateflow chart • Builds the generated code into an executable program for the simulation target, referred to as sfun target. • Creates a directory referred to as sfprj in the directory where the chart resides to store the generated files that make up the sfun target. • Creates a MEX (MATLAB executable) file that corresponds to the C source file During each of these processes, status messages are displayed at the MATLAB Command Window.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−113
Chapter 1 The Stateflow Chart We are now ready to begin simulation but before we issue the Start command in the Stateflow Debugging window in the previous page, we open the Scope block in the model of Page 1−109. We position the Scope block, the Stateflow Editor window, and the Stateflow Debugger window so that all are partially visible about as shown below.
1−114
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−115
Chapter 1 The Stateflow Chart In the Stateflow Debugger window above, we begin simulation by clicking the Start button. We observe that the TransferOff state appears highlighted as part of the animation and it is shown in Figure 1.64. This indicates that the chart is “awaken” by the CLOCK signal and the default transition arrow has activated the TransferOff state.
We notice also that the status panel at the upper part of the Stateflow Debugger window shows the activities at the first breakpoint and that the Browse Data option is now enabled as shown below.
1−116
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
In the Stateflow Debugger window above, we click the down arrow to the right of the Browse Data option and we select All Data (Current Chart) from the drop menu. The Stateflow Debugger window now appears as shown below and allows us to view the value of the output of the Stateflow Chart, i.e., production.* 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 production and MATLAB displays production = 0 To view the value of the input of the Stateflow Chart, i.e, boards, at the command prompt debug>> we type boards and MATLAB displays boards = 186.3330 that is, at this time, the approximate number of boards produced is 186.†
* We recall from Pages 1−79, 1−88 and 1−99 that production was assigned a minimum value of 0 and a maximum value of 3. † We recall that the initial condition in the Integrator block inside the Manufacturing Plant subsystem was set to 0.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−117
Chapter 1 The Stateflow Chart
To resume simulation, in the Stateflow Debugger window above we uncheck the breakpoint Chart Entry, and we click the Continue button repeatedly until the status panel at the upper part of the Stateflow Debugger window indicates Simulink Time: 25.000000. We click the Continue button once more and we observe that number of boards produced is 6,971 as indicated in the Stateflow Debugger window below, and we also observe that in the Stateflow Editor window the AddShift On state is now active while the AddShiftOff state has returned to the inactive state as shown below.
1−118
Introduction to Stateflow®with Applications Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−119
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
Solution to the End−of−Chapter Exercise
We continue the simulation until we reach the 300 second point (end of simulation time) and we observe that the Stateflow chart goes back to “sleep”. At this time the Scope block displays the waveform shown below. This waveform indicates that until the AddShiftOn state becomes active, the number of boards produced increases unchecked. However, after 25 seconds into the simulation, the rising edge of the SWITCH signal from the Signal Builder block switches the AddShiftOn state On and until the falling edge of SWITCH signal at 50 seconds the number of boards produced remains relatively constant around 5,000 boards. Then the number of boards produced begins to rise again towards the 15000 limit indicated by the Constant block input to the Manufacturing Plant subsystem. It is the CLOCK signal that causes the monotonic increase to about 15,000 boards. Because the SWITCH pulse width was defined with only 25 seconds duration starting at 25 seconds and ending at 50 seconds, the Second and Graveyard states never switched from the Off to the On states. The reader is invited to define a wider pulse width for the SWITCH signal and repeat the simulation.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
1−121
Chapter 1 The Stateflow Chart
1−122
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 F (false), or − (true or false). Each of the Decision columns combines an outcome for each condition with a logical AND into a compound condition, that is referred to as a decision. The truth table is evaluated as one decision at a time, beginning with Decision 1. If one of the decisions is true, we perform its action and truth table execution is complete. For example, if Conditions 1 and 2 are false and Condition 3 is true, Decision 3 is true and the variable t is set equal to 3. The remaining decisions are not tested and evaluation of the truth table is finished. The last decision, denoted as DN in Table 2.1, is the Default Decision, and covers all possible remaining decisions. If Decisions 1, 2, 3, 4, D N – 1 are false, then the Default Decision is automatically true and its action (t = n) is executed. The Default Decision must be the last decision on the right with an entry of − for all conditions in the decision where − denotes any outcome for the condition. The evaluation of t = k k = 1, 2, …, n in Table 2.1 behaves as the programming sequence below where the exclamation symbol (!) denotes negation. if ((A == 1) & !(B == 1) & !(C == 1) & !(D == 1)) t=1; elseif (!(A == 1) & (B == 1) & !(C == 1) & !(D == 1)) t=2; elseif (!(A == 1) & !(B == 1) & (C == 1) & !(D == 1)) t=3; elseif (!(A == 1) & !(B == 1) & !(C == 1) & (D == 1)) t=4; ..... else t=n; endif
or the Boolean expressions X = ABCD
Y = ABCD
Z = ABCD
W = ABCD
…
We can call a Truth Table functions from a Stateflow chart or by adding a Truth Table block directly to a Simulink model as shown in Figure 2.1 below. Adding a Truth Table block directly to a Simulink model is the more direct approach and has the advantage of being able to define truth table inputs and outputs to have inherent types and sizes. Moreover, the Truth Table block supports the Embedded MATLAB language* for programming conditions and actions, and gener-
* This topic is discussed in Chapter 3.
2−2
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow ates content as Embedded MATLAB code. This helps in debugging the Truth Table block during Simulation.
Call directly to a Simulink model Call from a Stateflow chart
Figure 2.1. The Stateflow Chart and Truth Table blocks
It is best to introduce the addition of a Truth Table block directly to a Simulink model with the following example. Example 2.1 In this example we will create a Simulink model that includes a Truth Table block to convert decimal numbers to Binary Coded Decimals (BCD). The truth table that performs this conversion is shown in Table 2.2. We will refer to this table as the generic truth table for this conversion. Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−3
Chapter 2 The Stateflow Truth Table TABLE 2.2 Generic Decimal−to−BCD Converter Inputs S0
S1
S2
S3
S4
S5
S6
S7
S8
S9
A
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 1 1
Outputs B C
D
0 0 0 0 1 1 1 1 0 0
0 1 0 1 0 1 0 1 0 1
0 0 1 1 0 0 1 1 0 0
From Table 2.2, by inspection, we obtain* A = S8 + S9 B = S4 + S5 + S6 + S7
(2.1)
C = S2 + S3 + S6 + S7 D = S1 + S3 + S5 + S7 + S9
We will make use of the relations in (2.1) when we program the Truth Table block. We begin by calling Simulink from the main MATLAB Window of Figure 2.2 using the Simulink tool
.
Figure 2.2. Opening the Simulink Library Browser with the Simulink tool * For a detailed discussion on this and other binary converters, please refer to Digital Circuit Analysis and Design with Simulink Modeling and Introduction to CPLDs and FPGAs, ISBN 978−1−934404−05−8.
2−4
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow The Simulink Library Browser window opens as shown in Figure 2.3.
Figure 2.3. The Simulink Library Browser window.
We click on the Create a new model tool (upper left), we scroll down on the left pane and we choose Stateflow. From the right pane we click and drag the Truth Table block into the new model named untitled as shown in Figure 2.4. We save this model as dec2BCDtt1 and now it appears as shown in Figure 2.5. The truth table block in Figure 2.5 is empty and we must program it to specify its function. We do this with the following steps: a. We double click on the Truth Table block of Figure 2.5 and the dec2BCDtt1/Truth Table window appears as shown in Figure 2.6. We observe that this window consists of a Condition Table, and an Action Table.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−5
Chapter 2 The Stateflow Truth Table
Figure 2.4. Dragging a Truth Table block into a Simulink model
Figure 2.5. Naming the Simulink model
b. The Condition Table contains a Description column, a Condition column, and two or more Decision columns denoted as D1, D2,... DN. The Action Table consists of a Description column and an Action column. The entries in Figure 2.6 are for illustration purposes and we delete them. Descriptions are optional, but are transferred as comments into the generated code for the truth table.
2−6
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.6. The Condition Table and the Action Table in a Stateflow Truth Table block
c. To specify the logical behavior of a truth table, we begin with the Condition column of the Condition Table. We can also enter an optional description in the Description column. The generic truth table of Table 2.2 consists of 10 rows and 10 input columns. After deleting the contents of the 2 rows and the contents of the 3 decision columns D1, D2, and D3 in the dec2BCDtt1/Truth Table window of Figure 2.6, we are left with 2 empty rows and three empty decision columns. Accordingly, we must add 8 rows and 8 columns to the dec2BCDtt1/Truth Table of Figure 2.6. Column D11 is the default decision column and the need for it will be explained in (d) below. We add 8 rows and 8 columns by clicking the Append Row tool times.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
8 times, and by clicking Append Column tool
8
2−7
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
Figure 2.9. The Ports and Data Manager window
On the left pane of the Ports and Data Manager of Figure 2.9 where the entry data appears under the Column Name, we change the name to a, and we press Enter. We click the entry Local under the Scope column, and from the drop menu we select Input. This means that Simulink provides the value for this data, which it passes to the Stateflow block through an input port on the Stateflow block. Using the same procedure we change the name u to Input b, Port 2, and the name y to Input c, Port 3. The new data now appear as shown in Figure 2.10.
Figure 2.10. The contents of the Ports and Data Manager window for Example 2.1
2−10
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow We click on the Add Data tool , we observe that a new entry appears with the name data, and using the procedure above we change the name data to Input d, Port 4. We repeat this procedure to enter inputs e through j, and outputs t1, t2, t3, and t4. The Ports and Data Manager window now appears as shown in Figure 2.11.*
Figure 2.11. Defined inputs and outputs in the Ports and Data Manager window for Example 2.1
The Truth Table block now appears as shown in Figure 2.12.
* The sequence in which the inputs and outputs are displayed is immaterial. The sequence can be rearranged by clicking Port in the Contents pane.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−11
Chapter 2 The Stateflow Truth Table
Figure 2.12. The Truth Table block inputs and outputs
In the Simulink model of Figure 2.12 we add ten Constant blocks as inputs to the Stateflow Truth Table block and four Display blocks as outputs interconnected as shown in the model of Figure 2.13. We check the validity of this model by entering S0=0; S1=0; S2=0; S3=0; S4=0; S5=0; S6=0; S7=0; S8=0; S9=0;
at MATLAB’s Command prompt, and observing that all 4 Display blocks show zero values. As another check, we enter S5=1;
and as expected, the Display blocks show the values A=0, B=1, C=0, and D=1. As a last check, at MATLAB’s Command prompt we enter S5=0;* S9=1;
and the output values are as shown in Figure 2.13.
* We set the value of S5 to 0 because only one of the inputs can be set to 1 at any time.
2−12
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.13. The complete Simulink model for Example 2.1
While the model of Figure 2.13 works well, it is not the most elegant design. We can add a Multiport Switch block and redefine the Truth Table block with only one input. This is left as an exercise for the reader at the end of this chapter. The Truth Table block used in Example 2.1 is an Embedded MATLAB truth table function and has the advantage to adding a Truth Table block directly to a Simulink model instead of calling truth table functions from a Stateflow Chart block. The Truth Table block uses the Embedded MATLAB language for programming conditions and actions, and generates content as Embedded MATLAB code. However, when a Truth Table is called from a Stateflow Chart, we have two options: Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−13
Chapter 2 The Stateflow Truth Table 1. Stateflow Classic (default) − Programming Actions in Stateflow Classic Action Language 2. Embedded MATLAB − Programming Actions in Embedded MATLAB Action Language We will illustrate the Stateflow Classic Action Language with Example 2.2, and the Embedded MATLAB Action Language with Example 2.3. Example 2.2 We will repeat Example 2.1 using the Stateflow Chart block with the Stateflow Classic Action Language option. We begin by calling Simulink from the main MATLAB Window of Figure 2.2 using the Simulink tool The Simulink Library Browser window opens as shown in Figure 2.3. We click on the Create a new model tool (upper left), we scroll down on the left pane and we choose Stateflow. From the right pane we click and drag the Stateflow Chart block into the new model.* We save this model as dec2BCDcl and now it appears as shown in Figure 2.14.
Figure 2.14. Using the Stateflow Chart Truth Table in the Simulink model of Example 2.1
In the Simulink model window of Figure 2.14, from the Simulation drop menu we select Configuration Parameters, we set the Solver Options Type field to Variable−step, and Stop Time to inf, and we save the model.
*
We can also call a Stateflow Chart block by typing sfnew at the MATLAB Command Window prompt.
2−14
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow The Chart block in the model of Figure 2.14 is empty and we must program it to specify its function. We do this with the following steps: a. We double click on the Chart block of Figure 2.14 and the Stateflow diagram editor named dec2BCDcl/Chart appears as shown in Figure 2.15.
Figure 2.15. Stateflow diagram editor for the Chart block of Figure 2.14
b. In the Stateflow diagram editor of Figure 2.15, we select the Truth Table drawing tool . We drag the Truth Table drawing tool into the blank space of the Stateflow diagram editor and we observe that the cursor transforms into a rectangle. We move it to the upper right corner and we click. The shaded rectangle appears with the title truthtable and a question mark (?) below it. We click on the question mark and a flashing text cursor in the center of the rectangle appears as shown in Figure 2.16.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−15
Chapter 2 The Stateflow Truth Table
Figure 2.16. Calling a Truth Table from the Stateflow Editor window
The generic truth table shown as Table 2.2, has four outputs A, B, C, and D, and each of these outputs is a function of the inputs S0 through S9. Using the Truth Table drawing tool
we add three more truthtable rectangles as shown in Figure 2.17.
Figure 2.17. Adding three more Truth Table rectangles inside the Stateflow Editor window
2−16
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow In the first truthtable rectangle of Figure 2.17 where the flashing text cursor appears we type t1=ttableA(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
This is referred to as the signature label and defines its name as ttableA, its arguments (S0,S1,S2,S3,S4,S5,S6,S7,S8,S9), and its return value t1 which is associated with the output A. Likewise, in the second, third, and fourth truthtable rectangles of Figure 2.17 we type t2=ttableB(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9) t3=ttableC(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9) t4=ttableD(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
respectively. The Stateflow diagram editor now appears as shown in Figure 2.18.
Figure 2.18. Defining the Signature labels
c. We right−click on the first truth table function t1 in Figure 2.18 above, and from the popup menu which is shown in Figure 2.19 below, we select Properties. The Truth Table Properties dialog box for the truth table function ttableA appears as shown in Figure 2.20 below where we have checked the Function Call field. d. We repeat step (c) above for the truth table functions ttableB, ttableC, and ttableD.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−17
Chapter 2 The Stateflow Truth Table
Figure 2.19. Submenu for selecting Properties
Figure 2.20. Truth Table window for defining the Truth Table properties
e. The fields in the Truth Table Properties for ttableA, ttableB, ttableC, and ttableD, are as shown in Table 2.3 below.
2−18
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow TABLE 2.3 Field Name Breakpoints Function Inline Option
Label Description Document Link
Description Function name (read only) When Function Call is checked, it sets a breakpoint to pause execution during simulation when the truth table function is called. Controls the inlining of the truth table generated code • Auto − Whether or not to inline the truth table function is decided by Stateflow • Inline − The truth table function is inlined by Stateflow • Function − The function is not inlined The signature label is specified Textual description and comments A URL address or a MATLAB command may be entered
f. The next step is to specify a call to the truth table functions ttableA, ttableB, ttableC, and ttableD. This step is necessary because when the Stateflow diagram executes during the simulation phase, it calls the truth table function(s). We call the truth table functions ttableA, ttableB, ttableC, and ttableD, from the default transition of its own Stateflow diagram by selecting the Default Transition tool from the drawing toolbar shown in Figure 2.18. We move the cursor to the left of the truth table functions shown in Figure 2.18, and we observe that the cursor transforms to a downward−pointing arrow as shown in Figure 2.21. To adjust the arrow to a vertical direction, we move the cursor towards the solid dot of the arrow, we observe that it changes to a circle around the dot, and we move it to the right until it becomes vertical. We move the question mark (?) character slightly to the right and we enter the following text: {A=ttableA(a,b,c,d,e,f,g,h,i,j); B=ttableB(a,b,c,d,e,f,g,h,i,j); C=ttableC(a,b,c,d,e,f,g,h,i,j); D=ttableD(a,b,c,d,e,f,g,h,i,j);}
The text above forms a condition action that calls the truth table with the arguments (a,b,c,d,e,f,g,h,i,j) and the return values (A,B,C,D). Thus, when Simulink activates the Stateflow block during simulation, the default transition becomes active and calls to the truth table functions ttableA, ttableB, ttableC, and ttableD, are made. The call to the truth table must match the truth table signature, that is, the type of the return values A, B, C, and D, must be associated with the type of the signature return values t1, t2, t3, and t4, and the type of the arguments (a,b,c,d,e,f,g,h,i,j) must be associated with the type of the signature arguments S0, S1, ..., and S9. This association is also shown in the Stateflow diagram editor and appears in Figure 2.22. We save the model and in step (g) below we will define the associations. Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−19
Chapter 2 The Stateflow Truth Table
Figure 2.21. Adding the Default Transition
Figure 2.22. The addition of the Truth Table functions
2−20
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow g. We double−click the truth table function ttableA in the Stateflow diagram editor of Figure 2.22, and the table editor named dec2BCDcl/ttableA appears as shown in Figure 2.23.
Figure 2.23. The Stateflow Truth Table Editor
In the truth table editor of Figure 2.23, we select the Edit Data/Ports tool and the Model Explorer window appears as shown in Figure 2.24 where the ttableA function is highlighted under Chart in the Model Hierarchy pane. The Contents pane displays the inputs (S0, S1, ..., S9) and the output t1 for the ttableA function. Likewise when the ttableB, ttableC, and ttableD functions are highlighted under Chart in the Model Hierarchy pane, the Contents pane displays the inputs (S0, S1, ..., S9) and the outputs t2, t3, and t4 respectively. Next, we select Chart in the Model Hierarchy pane and the Model Explorer window appears as shown in Figure 2.25. From the Add menu we select Data and we observe that the tool is added to the Contents pane with the default name data in the Name column. We double click on the name and in the text field we change the name to a and we press Enter. We click the entry Local under the Scope column, and from the drop menu we select Input, and this creates an input port to the Stateflow block. We repeat these steps to add the arguments b through i as inputs, and A, B, C, and D as outputs. The Model Explorer window now appears as shown* in Figure 2.26.
* The sequence in which the inputs and outputs are displayed is immaterial. The sequence can be rearranged by clicking Port in the Contents pane.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−21
Chapter 2 The Stateflow Truth Table
Figure 2.24. The Model Explorer window
2−22
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.25. The Model Explorer window displaying the contents of the Stateflow Chart
The Stateflow chart in the Simulink model now appears as shown in Figure 2.27 where we have added ten Constant blocks for the inputs S0 through S9 corresponding to the Stateflow block inputs a through j, and four Display blocks for the outputs A, B, C, and D. We have now built the Simulink model with the Stateflow block and the next step is to program the Stateflow truth table. We do this in step (h) below. h. We double click the Stateflow Chart block in Figure 2.27 and the Stateflow diagram editor appears as shown in Figure 2.28. We double click the truth table function ttableA rectangle and the truth table editor appears as shown in Figure 2.29. We must now select a Stateflow Action Language, either the Classic Action Language (default) or the Embedded MATLAB Action Language. For this example, we choose the Classic Action Language by selecting Language from the Settings drop menu in the truth table editor shown in Figure 2.29. i. The truth table editor in Figure 2.29 consists of the Condition Table which contains a Description column, a Condition column, and two or more Decision columns denoted as D1, D2, ... DN. The Action Table consists of a Description column and an Action column. Descriptions are optional, but are transferred as comments into the generated code for the truth table.We begin specifying the logical behavior in a truth table by entering conditions in the Condition column of the Condition Table in Figure 2.29. Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−23
Chapter 2 The Stateflow Truth Table
Figure 2.26. The Model Explorer window with the input and output list
j. The generic truth table of Table 2.2 consists of 10 rows and 10 input columns, and the truth table editor in Figure 2.29 contains one row and one column shown as D1. Accordingly, we must add 9 rows and 10 columns to the truth table editor shown in Figure 2.29. We add 9 rows and 10 columns by clicking the Append Row tool
9 times, and by
clicking Append Column tool 10 times. Column D11 is the default decision column. The truth table editor now appears as shown in Figure 2.30.
2−24
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.27. The Simulink model with the input and output blocks
Figure 2.28. Using the Stateflow Chart block to program the Truth Table
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−25
Chapter 2 The Stateflow Truth Table
Figure 2.29. The Condition Table in its original form
Figure 2.30. The Condition Table with added rows and columns
2−26
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow In the truth table editor shown in Figure 2.30, we type the entries shown in Figure 2.31.
Figure 2.31. The programmed Condition Table for ttableA
k. In the Condition column of the Condition Table each condition that we enter must be zero (false) or non−zero (true), that is, each condition must be specified as a == 0 or a == 1.* For this example arbitrarily we specified S0EQ1: S0 = = 1, S1EQ1: S1 = = 1, and so on as indicated in Figure 2.31 above. The entries in the Description column are optional. Whether these three conditions are true or false, they are indicated in the Decision columns D1 through D11. Thus, Decision column D1 indicates that condition S0 = = 1 in Row 1 is true and the remaining in Rows 2 through 10 are false since only one of the inputs S0 through S9 can be true at any time, and for this reason we have entered F (False)† in Rows 2 through 10 of Column D1. Using the same reasoning, we have entered F (False) or T (True) in Columns D2 through D10. As stated earlier, Column D11 is the default deci* We can also use optional brackets, e.g., [a == 1] as in Stateflow language. † Pressing the space bar on the keyboard toggles the possible values of F, −, and T. These characters can also be entered directly. All other entries with other characters are rejected. The dash (−) character represents either a true or false decision and it is used in some applications as a don’t care decision.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−27
Chapter 2 The Stateflow Truth Table sion and includes all other decisions and these are denoted with the dash (−) symbol. Each decision column binds a group of condition outcomes with the logical AND operation into a decision. The Actions X0 through X10 are defined in the Action Table which we will discuss in paragraph l below. l. We will now program the Action Table of the truth table which appears below the Condition Table. We highlight the Action Table, we click the Append Row tool 12 times, and we make the entries shown in Figure 2.32 where the entries in Rows 1 and 13 are for the initial and final actions respectively. The X0 through X10 actions listed in the last row of the Condition Table of Figure 2.31 are specified in Rows 2 through 12 in the Action Table of Figure 2.32.
Figure 2.32. The programmed Action Table for ttableA
m. The Condition Table in Figure 2.31 and the Action Table in Figure 2.32 are for the ttableA function shown in the Stateflow Chart editor of Figure 2.28. Next, we need to
2−28
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow specify the Condition Tables and the Action Tables for the ttableB, ttableC, and ttableD functions as defined in the Stateflow Chart editor of Figure 2.28. The entries are shown in Figures 2.33, 2.34, and 2.35 below where the actions for ttableB, ttableC, and ttableD are defined as Y0 through Y10, Z0 through Z10, and W0 through W10 respectively.
Figure 2.33. The programmed Condition Table and Action Table for ttableB
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−29
Chapter 2 The Stateflow Truth Table
Figure 2.34. The programmed Condition Table and Action Table for ttableC
2−30
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.35. The programmed Condition Table and Action Table for ttableD
n. We have now specified all four truth tables ttableA, ttableB, ttableC, and ttableD. In this step, we will initiate the process of debugging them. We begin with the truth table editor of ttableA shown partially in Figure 2.36.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−31
Chapter 2 The Stateflow Truth Table
Figure 2.36. Partial list of the Condition Table for ttableA
In the truth table editor of Figure 2.36 we click on the Run Diagnostics tool . If no errors are detected, the Builder window displays a message that no errors were detected as in Figure 2.37 below.
Figure 2.37. The Stateflow Builder window indicating status for ttableA
If errors are detected, the Builder window displays error messages such as that shown below in Figure 2.38.
2−32
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.38. The Stateflow Builder window indicating status for ttableA if errors have occurred
In the Stateflow diagram editor shown in Figure 2.22, Page 2−20, we double−click on the ttableB, ttableC, and ttableD functions and in the truth table editors we run the diagnostics using the Run Diagnostics tool cate that no errors were found.
. The Builder windows for these functions indi-
p. We can verify that the Simulink model in Figure 2.27, Page 2-25, produces the correct output for different inputs. For instance, in MATLAB’s command prompt we enter: S0=0; S1=0; S2=0; S3=0; S4=0; S5=0; S6=0; S7=0; S8=0; S9=1;
and the Simulink model appears as shown in Figure 2.39. We also observe that the Initial action and Final action messages in Rows 1 and 13 in the Action Tables appear in MATLAB’s Command Window as follows: truth truth truth truth truth truth truth truth
table table table table table table table table
ttableA ttableA ttableB ttableB ttableC ttableC ttableD ttableD
entered exited entered exited entered exited entered exited
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−33
Chapter 2 The Stateflow Truth Table
Figure 2.39. The Simulink model with the Truth Table Chart in its final form
q. Truth table diagnostics are performed automatically when we issue the simulation command. If no errors are detected, the Builder window is not displayed. However, we can debug a truth table during simulation by setting a breakpoint for the truth table. The breakpoint pauses execution during simulation so that we can debug each execution step. We begin by right−clicking the ttableA function in the Stateflow diagram editor shown in Figure 2.40 below, and from the pop-up menu shown in Figure 2.41, we select Properties, the Truth Table properties window appears, and we check the Function Call field for Breakpoints as shown in Figure 2.42. We click OK and this causes a breakpoint to occur when this truth table is called in the Stateflow diagram during simulation.
2−34
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.40. Using the Stateflow Truth Table Editor for debugging
Next, in the Stateflow diagram editor toolbar in Figure 2.40, we select the Debug tool and the Stateflow Debugging window appears as shown in Figure 2.43 where under the Animation column we have chosen the Enabled option with 0 sec Delay. From the Stateflow Debugging window in Figure 2.43 we click on the Start button and we wait until the breakpoint for the call to the truth table is reached, and when this occurs, the Start button changes to Continue button. We click the Step button four times to advance simulation to the ttableA truth table, and we observe that the INIT action of this truth table is highlighted as shown in Figure 2.44.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−35
Chapter 2 The Stateflow Truth Table
Figure 2.41. Truth Table submenu for selecting Properties
Figure 2.42. Truth Table dialog box for ttableA
2−36
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.43. Stateflow Debugging window for starting simulation
Figure 2.44. Partial view of the Action Table during initial simulation steps
We click the Step button twice to execute the INIT action and we observe that the truth table execution advances to the first condition in the Condition Table as shown in Figure 2.45.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−37
Chapter 2 The Stateflow Truth Table
Figure 2.45. Partial view of the Condition Table during initial simulation steps
We again click the Step button twice to execute the first condition in the Condition Table and we observe that the truth table execution advances to the second condition in the Condition Table. We repeat this step until the truth table execution advances to the last condition in the Condition Table as shown in Figure 2.46.
Figure 2.46. Partial view of the Condition Table during initial simulation steps
We click on the Step button twice to execute the first decision under Column D1 and we observe that it is highlighted as shown in Figure 2.47. Again, we click on the Step button twice and truth table execution advances to the second row in the Action Table which defines action X0. The truth table execution continues as we click the Step button to advance to Columns D2 through D10. We finally advance to the FINAL action as shown in Figure 2.48.
2−38
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.47. The Condition Table during execution of the first Decision
With the steps above, we completed the execution of the truth table ttableA. We repeat these steps to complete the execution of ttableB, ttableC, and ttableD, and when the execution of the truth table ttableD is completed, in the Stateflow Debugging window, from the Browse Data drop menu, we select All Data (Current Chart) and we observe that an updated display appears as shown in Figure 2.49.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−39
Chapter 2 The Stateflow Truth Table
Figure 2.48. Partial view of the Action Table in Final Action
Figure 2.49. Stateflow Debugging window for simulation continuation
2−40
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow Example 2.3 We will repeat Example 2.2 using the Stateflow Chart block with the Stateflow Embedded MATLAB Action Language option. We begin by calling Simulink from the main MATLAB Window of Figure 2.50 using the Simulink tool
.
Figure 2.50. Calling Simulink from the MATLAB main window
The Simulink Library Browser window opens as shown in Figure 2.51. We click on the Create a new model tool (upper left), we scroll down on the left pane and we choose Stateflow. From the right pane we click and drag the Stateflow Chart block into the new model.* We save this model as dec2BCDem and now it appears as shown in Figure 2.51.
Figure 2.51. Dragging a Stateflow Chart into the new Simulink model
*
We can also call a Stateflow Chart block by typing sfnew at the MATLAB Command Window prompt.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−41
Chapter 2 The Stateflow Truth Table In the Simulink model window of Figure 2.51, from the Simulation drop menu we select Configuration Parameters, we set the Solver Options Type field to Variable−step, and Stop Time to inf, and we save the model. The Chart block in the model of Figure 2.51 is empty and we must program it to specify its function. We do this with the following steps: a. We double click on the Chart block of Figure 2.51 and the Stateflow diagram editor named dec2BCDem/Chart appears as shown in Figure 2.52.
Figure 2.52. Stateflow diagram editor for the Chart block of Figure 2.51
b. In the Stateflow diagram editor of Figure 2.52, we select the Truth Table drawing tool . We drag the Truth Table drawing tool into the blank space of the Stateflow diagram editor and we observe that the cursor transforms into a rectangle. We move it to the upper right corner and we click. The shaded rectangle appears with the title truthtable and a question mark (?) below it. We click on the question mark and a flashing text cursor in the center of the rectangle appears as shown in Figure 2.53.
2−42
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.53. Adding a Truth Table rectangle into the Stateflow Truth Table Editor
The generic truth table shown as Table 2.2, Page 2−4, has four outputs A, B, C, and D, and each of these outputs is a function of the inputs S0 through S9. Accordingly, using the Truth Table drawing tool Figure 2.54.
we add three more truthtable rectangles as shown in
In the first truthtable rectangle of Figure 2.54 where the flashing text cursor appears we enter t1em=ttableAem(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
This is referred to as the signature label and defines its name as ttableA, its arguments (S0,S1,S2,S3,S4,S5,S6,S7,S8,S9), and its return value t1 which is associated with the output A. Likewise, in the second, third, and fourth truthtable rectangles of Figure 2.54 we enter t2em=ttableBem(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9) t3em=ttableCem(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9) t4em=ttableDem(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
respectively. The Stateflow diagram editor now appears as shown in Figure 2.55.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−43
Chapter 2 The Stateflow Truth Table
Figure 2.54. Adding three more Truth Table rectangles into the Stateflow Truth Table Editor
Figure 2.55. Defining the Truth Table rectangles
2−44
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow c. We right−click on the first truth table function t1em in Figure 2.55 above, and from the pop-up menu shown in Figure 2.56 below, we select Properties. The Truth Table Properties dialog box for the truth table function ttableAem appears as shown in Figure 2.57 below where we have checked the Function Call field.
Figure 2.56. Pop-up menu to select Truth Table Properties
Figure 2.57. Truth Table dialog box for defining ttableAem
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−45
Chapter 2 The Stateflow Truth Table d. We repeat step (c) for the truth table functions ttableBem, ttableCem, and ttableDem. e. The description for the fields in the Truth Table Properties for ttableAem, ttableBem, ttableCem, and ttableDem, are as shown in Table 2.4 below. TABLE 2.4 Field Name Breakpoints Function Inline Option
Label Description Document Link
Description Function name (read only) When Function Call is checked, it sets a breakpoint to pause execution during simulation when the truth table function is called. Controls the inlining of the truth table generated code • Auto − Whether or not to inline the truth table function is decided by Stateflow • Inline − The truth table function is inlined by Stateflow • Function − The function is not inlined The signature lavel is specified Textual description and comments A URL address or a MATLAB command may be entered
f. The next step is to specify a call to the truth table functions ttableAem, ttableBem, ttableCem, and ttableDem. This step is necessary because when the Stateflow diagram executes during the simulation phase, it calls the truth table function(s). We call the truth table functions ttableAem, ttableBem, ttableCem, and ttableDem, from the default transition of its own Stateflow diagram by selecting the Default Transition tool from the drawing toolbar shown in Figure 2.55. We move the cursor to the left of the truth table functions shown in Figure 2.55, and we observe that the cursor transforms to a downward− pointing arrow as shown in Figure 2.58. To adjust the arrow to a vertical direction, we move the cursor towards the solid dot of the arrow, we observe that it becomes a circle around the dot, and we move it to the right until it becomes vertical. We move the question mark (?) character slightly to the right and we enter the following text: {A=ttableAem(a,b,c,d,e,f,g,h,i,j); B=ttableBem(a,b,c,d,e,f,g,h,i,j); C=ttableCem(a,b,c,d,e,f,g,h,i,j); D=ttableDem(a,b,c,d,e,f,g,h,i,j);}
The text above forms a condition action that calls the truth table with the arguments (a,b,c,d,e,f,g,h,i,j) and the return values (A,B,C,D). Thus, when Simulink activates the Stateflow block during simulation, the default transition becomes active and calls to the truth table functions ttableA, ttableB, ttableC, and ttableD, are made.
2−46
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.58. Adding the Default Transition
The call to the truth table must match the truth table signature, that is, the type of the return values A, B, C, and D, must be associated with the type of the signature return values t1em, t2em, t3em, and t4em, and the type of the arguments (a,b,c,d,e,f,g,h,i,j) must must be associated with the type of the signature arguments S0, S1, ..., and S9. This association is also shown in the Stateflow diagram editor and appears in Figure 2.59. We save the model and in step (g) below we will define the associations.
Figure 2.59. The addition of the Truth Table functions
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−47
Chapter 2 The Stateflow Truth Table g. We double−click the truth table function ttableAem in the Stateflow diagram editor of Figure 2.59, and the table editor named dec2BCDem/ttableAem appears as shown in Figure 2.60.
Figure 2.60. The Stateflow Truth Table Editor
In the truth table editor of Figure 2.60, we select the Edit Data/Ports tool and the Model Explorer window appears as shown in Figure 2.61 where the ttableAem function is highlighted under Chart in the Model Hierarchy pane. The Contents pane displays the inputs (S0, S1, ..., S9) and the output t1em for the ttableAem function. Likewise when the ttableBem, ttableCem, and ttableDem functions are highlighted under Chart in the Model Hierarchy pane, the Contents pane displays the inputs (S0, S1, ..., S9) and the outputs t2em, t3em, and t4em respectively. Next, we select Chart in the Model Hierarchy pane and the Model Explorer window appears as shown in Figure 2.62. From the Add menu we select Data and we observe that the tool is added to the Contents pane with the default name data in the Name column. We double click on the name and in the text field we change the name to a and we press Enter. We click the entry Local under the Scope column, and from the drop menu we select Input, and this creates an input port to the Stateflow block. We repeat these steps to add the arguments b through i as inputs, and A , B, C , and D as outputs. The Model Explorer window now appears as shown* in Figure 2.63. * The sequence in which the inputs and outputs are displayed is immaterial. The sequence can be rearranged by clicking Port in the Contents pane.
2−48
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.61. The Model Explorer window
The Stateflow chart in the Simulink model now appears as shown in Figure 2.64 where we have added 10 Constant blocks for the inputs S0 through S9 corresponding to the Stateflow block inputs a through j, and 4 Display blocks for the outputs A, B, C, and D. We have now built the Simulink model with the Stateflow block and the next step is to program the Stateflow truth table. We do this in step (h) below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−49
Chapter 2 The Stateflow Truth Table
Figure 2.62. The Model Explorer window displaying the contents of the Stateflow Chart
h. We double click the Stateflow Chart block in Figure 2.64 and the Stateflow diagram editor appears as shown in Figure 2.65. We double click the truth table function ttableAem rectangle and the truth table editor appears as shown in Figure 2.66. We now must select a Stateflow Action Language, either the Classic Action Language (default) or the Embedded MATLAB Action Language. For this example, we choose the Embedded MATLAB Action Language by selecting Language from the Settings drop menu in the truth table editor shown in Figure 2.66. We repeat this step for the truth table functions ttableBem, ttableCem, and ttableDem, and the Stateflow diagram editor appears as shown in Figure 2.67. i. The truth table editor in Figure 2.66 consists of the Condition Table which contains a Description column, a Condition column, and two or more Decision columns denoted as D1, D2, ... DN. The Action Table consists of a Description column and an Action column. Descriptions are optional, but are transferred as comments into the generated code for the truth table. We begin specifying the logical behavior in a truth table by entering conditions in the Condition column of the Condition Table in Figure 2.66.
2−50
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.63. The Model Explorer window with the input and output list
j. In the Condition Table of the truth table editor in Figure 2.66 we add 9 rows and 10 columns by clicking the Append Row tool
9 times, and by clicking Append Column
tool 10 times. Column D11 is the default decision column. The truth table editor now appears as shown in Figure 2.68.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−51
Chapter 2 The Stateflow Truth Table
Figure 2.64. The Simulink model with the input and output blocks
Figure 2.65. Using the Stateflow Chart block to program the Truth Table
2−52
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.66. The Condition Table in its original form
Figure 2.67. Using the Stateflow Chart block to program the Truth Table
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−53
Chapter 2 The Stateflow Truth Table
Figure 2.68. The Condition Table with added rows and columns
In the Truth Table editor shown in Figure 2.68, we type the entries shown in Figure 2.69.
2−54
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.69. The programmed Condition Table for ttableAem
k. In the Condition column of the Condition Table shown in Figure 2.69, each condition that we enter must be zero (false) or non−zero (true), that is, each condition must be specified as a == 0 or a == 1.* For this example, arbitrarily we specified S0EQ1: S0 = = 1, S1EQ1: S1 = = 1, and so on as indicated in Figure 2.69 above. The entries in the Description column are optional. Whether these three conditions are true or false, they are indicated in the Decision columns D1 through D11. Thus, Decision column D1 indicates that condition S0 = = 1 in Row 1 is true and the remaining in Rows 2 through 10 are false since only one of the inputs S0 through S9 can be true at any time, and for this reason we have entered F (False)† in Rows 2 through 10 of Column D1. Using the same reasoning, we have entered F (False) or T (True) in Columns D2 through D10. As stated earlier, Column D11 is the default decision and includes all other decisions and these are denoted
* We can also use optional brackets, e.g., [a == 1] as in Stateflow language. † Pressing the space bar on the keyboard toggles the possible values of F, −, and T. These characters can also be entered directly. All other entries with other characters are rejected. The dash (−) character represents either a true or false decision and it is used in some applications as a don’t care decision.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−55
Chapter 2 The Stateflow Truth Table with the dash (−) symbol. Each decision column binds a group of condition outcomes with the logical AND operation into a decision. The Actions X0 through X10 are defined in the Action Table which we will discuss in paragraph l below. l. We will now program the Action Table of the truth table which appears below the Condition Table. We highlight the Action Table, and we click the Append Row tool 12 times. We click the first row in the Description column of the Action Table, and we enter Initial action: Display message . We press Tab to move to the Action column in the Action Table, and we enter INIT: eml.extrinsic(‘truth table ttableAem entered’); For this example we selected the Embedded MATLAB Language. This language provides a front−end for writing and simulating Embedded MATLAB functions in Stateflow charts. Accordingly, we need to write an M−code to program our actions in the Action Table. The M−code allows us to add control flow logic and to call MATLAB functions directly. We begin with an action in the truth table function ttableAem using the embedded MATLAB syntax consisting of persistent* variables, if ... else ... end control flows, for loop, and calling the MATLAB command plot directly. We click the second row in the Description column of the Action Table, and we enter the description: Define a counter and a vector of length 10. Whenever this action is called, the output t1em assumes the next value of the vector.
We press Tab to move to the Action column in the Action Table, we enter X0:, we press enter, and we enter the following: persistent values counter; cycle = 10; if isemptly(counter) % Initialize counter to zero counter = 0; else % Otherwise, increment counter counter = counter + 1; end if isemply(values) % Values is a vector of 1 to cycle * Persistent variables are local to the function in which they are declared, but their values are retained in memory between calls to the function. We declare persistent variables in embedded MATLAB functions using the persistent statement with the word persistent in front of the variable, e.g., persistent INV_X
2−56
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow values = zeros(1, cycle); for k = 1; cycle values(k)=k; end % The following is just for debugging purposes values end % Output t1em assumes the next value in values vector t1em=values(mod(counter, cycle) + 1);
The entries in rows 3 through 12 are the same as those in the previous example except that output t1 has been changed to t1em. In Row 13 we enter Final action: Display message, and FINAL: eml.extrinsic(truth table ttableAem exited’); The Action Table for truth table ttableAem appears as shown in Figure 2.70
Figure 2.70. The programmed Action Table for ttableAem
The entries for the truth table editors for truth tables ttableBem, ttableCem, and ttableDem, are shown in Figures 2.71, 2.72, and 2.73 respectively.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−57
Chapter 2 The Stateflow Truth Table
Figure 2.71. The programmed Condition Table and Action Table for ttableBem
2−58
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.72. The programmed Condition Table and Action Table for ttableCem
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−59
Chapter 2 The Stateflow Truth Table
Figure 2.73. The programmed Condition Table and Action Table for ttableDem
Our model is now completed and with the values below entered at the MATLAB command prompt, appears as shown in Figure 2.74. S0=0; S1=0; S2=0; S3=0; S4=0; S5=0; S6=0; S7=0; S8=0; S9=1;
2−60
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Truth Tables in Stateflow
Figure 2.74. The Simulink model with the Truth Table Chart in its final form
Truth table diagnostics are performed automatically when we issue the simulation command. If no errors are detected, the Builder window is not displayed. However, we can debug a truth table during simulation by setting a breakpoint for the truth table using the same procedure as in Example 2.2. The breakpoint pauses execution during simulation so that we can debug each execution step.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−61
Chapter 2 The Stateflow Truth Table 2.2 Summary • We add a Stateflow Truth Table block directly to a Simulink model or by calling truth table functions from a Stateflow Chart. • The Truth Table block is an embedded MATLAB truth table function. The Truth Table block used in Example 2.1 is an embedded MATLAB truth table function. • Truth table functions called from a Stateflow Chart block can be programmed in Stateflow Classic Language (default) or in Embedded MATLAB Language. The truth table functions called in Example 2.2 are programmed in Stateflow Classic Language, and the truth table functions called in Example 2.3 are programmed in Embedded MATLAB Language. • A graphical function is a function defined graphically by a Stateflow diagram. We use the Stateflow editor to create them and they reside in our Stateflow model along with the diagrams that invoke them. An example is shown in Figure 2.59 where the functions ttableA, ttableB, ttableC, and ttableD are called in the condition action of the transition from one state to another. • Truth Table blocks are easier to program than truth table functions called from a Stateflow Chart block with graphical functions. • If we use the Truth Table block in a Simulink model, we can invoke the Truth Table Editor window to enter the conditions, decisions, and actions. An example is shown in Figures 2.7, and 2.8. The Truth Table Editor allows us to edit conditions, decisions, and actions, add or modify Stateflow data and ports using the Ports and Data Manager by clicking the Edit Data/ Ports tool, run diagnostics to detect errors, and view generated content after simulation. • If we choose the Chart block to call a truth table function in a new Simulink model, we perform the following steps: 1. We enter sfnew at the MATLAB command prompt 2. We double−click the Stateflow Chart block, and in the Stateflow diagram editor window we select the Truth Table tool, we drag it near the upper right corner of the window, and we observe that it appears as a rectangle with the label truthtable with a flashing text cursor below it. 3. At the flashing text cursor we enter the text defining a function, e.g., z=f(x,y), and we click outside the truth table box. The function z=f(x,y) is referred to as the signature label and defines it name as f, its arguments as (x and y), and its return value z. There must be only one return value in any function within a rectangle. 4. We repeat Steps 2 and 3 above for additional functions, e.g., c=g(a,b).
2−62
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Summary 5. We specify properties by right−clicking the truth table function rectangle in the Stateflow diagram editor window and we select Properties from the drop menu and the Truth Table Properties dialog appears. The fields are described in Table 2.4, this chapter. 6. We need to specify a call to the truth table function. This is done by selecting the Default Transition tool from the drawing toolbar of the Stateflow diagram editor window, we move it near the upper left corner, we click to place a default transition into a terminating junction, we click the question mark (?) character, and where a flashing cursor appears, we enter the desired function name, e.g., {c=f(a,b);}, and we click outside this label to terminate the editing. The return value c must match the return value z of the signature label, and the values (a,b) must match the values (x,y) of the signature label. However, the function f must be the same as in the signature label. 7. In the Stateflow diagram editor window we double−click the truth table rectangle to open the Truth Table Editor window consisting of the Condition Table and Action Table, and we select the Edit Data/Ports tool. This opens the Model Explorer window. We notice that in the Model Hierarchy pane (left pane) that the function f is highlighted and the the Contents pane to the right displays the output z and the inputs x and y. 8. In the Model Hierarchy pane, above the function f is the parent node Chart, and when it is selected, we notice that there are no data in the Contents pane. From the Add drop menu we select Data, and we observe that a scalar data is added in the Contents pane. 9. In the Contents pane we double−click the entry data under the Name column. We observe that a small text field opens with the name data highlighted, we change the name to a and we press enter. We click the entry Local under the Scope column, and from the drop menu we select Input. This means that Simulink provides the value for this data and passes it to the Stateflow through an input port on the Stateflow block. The new data input a now appears in the Contents pane. 10. From the Add drop menu we select Data, and we observe that a new scalar data is added in the Contents pane. We repeat step 9 above to add the second input b. Using the same procedure, we add data c with a scope Output. The Stateflow Chart block now appears with two inputs a and b, and output c. At this time, we add the appropriate Simulink blocks from the Simulink Library Browser, and make the necessary connections to the Stateflow Chart block. 11. The next step is to program the truth table to specify its behavior. If the Classic Action Language is selected, we follow the steps delineated in Example 2.2. If the Embedded MATLAB Action Language is selected, we follow the steps in Example 2.3. 12. The final step is to debug the truth table. This is performed with the Run Diagnostics tool and the detailed procedure is illustrated in Example 2.2.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−63
Chapter 2 The Stateflow Truth Table 2.3 Exercises 1. Reprogram the Truth Table block in Example 2.1 so that the model of Figure 2.13 will be configured as shown below.
2. The truth table of the full adder is shown below. Inputs
2−64
Outputs
X
Y
C IN
S
C OUT
0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1
0 1 1 0 1 0 0 1
0 0 0 1 0 1 1 1
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Exercises Create a Simulink model to implement the truth table of a binary full−adder calling truth table functions from a Stateflow chart.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−65
Chapter 2 The Stateflow Truth Table 2.4 Solution to End−of−Chapter Exercises 1. We begin by calling Simulink from the main MATLAB Window of Figure 2.2, Page 2−4, using the Simulink tool
.
The Simulink Library Browser window opens as shown in Figure 2.3, Page 2−5. We click the Create a new model tool (upper left), we scroll down on the left pane and we choose Stateflow. From the right pane we click and drag the Truth Table block into the new model named untitled as shown below.
We save this model as Exercise2_1tt and now it appears as shown below.
The truth table block above is empty and we must program it to specify its function. We do this with the following steps:
2−66
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises a. We double click the Truth Table block and we observe that the Exercise2_1tt/Truth Table window appears as shown below. This window consists of a Condition Table, and an Action Table.
b. The Condition Table contains a Description column, a Condition column, and two or more Decision columns denoted as D1, D2, ... DN. The Action Table consists of Description column and an Action column. The entries in the Condition Table and Action Table above are for illustration purposes and we delete them. Descriptions are optional, but are transferred as comments into the generated code for the truth table. c. To specify the logical behavior of a truth table, we begin with the Condition column of the Condition Table. We can also enter an optional description in the Description column. The generic truth table of Table 2.2 consists of 10 rows and 10 input columns. After deleting the contents of the 2 rows and the contents of the 3 decision columns D1, D2, and D3 in the Exercise2_1tt/Truth Table window above, we are left with 2 empty rows and three empty decision columns. Accordingly, we must add 8 rows and 8 columns to the Exercise2_1tt/Truth Table. Column D11 is the default decision column. We add 8 rows and 8 columns by clicking the Append Row tool Append Column tool
8 times, and by clicking
8 times.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−67
Chapter 2 The Stateflow Truth Table d. In the Condition Table of Figure 2.6 we make the entries shown in the table below.
The Condition Table appears as shown below.
2−68
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises
e. In the Action Table we make the entries shown in the table below.
and the Action Table appears as shown below. Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−69
Chapter 2 The Stateflow Truth Table
We observe that the actions X0 through X10 are those appearing in the last row of the Condition Table. f. From the Exercise2_1tt/Truth Table on the previous page, we click on Edit Data/Ports from the Add drop menu, and the Ports and Data Manager window appears as shown below.
2−70
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises
g. On the left pane in the Ports and Data Manager above where the entry u appears under the column Name, we select it, we change the name to t, and we press Enter. The data t is an input and thus we need not make any further changes in that row. This means that Simulink provides the value for this data, which it passes to the Stateflow block through an input port on the Stateflow block. h. Next, we need to define the outputs A, B, C, and D. Using the same procedure as in (g) above, we change name y to A. We click the entry Local under the Scope column, and from the drop menu we select Output. This means that Simulink provides the value for this data, which it passes to the Stateflow block through an output port on the Stateflow block. The new data now appear as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−71
Chapter 2 The Stateflow Truth Table
i. We click on the Add Data tool , we observe that a new entry appears with the name data, and using the procedure above, we change the name data to B, Output, Port 2. We repeat this procedure to enter outputs C and D. The Ports and Data Manager window now appears as shown below.
j. The Truth Table block in the Simulink model appears as shown below.
2−72
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises
k. From the Simulink Library Browser we drag into the Simulink model above eleven Constant blocks, a Manual Switch block, a Multiport Switch block, a Digital Clock block, a Scope block, and five Display blocks. We configure the blocks and we interconnect them as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−73
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
Solution to End−of−Chapter Exercises 2. To create a Simulink model that calls a Stateflow block, we will use the following procedure: a. At the MATLAB command prompt we type and execute the command sfnew, and we observe that the untitled Simulink model with a Stateflow Chart block appears as shown below.
b. We click and drag the Stateflow block to the center of the Simulink window, we click on the Simulink tool to open the Simulink Library Browser, from the Simulink Sources Library we click and drag the Constant block to the left of the Stateflow block, we click it and we copy and paste it twice to create two more Constant blocks, from the Sinks Library we click and drag the Display block, and we click it and we copy and past it to create one more Display block. Our Simulink model is now as shown in the figure below where we have labeled the Constant blocks as the inputs shown in the table above, and the Sink blocks as the outputs.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−75
Chapter 2 The Stateflow Truth Table c. In the Simulink model above, from the Simulation menu, we select Configuration Parameters and from the dialog window which appears, we set the Solver Options Type to Variable−step, and the Stop Time to inf. We click OK to accept these values, we close the Configuration Parameters dialog window, and we save this model as FullAdder. As we know from our previous studies, Simulink appends the extension .mdl to this name. We create a Stateflow Truth Table with the following steps: 1. In the Simulink model above, we double−click the Stateflow block named Chart, and a blank Stateflow diagram editor appears as shown below.
Truth Table drawing tool
2. In the Stateflow diagram editor above, we click and drag the Truth Table tool into the empty area and we place it to the right side as shown below. We observe that it changes to a rectangle with the title truthtable with a flashing text cursor below it.
2−76
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises
3. Where the cursor appears in the Stateflow diagram editor above, we enter the label text t1=ttable1(X,Y,Cin) and we click outside the truth table rectangle. The label text t1=ttable(X,Y,Cin) is referred to as the signature label where ttable1 defines its name, (X,Y,Cin) are its arguments, and t1 is its return value. If we must change the signature label at a later time, we can click the label to place an editing cursor in the text of the label, and type−in the new name. 4. We repeat steps (2) and (3) above and for the second truthtable we enter the label text t2=ttable2(X,Y,Cin), and we click outside the truthtable rectangle. The Stateflow diagram editor now appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−77
Chapter 2 The Stateflow Truth Table
d. We specify the properties of the Truth Table functions with the following steps: 1. We right−click once* the first truth table function rectangle truthtable. The pop-up menu shown below appears, and we select Properties from it.
*
If we right−click twice, the truth table editor will appear. We will discuss this editor shortly.
2−78
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises 2. The fields in the Truth Table Properties dialog window below contain the information listed in the table below it.
Field Name Breakpoints Function Inline Option
Label Description Document Link
Description Function name (read only) When Function Call is checked, it sets a breakpoint to pause execution during simulation when the truth table function is called. Controls the inlining of the truth table generated code • Auto − Whether or not to inline the truth table function is decided by Stateflow • Inline − The truth table function is inlined by Stateflow • Function − The function is not inlined The signature lavel is specified Textual description and comments A URL address or a MATLAB command may be entered
3. As mentioned earlier, the table functions t1=ttable1(X,Y,Cin) and t2=ttable2(X,Y,Cin) are referred to as the signature labels where ttable1 and ttable2 define their name, (X,Y,Cin) are their arguments, and t1 and t2 are their return values.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−79
Chapter 2 The Stateflow Truth Table Now, we must specify a call to the truth table function in the Stateflow diagram, so that when later the diagram executes during simulation, it calls* the truth table. 4. To call the ttable1 and ttable2 function from the default transition of their own Stateflow diagram, we select the Default Transition tool from the drawing toolbar and we move the cursor to a location left of the truth table function. We observe that the cursor changes to a shape with a downward arrow. We click to place a default transition into a terminating junction. We click the question mark character (?) that appears on the highlighted default transition, we move it about two spaces to the right, and where the blinking cursor for entering the label of the default transition appears, we type the text {Sum=ttable1(A,B,C); Cout=ttable2(A,B,C);}. The Stateflow diagram editor now appears as shown below.†
* We can call truth table functions from the actions of any state or transition. We can also call truth tables from other functions including other truth tables and graphical functions, i.e., functions defined graphically. The functions ttable1 and ttable2 in Figure 2.21 are graphical functions. If we export a truth table, we can call it from any Stateflow chart. † To display the arrow in a vertical position, we move the cursor near the top of the arrow. and when a small circle appears, we move it to the right until the arrow becomes vertical.
2−80
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises 5. The Default Transition label {Sum=ttable1(A,B,C);Cout=ttable2(A,B,C);}, provides a condition action that calls the truth table with arguments (A,B,C) and return values t1 and t2. Thus, when Simulink triggers the Stateflow block during simulation, the default transitions occur and calls to the truth tables ttable1 and ttable1 are initiated. We must make sure that a call to the Stateflow truth table is matched with the truth table signature. In this example, the type of the return values Sum and Cout must match the return values t1 and t2, and the type of the arguments (A,B,C) match the signature arguments (X,Y,Cin). The matching procedure is discussed next. 6. We select Model Explorer from the View drop menu of the FullAdder/Chart window above, and it appears as shown below.
We observe that in the Model Hierarchy (left) pane the functions ttable1 and ttable2 appear under Chart* which is the name of the Stateflow block in the Simulink model of Figure 2.15. We also observe that when the function ttable1 is highlighted, the Contents (center) pane displays the signature arguments (X,Y,Cin) as inputs, and the
*
It may be necessary to expand Chart to see ttable1 and ttable2.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−81
Chapter 2 The Stateflow Truth Table return value t1 as the output. Likewise, when the function ttable2 is highlighted, the Contents pane displays the signature arguments (X,Y,Cin) as inputs, and the return value t2 as the output. The pane on the right displays the function names, ttable1 and ttable2 depending on which function is highlighted on the left pane, and shows the check mark that we added in the Truth Table Properties dialog box. This pane also shows the names of the default transitions as defined in the Stateflow diagram editor. 7. We now need to add the argument and return data used in calling ttable1 and ttable2. We begin by selecting Chart in the Model Hierarchy pane and we observe that Chart contains no data in the Contents pane. From the Add drop menu we select Data and we observe that the name data appears in the Contents pane. This data matches* the signature argument X in type and size. In the Contents pane, we double−click the entry data in the Name column, we change the name to A, we press Enter, we click the entry Local under the Scope column, and from the drop menu we select Input.† We can see the new data input A in the Contents pane. We repeat this procedure to add the data B and C with the Scope Input, and the data t1 and t2 with the Scope Output. The Stateflow Model Explorer Contents pane now appears as shown below.
8. The Simulink model now appears as shown below. * †
This can be verified by right−clicking in the Contents pane and selecting Properties. We observe that the type is double is scalar which is the default when there is no entry in the Size field. The scope input means that Simulink provides this data which it passes to the Stateflow diagram through an input port on the Stateflow block.
2−82
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises
9. In the Chart block of the Simulink model above, the default transition data A, B, C, t1, and t2, match their counterparts X, Y, Cin, Sum, and Cout, in the truth table signature in size (scalar) and type (double). We complete the Stateflow Truth Table by making the connections shown below, and we save it as FullAdder. We are now ready to program the truth table.
e. The Stateflow diagram editor that we created in Step (d).4, Page 2−80, is empty and therefore we need to program it by specifying its behavior. We do this with the following steps:
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−83
Chapter 2 The Stateflow Truth Table 1. In the Stateflow diagram editor we double−click the truth table function ttable1 to open its editor which is shown below. We observe that this empty default truth table contains a Condition Table and an Action Table each with one row. The Condition Table also contains a single Decision Column, D1, and a single action row. From the Settings drop menu we select the Stateflow Classic Language.*
2. To specify the logical behavior of a truth table, we begin with the Condition column of the Condition Table. We can also enter an optional description in the Description column. The generic truth table of the full−adder contains the three inputs X, Y, and Cin, and eight rows indicating that we need eight Decision columns. Therefore, we must add two rows and seven columns to the Condition Table above. We do this by clicking the Append Row tool twice, and by clicking Append Column tool seven times. The Condition Table now appears as shown below where the entries are described in Step 3 below.
* The programming language options for Stateflow truth tables are the Stateflow Classic (the default), and the Embedded MATLAB. We have used the Embedded MATLAB option in Example 2.3.
2−84
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises
3. In the Condition column of the Condition Table each condition that we enter must be zero (false) or non−zero (true), that is, each condition must be specified as a == 0 or a == 1.* For this example arbitrarily we specified XEQ1: X = = 1, YEQ1: Y = = 1, and CinEQ1: Cin = = 1. The entries in the Description column are optional. Whether these three conditions are true or false, they are indicated in the Decision columns D1 through D8. Thus, Decision column D1 shows that all three conditions are false corresponding to Row 1 of the generic truth table for Full Adder, and for this reason we have entered F (False)† in all three rows of Column D1. However, all three conditions are satisfied in Column D8, and thus we have entered T (True) in that column. Each decision column binds a group of condition outcomes with the logical AND operation into a decision. The Actions W1 through W8 are defined in Step 4 below. 4. Next, we will program the Action Table of the truth table which appears below the Condition Table. The entries to the Action Table for the truth table function ttable1 are shown below.
* We can also use optional brackets, e.g., [a == 1] as in Stateflow language. † Pressing the space bar on the keyboard toggles the possible values of F, −, and T. These characters can also be entered directly. All other entries with other characters are rejected. The dash (−) character represents either a true or false decision and it is used in some applications as a don’t care decision.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−85
Chapter 2 The Stateflow Truth Table
The entries in the Description column of the Action Table are optional but are recommended because they are carried into the generated code for the truth table as code comments. The first row in the Action Table displays the initial action with the message indicated under the Action column of the Action Table. Likewise, the tenth row in the Action Table displays the final action with the message indicated under the Action column of the Action Table. These messages will appear in MATLAB’s Command Window during simulation. 5. Rows 2 through 9 under the Action column of the Action Table define the Actions W1 through W8, and these are consistent with the Output S (Sum) column of the generic truth table of the Full Adder. From the Simulink model we observe that the Display 1 block receives its input from t1 output of the Stateflow block. f. The data we provided in Step (e) above are for the truth table function ttable1. We must now provide the appropriate data for the truth table function ttable2 shown in the TruthTable editor below which is repeated for convenience.
2−86
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises
We do this with the following steps: 1. We double−click the truth table function ttable2 shown above to open its editor which is shown below.
From the Settings drop menu we select the Stateflow Classic Language. Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−87
Chapter 2 The Stateflow Truth Table 2. As with the table function ttable1, we must add two rows and seven columns to the Condition Table. We do this by clicking the Append Row tool twice, and the Append Column tool seven times, and we repeat the steps as with the table function ttable1, above where the Actions V1 through V8 are defined in Rows 2 through 9 under the Action column of the Action Table, and these are consistent with the Output Cout (Carry Out) column of the generic truth table of the Full Adder.
2−88
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to End−of−Chapter Exercises From the Simulink model below we observe that the Display 2 block receives its input from t2 output of the Stateflow block.
g. The final step in completing the Simulink model for the Full Adder is to debug the truth tables ttable1 and ttable2. 1. In the Truth Table Editor toolbar for ttable1 shown below, we click on the Diagnostics tool
The Stateflow Builder window below displays a message that no errors were found.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
2−89
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
Chapter 3 Embedded MATLAB Functions in Stateflow Charts The structure of an Embedded MATLAB function is the same as that of a function used with the Embedded MATLAB Function block* that is included in the Simulink User-Defined Functions Library. The advantage of adding Embedded MATLAB functions to a Stateflow Chart is the capability of coding algorithms in the textual MATLAB language instead of the Stateflow graphical language. It is best to illustrate the procedure for building a Simulink model with a Stateflow diagram that calls an Embedded MATLAB function with an example. Example 3.1 In this example we will build, program, and debug a model with a Stateflow Chart that contains an Embedded MATLAB Function. The Stateflow Chart will accept a 3 × 3 matrix and will output the value of its determinant and its inverse matrix. We will build the model in Section 3.2, we will program it in Section 3.3, and will debug it in Section 3.4.
3.2 Building the Model with a Stateflow Embedded MATLAB Function We begin with a new Simulink model that contains a Constant block, a Stateflow Chart, and two Display blocks as shown in Figure 3.2. We save this model as matrix_det_inv_stateflow.
Figure 3.2. Blocks for the model of Example 3.1
In the model of Figure 3.2 we double−click the Stateflow Chart block to open the Stateflow Editor that appears in Figure 3.3.
* For the description of this block please refer to Introduction to Simulink with Engineering Applications, ISBN 978-09744239-7-5 or the online Simulink documentation.
3−2
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Building the Model with a Stateflow Embedded MATLAB Function
Figure 3.3. The Stateflow Editor window
In the Stateflow Editor window of Figure 3.3, we drag two Embedded MATLAB functions into the empty space of the Stateflow Editor using the Embedded MATLAB Function tool from the tool palette. We observe that a flashing text cursor appears, and we define the first function as detout=detmat(value)
and the second as invout=invmat(value)
These labels conform to the Embedded MATLAB function syntax return_value=function_name(argument1, argument2,...)
where the return_value and each argument can be a scalar, vector, or matrix of values. A matrix is a two−dimensional array (rows and columns) of values, and a vector is a matrix with a row or column with one dimension. Multiple return values are not allowed. The Stateflow Editor window now appears as shown in Figure 3.4. The label eM above the flashing text cursor where we enter the function name, indicates that this is an Embedded MATLAB function. Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−3
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.4. Defined functions in the Stateflow Editor window.
In the Stateflow Editor window in Figure 3.4, we drag the Default Transition tool to form a terminating junction, we click the question (?) mark to change it to a flashing text editor, and we type {det = detmat(invalue); inv = invmat(invalue);}
and the Stateflow Editor window now appears as shown in Figure 3.5. The function names at the Default Transition tool and the eM functions must be the same. Thus, in the Stateflow Editor window in Figure 3.5, the function names detmat and invmat are the same for the Default Transition tool and the eM functions. The label on the Default Transition provides a condition action that calls the eM functions with arguments and a return value. When the Stateflow block is triggered during simulation, the Default Transition is taken and calls to the detmat and invmat functions are made.
3−4
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Building the Model with a Stateflow Embedded MATLAB Function
Figure 3.5. The Embedded MATLAB Editor window with defined condition actions
The return values of the eM functions, e.g., detout and invout are often referred to as the signature return values. The return values of the Default Transition, e.g., det and inv must match the signature return values detout and invout, and the type of arguments in the Default Transition, e.g., invalue must match the type of the signature arguments, e.g., value. This will be ensured later when we define the inputs and outputs in the Model Explorer window. In the Stateflow Editor window in Figure 3.5, we double-click the detmat function to edit its function body in the Embedded MATLAB Editor shown in Figure 3.6.
Figure 3.6. The Embedded MATLAB Editor window for the detmat function
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−5
Chapter 3 Embedded MATLAB Functions in Stateflow Charts In the Embedded MATLAB Editor in Figure 3.6, we select Tools>Model Explorer, and the Model Explorer window appears as shown in Figure 3.7.
Figure 3.7. Partial view of the Model Explorer window for detmat function
We observe that the function detmat is highlighted in the Model Hierarchy pane (left), and the Contents pane (right) displays the input argument value and output argument detout. By default, both are scalars of type double. We double-click the value row under the Size column and we set the size of value to 3,3.* The Model Explorer window appears as shown in Figure 3.8.
* This is the size of the input matrix that will be defined in the Constant block of the Simulink model, Figure 3.2.
3−6
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Building the Model with a Stateflow Embedded MATLAB Function
Figure 3.8. Defining the size of the input value for the detmat function in the Contents pane
We return to the Stateflow Editor window in Figure 3.5, and we double-click the invmat function to edit its function body in the Embedded MATLAB Editor shown in Figure 3.9.
Figure 3.9. The Embedded MATLAB Editor window for the invmat function
In the Embedded MATLAB Editor in Figure 3.9, we select Tools>Model Explorer, and the Model Explorer window appears as shown in Figure 3.10.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−7
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.10. Partial view of the Model Explorer window for invmat function
We observe that the function invmat is highlighted in the Model Hierarchy pane (left), and the Contents pane (right) displays the input argument value and output argument invmat . By default, both are scalars of type double. We double-click the value row under the Size column and we set the size of value to 3,3.* The Model Explorer window appears as shown in Figure 3.11.
* This is the size of the input matrix that will be defined in the Constant block of the Simulink model, Figure 3.2.
3−8
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Building the Model with a Stateflow Embedded MATLAB Function
Figure 3.11. Defining the size of the input value for the invmat function in the Contents pane
In the Model Hierarchy pane of the Model Explorer in Figure 3.11, we select Chart, from the Add drop menu we select add the following data:
, and under the indicated columns in the Contents pane we
Name
Scope
Size
invalue
Input from Simulink
3,3
det
Output to Simulink
Scalar (no change)
inv
Output to Simulink
Scalar (no change)
The Model Explorer now appears as shown in Figure 3.12.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−9
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.12. Defining the Stateflow Chart input and outputs
Our Simulink model is now built and appears as shown in Figure 3.13 after connecting the Constant block to the input of the Stateflow Chart and the Display blocks to the outputs of the Stateflow Chart. The matrix A in the Constant block will be defined in the MATLAB command prompt. The Stateflow chart will be programmed in the next section.
Figure 3.13. The built model for Example 3.1
3−10
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Programming the Stateflow Chart with an Embedded MATLAB Function 3.3 Programming the Stateflow Chart with an Embedded MATLAB Function We begin by opening our saved model matrix_det_inv_stateflow and in the Stateflow Editor window we double-click the detmat function and this opens the Embedded MATLAB Editor window shown in Figure 3.14.
Figure 3.14. The Embedded MATLAB Editor window for the detmat function
After the function header in the Embedded MATLAB Editor window in Figure 3.14, we enter a line space and we type the following comment lines: % This function computes the determinant of a 3x3 matrix A % that must be defined in MATLAB's Command Window. %
The Embedded MATLAB Editor window now appears as shown in Figure 3.15
Figure 3.15. The Embedded MATLAB Editor window for the detmat function with comment lines
Next, we enter the following statement: eml.extrinsic(‘plot’);
There is no need to plot anything in this example but we add this statement to point out that a number of MATLAB functions are not supported by the Embedded MATLAB subset, and plot is Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−11
Chapter 3 Embedded MATLAB Functions in Stateflow Charts one of them. Should there be necessary to use MATLAB functions that are not supported by the Embedded MATLAB subset, we must first declare them to be extrinsic as described in “Calling MATLAB Functions” in the Embedded MATLAB documentation. The complete script for the Embedded MATLAB function detmat is listed below. function detout=detmat(value) % This function computes the determinant and the inverse of a 3x3 % matrix A which must be defined in MATLAB's Command Window. % eml.extrinsic('plot') sz=size(value) detout=determinant(value,sz); plot(value,'-+'); % % We also define the subfunction 'determinant' as follows: % function det = determinant(A,value) det=A(1,1)*A(2,2)*A(3,3)+A(1,2)*A(2,3)*A(3,1)+A(1,3)*A(2,1)*A(3,2)... -A(3,1)*A(2,2)*A(1,3)-A(3,2)*A(2,3)*A(1,1)-A(3,3)*A(2,1)*A(1,2);
This script is entered into the Embedded MATLAB Editor window as shown in Figure 3.16.
Figure 3.16. The Embedded MATLAB Editor window with the complete script for the function detmat
The complete script for the Embedded MATLAB function invmat is listed below.
3−12
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Programming the Stateflow Chart with an Embedded MATLAB Function function invout=invmat(value) % This function computes the inverse of a 3x3 % matrix A which must % be defined in MATLAB's Command Window. % sz=size(value) invout=inverse(value,sz); % Now. we define the subfunction "inverse" as follows: function inv = inverse(A,value) % % For a 3x3 matrix where A=[a11 a12 a13; a21 a22 a23; a31 a32 a33], % the inverse of A is obtained as invA = (1/detA)*adjA where adjA % represents the adjoint of A. % Ref: Numerical Analysis, ISBN 0-9709511-1-6 % The cofactors are defined below. % b11=A(2,2)*A(3,3)-A(2,3)*A(3,2); b12=-(A(2,1)*A(3,3)-A(2,3)*A(3,1)); b13=A(2,1)*A(3,2)-A(2,2)*A(3,1); b21=-(A(1,2)*A(3,3)-A(1,3)*A(3,2)); b22=A(1,1)*A(3,3)-A(1,3)*A(3,1); b23=-(A(1,1)*A(3,2)-A(1,2)*A(3,1)); b31=A(1,2)*A(2,3)-A(1,3)*A(2,2); b32=-(A(1,1)*A(2,3)-A(1,3)*A(2,1)); b33=A(1,1)*A(2,2)-A(1,2)*A(2,1); % % We must remember that the cofactors of the elements of the ith % row (column) of A are the elements of the ith column (row) of AdjA. % Thus, for the next statement below, we use the single quotation % character (') to transpose the elements of the resulting matrix. % adjA=[b11 b12 b13; b21 b22 b23; b31 b32 b33]'; % inv=(1/det)*adjA
This script is entered into the Embedded MATLAB Editor window as shown in Figure 3.17.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−13
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.17. The Embedded MATLAB Editor window with the complete script for the function invmat
3−14
Introduction to Stateflow®with Applications 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 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
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.19. The Configuration Parameters dialog box
When a Simulink model that contains a Stateflow Chart block is simulated, we can animate the Stateflow Chart to highlight the states and the transitions as they occur, and this feature provides visual verification that our chart behaves as expected. Animation is enabled by default but we need to specify the speed. To make sure that the animation has been enabled, we double-click the Matrix Operations Stateflow Chart in the model in Figure 3.18, in the Stateflow Editor window in Figure 3.20 from the Tools drop menu we select Open Simulation Target, and this opens the Stateflow Target Builder dialog box* shown in Figure 3.21.
* A target is a program that executes a Stateflow chart or a Simulink model that contains a Stateflow chart, and the Stateflow Target Builder dialog box in Figure 3.21 is used to configure Stateflow for building targets. Stateflow then builds a simulation target (sfun) file that allows us to simulate our Stateflow application in Simulink.
3−16
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart
Figure 3.20. The Stateflow Editor window to select Tools>Open Simulation Target
Figure 3.21. The Target Builder window for selecting Target Options and Coder Options
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−17
Chapter 3 Embedded MATLAB Functions in Stateflow Charts In the Stateflow Target Builder dialog box in Figure 3.21, we click the Coder Options button, and the Stateflow sfun Coder Options dialog box appears as shown in Figure 3.22 where we observe that Enable debugging/animation is checked.
Figure 3.22. The Coder Options window to Enable debugging/animation
To set the animation speed, from the Stateflow Editor window in Figure 3.20 we click the Debug tool and the Stateflow Debugging window appears as shown in Figure 3.23 where the Delay (sec) has been set to 1 sec so that the animation will proceed at the slowest speed.
Figure 3.23. The Stateflow Debugging window to start simulation with breakpoints
3−18
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the debugger to pause simulation during run−time activities. Breakpoints that can set in the Stateflow Debugging window are listed below. Breakpoint
Description
Chart Entry
Simulation halts when Stateflow chart “wakes up”
Event Broadcasta
Simulation halts when an external event occurs.
State Entry
Simulation halts when a state becomes active
a. There is no such event used in this example, and thus we will not use Event Broadcast.
In the Stateflow Debugging window in Figure 3.23, we check Chart Entry and State Entry as breakpoints and this window now appears as shown in Figure 3.24.
Figure 3.24. The Stateflow Debugging window with selected breakpoints
The option Browse Data in Figure 3.24 is a menu for observing data when simulation pauses at a breakpoint. In the window of Figure 3.24 the Browse Data is inactive but it will become active when simulation begins and halts at a breakpoint. Before simulation begins, Stateflow builds the simulation target by performing the following actions:
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−19
Chapter 3 Embedded MATLAB Functions in Stateflow Charts • Parses the Stateflow chart for errors such as no default transition at every level of the Stateflow hierarchy that contains exclusive (OR) states, input data objects do not inherit properties from the associated Simulink signal, and output data objects do inherit types and sizes. • Generates C code that represents the behavior of the Stateflow chart • Builds the generated code into an executable program for the simulation target, referred to as sfun target. • Creates a directory referred to as sfprj in the directory where the chart resides to store the generated files that make up the sfun target. • Creates a MEX (MATLAB executable) file that corresponds to the C source file During each of these processes, status messages are displayed at the MATLAB Command Window. We are now ready to begin simulation but before we issue the Start command in the Stateflow Debugging window, we position the Simulink model, the Stateflow Editor window, and the Stateflow Debugger window so that all are visible as shown in Figure 3.25.
3−20
Introduction to Stateflow®with Applications 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 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
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.26. Block error message indicating “Undefined function or variable A”
Figure 3.27. The Stateflow Debugging window after the simulation command has been issued
In the Stateflow Debugging window in Figure 3.27 we click the down arrow to the right of the Browse Data option and we select All Data (Current Chart) from the submenu. The Browse Data option now appears in green color and displays the status of the model at the start of the simulation as shown in Figure 3.29.
3−22
Introduction to Stateflow®with Applications 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 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 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.29. The Stateflow Debugging window at the start of simulation
As we continue with the simulation, we observe that the plot appears as shown in Figure 3.30,* and the Default Transition tool in the Stateflow Editor window appears highlighted on and off during the simulation as shown in Figure 3.31. To advance through the rest of the simulation in the Stateflow Debugging window in Figure 3.29, we check the Disable all field to remove all breakpoints, and we click the Continue button and we observe the status at simulation time from zero to 10 seconds. In the Simulink model shown in Figure 3.32, the Progress bar at the bottom of the window indicates 7.2 seconds have elapsed after the start of the simulation. * For clarity, this plot has been edited using the MATLAB Edit Figure properties.
3−24
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart
Figure 3.30. The plot generated by the plot(value,’-+’) statement
Figure 3.31. The Default Transition highlighted on and off during simulation execution
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−25
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.32. The Simulink model for Example 3.1 at simulation time T=7.2 seconds
The Simulink model at the end of simulation time is shown in Figure 3.33.
Figure 3.33. The Simulink model for Example 3.1 at the end of simulation time
We can use simulation to test our Embedded MATLAB functions for run-time errors that are not detectable by Stateflow diagnostics. When we simulate our model, Simulink tests the Embedded MATLAB functions for missing or undefined information and possible logical conflicts. The procedure is illustrated by simulating and debugging the detmat function during run-time conditions as follows:
3−26
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart In the model of Figure 3.33 above we double click the Matrix Operations Stateflow Chart and this opens the Stateflow Editor window shown in Figure 3.34.
Figure 3.34. The Stateflow Editor window
We double-click the detmat function and the Embedded MATLAB Editor window appears as shown in Figure 3.35. We click the dash (-) character in the left margin of line 6 and we observe that a small red ball appears next to line 6 as shown in Figure 3.36 indicating that we’ve set a breakpoint there. In the Embedded MATLAB Editor window in Figure 3.36, we click the Start Simulation tool (green arrow) to begin simulation. If we get any errors, we make corrections before simulation again. If no errors are detected, the simulation pauses when execution reaches the breakpoint that we’ve set, and this is indicated by a small green arrow ure 3.37.
in the left margin as shown in Fig-
We click the Step tool to advance the execution one line, i.e., to line 7, indicated by the small green arrow shown in Figure 3.38. But if we click again the Step tool, execution will advance to line 8, and we will not see the execution of the subfunction determinant. For this reason, we need to click the Step In tool which is immediately to the right of the Step tool on the main task bar in the Embedded MATLAB Editor window. Therefore, to advance execution to the first line of the subfunction determinant, we click the Step In tool, and the Embedded MATLAB Editor window now appears as shown in Figure 3.39.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−27
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.35. The Embedded MATLAB Editor window where we click the dash (-) character in line 6
Figure 3.36. The Embedded MATLAB Editor window with the small red ball in line 6 indicating a breakpoint
3−28
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart
Figure 3.37. Green arrow in line 6 indicating that execution has reached the breakpoint that we’ve set
Figure 3.38. Using the Step tool to advance execution one line
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−29
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.39. Using the Step In tool to track execution of the determinant subfunction
Once we are in the subfunction line, we can advance through the subfunction statements one line at a time. with the Step tool. But if the subfunction calls another subfunction, we should use the Step In tool to step into it. If we want to continue through the remaining lines of the subfunction and go back to the line after the subfunction call, we should use the Step Out tool
.
When the subfunction finishes execution, we will see a green arrow pointing down under its last line as shown in Figure 3.40.
3−30
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart
Figure 3.40. The Editor window with a green arrow pointing down to indicate end of execution
We click the Step tool to return to the detmat function and we observe that execution advances to line 8 as shown in Figure 3.41, and the plot is displayed as shown in Figure 3.42. If we want to see the value of the variable sz in line 6, we place the text cursor over the text sz for about two seconds, and the value appears as shown in Figure 3.43. Using the same procedure, we can see the value of any data. The values can also be seen in the MATLAB Command window. When a breakpoint is reached, the debug >> command appears.* At this prompt, we enter the name of the data, for example, debug>> sz sz = 3 3 debug>>
*
We may need to press the Enter key to see it.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−31
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.41. Clicking the Step tool one more time causes execution to advance to line 8
Figure 3.42. Generated plot when execution advances to line 8
3−32
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart
Figure 3.43. Display of the size of matrix A when the text cursor is placed over the text sz
If we want to leave the function until it is called again, we click the Continue Debugging tool and the breakpoint on line 6 is reached again. Then, we can advance through the execution of the remaining statements with the Continue Debugging tool. To remove the breakpoint at line 6, we click it and then we click the green arrow to complete execution of the simulation. The model then will be completed as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−33
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Figure 3.44. Model with computed values of determinant and inverse of the matrix at completion of simulation
3−34
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Summary 3.5 Summary • Embedded MATLAB functions insert the powerful features of MATLAB into Stateflow Charts. • The Embedded MATLAB Run−Time Function Library List includes common functions as sum, sqrt, sin, cos, and others. Those not included in this list must be declared to be extrinsic so that they can be resolved as MATLAB functions. The command plot, and the functions det and inv are examples of commands and functions not included in this list and thus they must be declared to be extrinsic or defined as subfunctions. • The structure of an Embedded MATLAB function is the same as that of a function used with the Embedded MATLAB Function block that is included in the Simulink User-Defined Functions Library. • The advantage of adding Embedded MATLAB functions to a Stateflow Chart is the capability of coding algorithms in the textual MATLAB language instead of the Stateflow graphical language. • To place Embedded MATLAB functions into Stateflow Editor we drag the Embedded MATLAB Function tool from the tool palette into the Stateflow Editor window. The label eM above the flashing text cursor where we enter the function name, indicates that this is an Embedded MATLAB function. • The syntax for Embedded MATLAB functions is return_value=function_name(argument1, argument2,...) where the return_value and each argument can be a scalar, vector, or matrix of values. A matrix is a two−dimensional array (rows and columns) of values, and a vector is a matrix with a row or column with one dimension. Multiple return values are not allowed. • The function names at the Default Transition tool same. Thus, in the Stateflow Editor window below
and the eM functions must be the
the function names detmat and invmat are the same for the Default Transition tool and the eM functions. Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−35
Chapter 3 Embedded MATLAB Functions in Stateflow Charts The label on the Default Transition provides a condition action that calls the eM functions with arguments and a return value. When the Stateflow block is triggered during simulation, the Default Transition is taken and calls to the detmat and invmat are made. • The return values of the eM functions, e.g., detout and invout are often referred to as the signature return values. The return values of the Default Transition, e.g., det and inv must match the signature return values detout and invout, and the type of arguments in the Default Transition, e.g., invalue must match the type of the signature arguments, e.g., value. This is ensured by the entries we make into the Model Explorer window to define the inputs and outputs of the Stateflow chart. • To access the Model Explorer window to define the inputs and outputs of the Stateflow chart, we click each of the eM functions in the Stateflow Editor window, and in the Embedded MATLAB Editor window that appears we select Tools>Model Explorer, and in the Model Explorer window the Model Hierarchy pane (left), and the Contents pane (right) display the input and output arguments of the eM function with the appropriate size under the Size column. • To ensure that the type of arguments in the Default Transition match the type of the signature arguments, in the Model Hierarchy pane of the Model Explorer in Figure 3.11, we select Chart, from the Add drop menu we select Contents pane we add the appropriate data.
, and under the indicated columns in the
• To program a Stateflow Chart with an Embedded MATLAB function, in the Stateflow Editor window we double-click the eM function and this opens the Embedded MATLAB Editor window. After the function header in the Embedded MATLAB Editor window, we enter a line space and appropriate comment lines. • To use MATLAB functions that are not supported by the Embedded MATLAB subset, we must first declare them to be extrinsic as described in “Calling MATLAB Functions” in the Embedded MATLAB documentation. • To set the simulation parameters, we double−click the Stateflow chart, 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 chosen earlier, and we make changes if necessary. We click OK to accept these values. • We can animate the Stateflow Chart to highlight the states and the transitions as they occur, and this feature provides visual verification that our chart behaves as expected. Animation is enabled by default but we need to specify the speed. To make sure that the animation has been enabled, we double-click the Stateflow Chart, in the Stateflow Editor window from the Tools drop menu we select Open Simulation Target, and this opens the Stateflow Target Builder dialog box. In the Stateflow Target Builder dialog box, we click the Coder Options
3−36
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Summary button, and the Stateflow sfun Coder Options dialog box appears and by default we observe that Enable debugging/animation is checked. • To set the animation speed, from the Stateflow Editor window we click the Debug tool and the Stateflow Debugging window appears. It is best to set the Delay (sec) to 1 sec so that initially the animation will proceed at the slowest speed. • To observe the behavior of our Stateflow chart in slow motion, we need to set breakpoints in the debugger to pause simulation during run−time activities. Breakpoints that can set are listed below. Breakpoint
Description
Chart Entry
Simulation halts when Stateflow chart “wakes up”
Event Broadcasta
Simulation halts when an external event occurs.
State Entry
Simulation halts when a state becomes active
a. Breakpoint at this event is normally omitted
• To start simulation with breakpoints, it is best to begin by checking the Chart Entry and State Entry as breakpoints in the Stateflow Debugging dialog box. The option Browse Data is a menu for observing data when simulation pauses at a breakpoint. This option is initially inactive but it becomes active when simulation begins and halts at a breakpoint. • Before simulation begins, Stateflow builds the simulation target by performing the following actions: 1. Parses the Stateflow chart for errors such as no default transition at every level of the Stateflow hierarchy that contains exclusive (OR) states, input data objects do not inherit properties from the associated Simulink signal, and output data objects do inherit types and sizes. 2. Generates C code that represents the behavior of the Stateflow chart 3. Builds the generated code into an executable program for the simulation target, referred to as sfun target. 4. Creates a directory referred to as sfprj in the directory where the chart resides to store the generated files that make up the sfun target. 5. Creates a MEX (MATLAB executable) file that corresponds to the C source file During each of these processes, status messages are displayed at the MATLAB Command Window.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−37
Chapter 3 Embedded MATLAB Functions in Stateflow Charts • Before issuing the Start command in the Stateflow Debugging window, it is a good idea to position the Simulink model window, the Stateflow Editor window, and the Stateflow Debugger window so that all are visible and we can observe the changes as the simulation advances. as shown in Figure 3.25. If an error is detected, Stateflow displays a Block Error message with the name and location of the offending block, and we are allowed to make the necessary corrections. After the corrections are made, in the Stateflow Debugger window in we click again the Start button and we observe that it is changed to a Continue button. We also observe that the Browse Data field is now active, and in the model window the Display blocks have been filled with zeros, and the Start command button has been replaced with the Stop button and the Pause button . We click the down arrow to the right of the Browse Data option and we select All Data (Current Chart) from the submenu. The Browse Data option now appears in green color and displays the status of the model at the start of the simulation. We can also view this value in the MATLAB Command window by pressing the Enter key at the command prompt and entering the value where MATLAB displays debug>>. • To advance through the rest of the simulation in the Stateflow Debugging window we check the Disable all field to remove all breakpoints, we click the Continue button, and we observe the status at simulation time from zero to 10 seconds or any other simulation time that we have chosen. The Progress bar at the bottom of the model window indicates the time that has elapsed after the start of the simulation. • We can use simulation to test our Embedded MATLAB functions for run-time errors that are not detectable by Stateflow diagnostics. When we simulate our model, Simulink tests the Embedded MATLAB functions for missing or undefined information and possible logical conflicts. The procedure for simulating and debugging an eM function during run-time conditions is as follows: 1
In the Stateflow Editor window, we double-click the eM function and the Embedded MATLAB Editor window that appears, we click the dash (-) character in the left margin of a line of interest and we observe that a small red ball appears next to that line 6 indicating that we’ve set a breakpoint there.
2. In the Embedded MATLAB Editor window we click the Start Simulation tool (green arrow) to begin simulation. If we get any errors, we make corrections before simulation again. If no errors are detected, the simulation pauses when execution reaches the breakpoint that we’ve set, and this is indicated by a small green arrow
in the left margin.
3. We click the Step tool to advance the execution one line indicated by the small green arrow. If we click again the Step tool, execution will advance to another line and we will not see the execution of the subfunction that we’ve selected. To advance execution to
3−38
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Summary the first line of the subfunction that we’ve selected, we click the Step In Step In tool tool. 4. Once we are in the subfunction line, we can advance through the subfunction statements one line at a time. with the Step tool. But if the subfunction calls another subfunction, we should use the Step In tool to step into it. 5. If we want to continue through the remaining lines of the subfunction and go back to the line after the subfunction call, we should use the Step Out tool
.
6. When the subfunction finishes execution, we will see a green arrow pointing down under its last line. 7. If we want to see the value of a variable, we place the text cursor over the text of that variable for about two seconds, and the value appears above the text of that variable. Using the same procedure, we can see the value of any data. 8. The values can also be seen in the MATLAB Command window. When a breakpoint is reached, the debug >> command appears.* At this prompt, we enter the name of the data. 9. If we want to leave the function until it is called again, we click the Continue Debugging tool and the breakpoint on selected line is reached again. Then, we can advance through the execution of the remaining statements with the Continue Debugging tool. 10. To remove the breakpoint at the selected line, we click it and then we click the green arrow to complete execution of the simulation.
*
We may need to press the Enter key to see it.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−39
Chapter 3 Embedded MATLAB Functions in Stateflow Charts 3.6 Exercises for the Reader 1. From antenna theory, for a half-wave dipole in the direction of maximum radiation, the power density P in watts per square meter and the electric field strength E in volts per meter, in the direction of maximum radiation are given by P = 1.64P t ⁄ 4πR
2
E = ( 49.2P t ) ⁄ R
respectively where P t is the transmitted power in watts and R is the distance in meters. Using Embedded MATLAB Functions, create a Simulink model that includes a Stateflow Chart block to display the values of the power density P and the electric field strength E for given values of P t and R . Use the plot command by declaring it as extrinsic to display the coordinates of the input values of P t and R . 2. The dimensionless unit named the Erlang is used in telephony as a statistical measure of the volume of telecommunications traffic. It is named after the Danish telephone engineer A. K. Erlang, the originator of traffic engineering and queueing theory. Traffic of one Erlang refers to a single resource being in continuous use, or two channels being at fifty percent use, and so on. For example, if an office had two telephone operators who are both busy all the time, that would represent two Erlangs of traffic. Alternatively, an Erlang may be regarded as a "use multiplier" per unit time, so 100% use is 1 Erlang, 200% use is 2 Erlangs, and so on. For example, if total cell phone use in a given area per hour is 180 minutes, this represents 180/60 = 3 Erlangs. In general, if the mean arrival rate of new calls is λ per unit time and the mean call holding time is h , then the traffic in Erlangs A is: A = λ×h
This may be used to determine if a system is over-provisioned or under-provisioned (has too many or too few resources allocated). For example, the traffic measured over many busy hours might be used for a T1 or E1 circuit group to determine how many voice lines are likely to be used during the busiest hours. If no more than 12 out of 24 channels are likely to be used at any given time, the other 12 might be made available as data channels. Traffic, measured in Erlangs, is used to calculate grade of service (GoS) or quality of service (QoS). There are a range of different Erlang formulae to calculate these, including Poisson, Erlang B, and Erlang C. Blocking refers to the inability to interconnect two idle lines connected to a network because all possible paths between them are already in use.
3−40
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Exercises for the Reader The three most commonly models for determining the probability of blocked calls are the Poisson, Erlang B, and Erlang C models. All three assume an infinite number of sources, random traffic arrival pattern, and hold times exponentially distributed. The Poisson model assumes blocked calls held, the Erlang B model assumes blocked calls cleared, and the Erlang C model assumes blocked calls delayed. The Poisson model gives the probability P of blocking as c–1
P = 1–e
–a
∑a
n
⁄ n!
n=0
The Erlang B model gives the probability P of blocking as ⎛ c ⎞ n a ⁄ n!⎟ P = ( a ⁄ c! ) ⁄ ⎜ ⎜ ⎟ ⎝ n=0 ⎠ c
∑
The Erlang C model gives the probability of blocking as ⎛ c–1 ⎞ c n P = a c ⁄ c( c – a) ⁄ ⎜ a ⁄ n! + a c ⁄ c ( c – a )⎟ ⎜ ⎟ ⎝ n=0 ⎠ c
∑
where: a = traffic load in Erlangs c = number of circuits commonly referred to as trunks P= probability of blocking Create a Simulink model that includes a Stateflow Chart block to display the probability values for each of these three models. Should you encounter any problems, replace the Stateflow Chart with the Simulink Embedded MATLAB Function block found in the Simulink UserDefined Function Library.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−41
Chapter 3 Embedded MATLAB Functions in Stateflow Charts 3.7 Solution to the End-of-Chapter Exercises 1. In the MATLAB Command window we type sfnew
and the untitled model shown below is displayed.
From the Simulink Library Browser, we highlight the Commonly Used Blocks library and from it we drag two Constant blocks. Then we highlight the Sinks library and from it we drag two Display blocks. We rearrange, we rename the Constant blocks as Constant 1 and Constant 2 , and the Display blocks as Display 1 and Display 2 . We save this model as Dipole_Stateflow. The model now appears as shown below.
We double-click the Stateflow Chart and the Stateflow Editor window appears as shown below.
3−42
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
In the Stateflow Editor window above, we drag two Embedded MATLAB functions into the empty space of the Stateflow Editor using the Embedded MATLAB Function tool from the tool palette. We observe that a flashing text cursor appears, and we define the first function as PowerDensity=dipoleP(value1,value2)
and the second as ElectricField=dipoleE(value1,value2)
These labels conform to the Embedded MATLAB function syntax return_value=function_name(argument1, argument2,...)
where the return_value and each argument can be a scalar, vector, or matrix of values. A matrix is a two−dimensional array (rows and columns) of values, and a vector is a matrix with a row or column with one dimension. Multiple return values are not allowed.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−43
Chapter 3 Embedded MATLAB Functions in Stateflow Charts The Stateflow Editor window now appears as shown below. The label eM above the flashing text cursor where we enter the function name, indicates that this is an Embedded MATLAB function.
In the Stateflow Editor window above, we drag the Default Transition tool to form a terminating junction, we click the question (?) mark to change it to a flashing text editor, and we type {Power = dipoleP(invalue1,invalue2); Field = dipoleE(invalue1,invalue2);}
and the Stateflow Editor window now appears as shown below.
3−44
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises The function names at the Default Transition tool and the eM functions must be the same. Thus, in the Stateflow Editor window below, the function names dipoleP and dipoleE are the same for the Default Transition tool and the eM functions. The label on the Default Transition provides a condition action that calls the eM functions with arguments and a return value. When the Stateflow block is triggered during simulation, the Default Transition is taken and calls to the dipoleP and dipoleE functions are made.The return values of the eM functions, i.e., PowerDensity and ElectricField are often referred to as the signature return values. The return values of the Default Transition, i.e., Power and Field must match the signature return values PowerDensity and ElectricField, and the type of arguments in the Default Transition, e.g., invalue1 must match the type of the signature arguments, i.e., value1. This will be ensured later when we define the inputs and outputs in the Model Explorer window. In the Stateflow Editor window above, we double-click the eM dipoleP function to edit its function body in the Embedded MATLAB Editor shown below.
In the Embedded MATLAB Editor above, we select Tools>Model Explorer, and the Model Explorer window appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−45
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
We observe that the function dipoleP is highlighted in the Model Hierarchy pane (left), and the Contents pane (right) displays the input arguments value1 and value2, and output argument PowerDensity. By default, both are scalars of type double. We return to the Stateflow Editor window and we double-click the eM dipoleE function to edit its function body in the Embedded MATLAB Editor shown in below.
3−46
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
In the Embedded MATLAB Editor above we select Tools>Model Explorer, and the Model Explorer window appears as shown below.
We observe that the function dipoleE is highlighted in the Model Hierarchy pane (left), and the Contents pane (right) displays the input arguments value1 and value2, and output argument ElectricField. By default, both are scalars of type double. Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−47
Chapter 3 Embedded MATLAB Functions in Stateflow Charts In the Model Hierarchy pane of the Model Explorer above, we select Chart, from the Add drop menu we select the following data: Name
, and under the indicated columns in the Contents pane we add Scope
Size
invalue1
Input from Simulink
Scalar (no change)
invalue2
Input from Simulink
Scalar (no change)
Power
Output to Simulink
Scalar (no change)
Field
Output to Simulink
Scalar (no change)
The Contents pane in the Model Explorer now appears as shown below.
Our Simulink model is now built and appears as shown below after connecting the Constant blocks to the inputs of the Stateflow Chart and the Display blocks to the outputs of the State-
3−48
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises flow Chart. We have renamed the Constant blocks P t for Power transmitted, and R for distance. The values of P t and R will be defined in the MATLAB command prompt. We save the model and we will program the Stateflow chart in the next paragraphs.
We begin the programming by opening our saved model Dipole_Stateflow and in the Stateflow Editor window we double-click the dipoleP function and this opens the Embedded MATLAB Editor window shown below.
After the function header in the Embedded MATLAB Editor window above, we enter a line space and we type the following comment lines: % This function computes the Power Density of a half-wave % dipole in terms of the transmitted power Pt and distance R % whose values will be entered in MATLAB's Command Window. %
The Embedded MATLAB Editor window now appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−49
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
Next, we enter the following statement: eml.extrinsic(‘plot’);
This statement will enable us to see the input values of P t and R in a plot to be defined below. As we now know, there are a number of MATLAB functions are not supported by the Embedded MATLAB subset, and plot is one of them. Should there be necessary to use MATLAB functions that are not supported by the Embedded MATLAB subset, we must first declare them to be extrinsic as described in “Calling MATLAB Functions” in the Embedded MATLAB documentation. The complete script for the Embedded MATLAB function PowerDensity is listed below. function PowerDensity=dipoleP(value1,value2) % This function computes the Power Density of a half-wave % dipole in terms of the transmitted power Pt and distance R % whose values will be entered in MATLAB's Command Window. % eml.extrinsic('plot') PowerDensity=PD(value1,value2) function Power=PD(Pt,R) Power=1.64*Pt/(4*pi*R^2); plot(Pt,R,’-+’); %
This script is entered into the Embedded MATLAB Editor window as shown below.
3−50
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
The complete script for the Embedded MATLAB function ElectricField is listed below. function ElectricField=dipoleE(value1,value2) % This function computes the Electric Field of a half-wave % dipole in terms of the transmitted power Pt and distance R % whose values will be entered in MATLAB's Command Window. % ElectricField=EF(value1,value2); function Field=EF(Pt,R) Field=sqrt(49.2.*Pt)./R; %
This script is entered into the Embedded MATLAB Editor window as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−51
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
We name the Stateflow Chart as shown below and save the model. We will simulate it in the next paragraph.
To set the simulation parameters, we double−click the Stateflow chart in the Simulink model above, 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 below, and we make changes if necessary. We click OK to accept these values.
3−52
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
When a Simulink model that contains a Stateflow Chart block is simulated, we can animate the Stateflow Chart to highlight the states and the transitions as they occur, and this feature provides visual verification that our chart behaves as expected. Animation is enabled by default but we need to specify the speed. To make sure that the animation has been enabled, we double-click the Computations Stateflow Chart in the model Dipole_Stateflow in the previous page, and the Stateflow Editor window appears as shown below. From the Tools drop menu we select Open Simulation Target, and this opens the Stateflow Target Builder dialog box shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−53
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
In the Stateflow Target Builder dialog box above, we click the Coder Options button, and the Stateflow sfun Coder Options dialog box appears as shown below where we observe that Enable debugging/animation is checked.
3−54
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
We can set the animation speed from the Stateflow Editor window below.
In the Stateflow Editor window above we click the Debug tool and the Stateflow Debugging window appears below where the Delay (sec) has been set to 1 sec so that the animation will proceed at the slowest speed.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−55
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the debugger to pause simulation during run−time activities. Breakpoints that can set in the Stateflow Debugging window are listed below. Breakpoint
Description
Chart Entry
Simulation halts when Stateflow chart “wakes up”
Event Broadcasta
Simulation halts when an external event occurs.
State Entry
Simulation halts when a state becomes active
a. There is no such event used in this example, and thus we will not use Event Broadcast.
In the Stateflow Debugging window above, we check Chart Entry and State Entry as breakpoints and this window now appears as shown below.
3−56
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
The option Browse Data in the lower part of the Stateflow Debugging window above is a menu for observing data when simulation pauses at a breakpoint. In the window above the Browse Data is inactive but it will become active when simulation begins and halts at a breakpoint. Before simulation begins, Stateflow builds the simulation target by performing the following actions: • Parses the Stateflow chart for errors such as no default transition at every level of the Stateflow hierarchy that contains exclusive (OR) states, input data objects do not inherit properties from the associated Simulink signal, and output data objects do inherit types and sizes. • Generates C code that represents the behavior of the Stateflow chart • Builds the generated code into an executable program for the simulation target, referred to as sfun target. • Creates a directory referred to as sfprj in the directory where the chart resides to store the generated files that make up the sfun target. • Creates a MEX (MATLAB executable) file that corresponds to the C source file During each of these processes, status messages are displayed at the MATLAB Command Window.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−57
Chapter 3 Embedded MATLAB Functions in Stateflow Charts We are now ready to begin simulation but before we issue the Start command in the Stateflow Debugging window, we position the Simulink model, the Stateflow Editor window, and the Stateflow Debugger window so that all are visible as shown below.
In the Stateflow Debugger window above, we begin simulation by clicking the Start button. As shown below, the Stateflow displays two Block error messages indicating that the values of P t and R are not defined. This is because we failed to define these values in the MATLAB Command window before starting the simulation. Therefore, we open the MATLAB Command Window and we enter the values of P t and R as Pt=2; R=1000;
3−58
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
In the Stateflow Debugger window we click again the Start button and we observe that it is changed to a Continue button. We also observe that the Browse Data field is now active as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−59
Chapter 3 Embedded MATLAB Functions in Stateflow Charts We also observe that in the model window the Display blocks have been filled with zeros, and the Start command button has been replaced with the Stop button and the Pause button , as shown below.
In the Stateflow Debugging window we click the down arrow to the right of the Browse Data option and we select All Data (Current Chart) from the submenu. The Browse Data option now appears in green color and displays the status of the model at the start of the simulation as shown below. We can also view this value in the MATLAB Command window by pressing the Enter key at the command prompt and MATLAB displays debug>>
The values of the outputs Power and Field at this time can be displayed by entering debug>> Power
Power = 0 debug>> Field
Field = 0 debug>>
3−60
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
As we continue with the simulation, we observe that the plot appears as shown below where the cross (+) symbol indicates the coordinates of the specified input values, that is, P t = 2 (horizontal axis), and R = 1000 (vertical axis). and the Default Transition tool in the Stateflow Editor window appears highlighted on and off during the simulation as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−61
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
3−62
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises To advance through the rest of the simulation in the Stateflow Debugging window we check the Disable all field to remove all breakpoints, and we click the Continue button and we observe the status at simulation time from zero to 10 seconds. In the Simulink model shown below, the Progress bar at the bottom of the window indicates 2.6 seconds have elapsed after the start of the simulation.
The Simulink model at the end of simulation time is shown below.
We can use simulation to test our Embedded MATLAB functions for run-time errors that are not detectable by Stateflow diagnostics. When we simulate our model, Simulink tests the Embedded MATLAB functions for missing or undefined information and possible logical con-
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−63
Chapter 3 Embedded MATLAB Functions in Stateflow Charts flicts. The procedure is illustrated by simulating and debugging the dipoleP function during run-time conditions as follows: In the Dipole_Stateflow model above we double click the Stateflow Chart and the Stateflow Editor window appears as shown below.
Figure 3.45.
We double-click the dipoleP function and the Embedded MATLAB Editor window appears as shown below. We click the dash (-) character in the left margin of line 6 and we observe that a small red ball appears next to line 7 as shown indicating that we’ve set a breakpoint there. In the Embedded MATLAB Editor window, we click the Start Simulation tool (green arrow) to begin simulation. If we get any errors, we make corrections before simulation again. If no errors are detected, the simulation pauses when execution reaches the breakpoint that we’ve set, and this is indicated by a small green arrow
3−64
in the left margin as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−65
Chapter 3 Embedded MATLAB Functions in Stateflow Charts We click the Step tool to advance the execution one line, i.e., to line 8, indicated by the small green arrow shown below.
If we click again the Step tool, execution will advance to line 10, and we will not see the execution of the subfunction Power. For this reason, we need to click the Step In tool which is immediately to the right of the Step tool on the main task bar in the Embedded MATLAB Editor window. Therefore, to advance execution to the first line of the subfunction Power, we click the Step In tool, and the Embedded MATLAB Editor window now appears as shown below.
3−66
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
Once we are in the subfunction line, we can advance through the subfunction statements one line at a time. with the Step tool. But if the subfunction calls another subfunction, we should use the Step In tool to step into it. If we want to continue through the remaining lines of the subfunction and go back to the line after the subfunction call, we should use the Step Out tool
.
When the subfunction finishes execution, we will see a green arrow pointing down under its last line as shown below. We click the Step tool to return to the PowerDensity function and we observe that execution advances to line 8 as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−67
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
The plot is displayed as shown below.
3−68
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
If we want to see the value of the variable Power in line 10, we place the text cursor over the text Power for about two seconds, and the value appears as shown below. Using the same procedure, we can see the value of any data. The values can also be seen in the MATLAB Command window. When a breakpoint is reached, the debug>> command appears.* At this prompt, we enter the name of the data, for example, debug>> Power
Power = 2.6101e-007 debug>> *
We may need to press the Enter key to see it.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−69
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
If we want to leave the function until it is called again, we click the Continue Debugging tool and the breakpoint on line 7 is reached again as shown below. Then, we can advance through the execution of the remaining statements with the Continue Debugging tool.
3−70
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
To remove the breakpoint at line 7, we click it and then we click the green arrow to complete execution of the simulation. The model then will be completed as shown below.
NOTE: In electromagnetic waves and antennas textbooks the Power Density and Electric Field Strength are plotted in logarithmic scales in terms of the radiated power P t and distance R . These can be easily constructed with the following MATLAB script: Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−71
Chapter 3 Embedded MATLAB Functions in Stateflow Charts Pt=1; R=10:10000; PD=1.64.*Pt./(4.*pi.*R.^2); EF=sqrt(49.2.*Pt)./R; loglog(R,PD,R,EF); grid; xlabel('Distance in meters'); ylabel('Power Density, Field Strenth'); title('Power Density and Field Strenth as a function of distance');
3−72
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises 2.
In the MATLAB Command window we type sfnew
and the untitled model shown below is displayed.
From the Simulink Library Browser, we highlight the Commonly Used Blocks library and from it we drag two Constant blocks. Then we highlight the Sinks library and from it we drag three Display blocks. We name it Poisson_Erlang_Stateflow and now it appears as shown below.
We double-click the Stateflow Chart and the Stateflow Editor window appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−73
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
In the Stateflow Editor window above, we drag three Embedded MATLAB functions into the empty space of the Stateflow Editor using the Embedded MATLAB Function tool from the tool palette. We observe that a flashing text cursor appears, and we define the first function as Poissonout=Poisson(value1,value2)
the second as ErlangBout=ErlangB(value1,value2)
and the third as ErlangCout=ErlangC(value1,value2)
These labels conform to the Embedded MATLAB function syntax return_value=function_name(argument1, argument2,...)
where the return_value and each argument can be a scalar, vector, or matrix of values. A matrix is a two−dimensional array (rows and columns) of values, and a vector is a matrix with a row or column with one dimension. Multiple return values are not allowed.
3−74
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises The Stateflow Editor window now appears as shown below. The label eM above the flashing text cursor where we enter the function name, indicates that this is an Embedded MATLAB function.
In the Stateflow Editor window above, we drag the Default Transition tool to form a terminating junction, we click the question (?) mark to change it to a flashing text editor, and we type {PoissonProb = Poisson(invalue1,invalue2); ErlangBProp = ErlangB(invalue1,invalue2); ErlangCProp = ErlangC(invalue1,invalue2);}
and the Stateflow Editor window now appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−75
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
The function names at the Default Transition tool and the eM functions must be the same. Thus, in the Stateflow Editor window below, the function names Poisson, ErlangB, and ErlangC are the same for the Default Transition tool and the eM functions. The label on the Default Transition provides a condition action that calls the eM functions with arguments and a return value. When the Stateflow block is triggered during simulation, the Default Transition is taken and calls to the Poisson, ErlangB, and ErlangC functions are made.The return values of the eM functions, i.e., Poissonout, ErlangBout, and ErlangCout are often referred to as the signature return values. The return values of the Default Transition, i.e., PoissonProb, ErlangBProb, and ErlangCProb must match the signature return values Poissonout, ErlangBout, and ErlangCout, and the type of arguments in the Default Transition, i.e., invalue1 must match the type of the signature arguments, i.e., value1. This will be ensured later when we define the inputs and outputs in the Model Explorer window. In the Stateflow Editor window above, we double-click the eM dipoleP function to edit its function body in the Embedded MATLAB Editor shown below.
3−76
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
In the Embedded MATLAB Editor above, we select Tools>Model Explorer, and the Model Explorer window appears as shown below.
We observe that the function Poisson is highlighted in the Model Hierarchy pane (left), and the Contents pane (right) displays the input arguments value1 and value2, and output argument Poissonout. By default, both are scalars of type double.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−77
Chapter 3 Embedded MATLAB Functions in Stateflow Charts We return to the Stateflow Editor window and we double-click the eM ErlangB function to edit its function body in the Embedded MATLAB Editor shown in below.
In the Embedded MATLAB Editor above we select Tools>Model Explorer, and the Model Explorer window appears as shown below.
3−78
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises We observe that the function ErlangB is highlighted in the Model Hierarchy pane (left), and the Contents pane (right) displays the input arguments value1 and value2, and output argument ErlangBout. By default, both are scalars of type double. We return to the Stateflow Editor window and we double-click the eM ErlangC function to edit its function body in the Embedded MATLAB Editor shown in below.
In the Embedded MATLAB Editor above we select Tools>Model Explorer, and the Model Explorer window appears as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−79
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
We observe that the function ErlangC is highlighted in the Model Hierarchy pane (left), and the Contents pane (right) displays the input arguments value1 and value2, and output argument ErlangCout. By default, both are scalars of type double. In the Model Hierarchy pane of the Model Explorer above, we select Chart, from the Add drop menu we select the following data: Name
3−80
, and under the indicated columns in the Contents pane we add Scope
Size
invalue1
Input from Simulink
Scalar (no change)
invalue2
Input from Simulink
Scalar (no change)
PoissonProb
Output to Simulink
Scalar (no change)
ErlangBProb
Output to Simulink
Scalar (no change)
ErlangCProb
Output to Simulink
Scalar (no change)
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises The Contents pane in the Model Explorer now appears as shown below.
Our Simulink model is now built and appears as shown below after connecting the Constant blocks to the inputs of the Stateflow Chart and the Display blocks to the outputs of the Stateflow Chart. We have renamed the Constant blocks E for the number of Erlangs, and T for the number of Trunks. The values of E and T will be defined in the MATLAB command prompt. We save the model and we will program the Stateflow chart in the next paragraphs.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−81
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
We begin the programming by opening our saved model Poisson_Erlang_Stateflow and in the Stateflow Editor window we double-click the eM Poisson function and this opens the Embedded MATLAB Editor window shown below.
After the function header in the Embedded MATLAB Editor window above, we enter a line space and we type the following comment lines: % This function computes the probability of blocked calls for a % traffic system using the Poisson model. The number of Erlangs % and Trunks will be entered in MATLAB's Command Window. %
The Embedded MATLAB Editor window now appears as shown below.
3−82
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
Next, we enter the following statement: eml.extrinsic(‘plot’,’sum’);
The command plot will enable us to see the input values of E and T in a plot to be defined below, and the function sum will enable us to perform summation of values over a range specified by the equation that defines the Poisson model. As we now know, there are a number of MATLAB functions are not supported by the Embedded MATLAB subset, and plot is one of them. Should there be necessary to use MATLAB functions that are not supported by the Embedded MATLAB subset, we must first declare them to be extrinsic as described in “Calling MATLAB Functions” in the Embedded MATLAB documentation. The complete script for the Embedded MATLAB function Poissonout is listed below. function Poissonout=Poisson(value1,value2) % This function computes the probability of blocked calls for a % traffic system using the Poisson model. The number of Erlangs % and Trunks will be entered in MATLAB's Command Window. % eml.extrinsic('plot',’sum’) Poissonout=PP(value1,value2) function PoissonProb=PP(E,T) PoissonProb=1−exp(−E).*sum(E.^(0:T-1)./factorial(0:T-1)); plot(E,T,’-+’); %
This script is entered into the Embedded MATLAB Editor window as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−83
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
The complete script for the Embedded MATLAB function ErlangBout is listed below. function ErlangBout=ErlangB(value1,value2) % This function computes the probability of blocked calls for a % traffic system using the ErlangB model. The number of Erlangs % and Trunks will be entered in MATLAB's Command Window. % ErlangBout=PEB(value1,value2) function ErlangBProb=PEB(E,T) ErlangBProb=(E.^T/factorial(T))./(sum(E.^(0:T)./factorial(0:T))); %
This script is entered into the Embedded MATLAB Editor window as shown below.
3−84
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
The complete script for the Embedded MATLAB function ErlangCout is listed below. function ErlangCout=ErlangC(value1,value2) % This function computes the probability of blocked calls for a % traffic system using the ErlangC model. The number of Erlangs % and Trunks will be entered in MATLAB's Command Window. % ErlangCout=PEC(value1,value2) function ErlangCProb=PEC(E,T) ErlangCProb=(E.^T./(factorial(T).*(T−E)))./((sum(E.^(0:T-1)... ./factorial(0:T-1))+E.^T./(factorial(T).*(T-E)))) %
This script is entered into the Embedded MATLAB Editor window as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−85
Chapter 3 Embedded MATLAB Functions in Stateflow Charts
The saved model is shown below.
In MATLAB’s Command Window we enter the values E=4; T=10;
we issue the simulation command, and Simulink responds with the following messages:
3−86
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
Let us replace the Stateflow Chart with an Embedded MATLAB Function block from the Simulink User-Defined Function library, as shown below, to find out whether this block imposes the same requirement.
We name this model Poisson_Erlang_Simulink. We double-click the Embedded MATLAB Function block and in the Embedded MATLAB Editor window we erase the existing contents and we define a new function file as:
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−87
Chapter 3 Embedded MATLAB Functions in Stateflow Charts function [PoissonProb,ErlangBProb,ErlangCProb]=Probability(E,T) % This function computes the probability of blocked calls for a % traffic system using the Poisson, Erlang B, and Erlang C models. % The number of Erlangs (E) and Trunks (T) will be entered in % MATLAB's Command Window. % PoissonProb=1-exp(-E).*sum(E.^(0:T-1)./factorial(0:T-1)); % ErlangBProb=(E.^T/factorial(T))./(sum(E.^(0:T)./factorial(0:T))); % ErlangCProb=(E.^T./(factorial(T).*(T-E)))./((sum(E.^(0:T-1)... ./factorial(0:T-1))+E.^T./(factorial(T).*(T-E)))); %
The Embedded MATLAB Editor window now appears as shown below.
The Simulink model now appears as shown below.
3−88
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises
We interconnect the blocks as shown below, in MATLAB’s Command Window we enter the values E=4; T=10;
we issue the simulation command, and Simulink responds with the following messages:
These are the same error messages that we received with the Stateflow Chart.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−89
Chapter 3 Embedded MATLAB Functions in Stateflow Charts To obtain the probability values for each of the three traffic models, in the Embedded MATLAB Editor window we replace the offending variable T with its numerical value, i.e., T = 10 , so that 0:T-1 is replaced with 0:9 .* When this is done, we re-issue the simulation command and the Simulink model now appears as shown below.
These values are verified in MATLAB, i.e., E=4; T=10; >> >> PoissonProb=1-exp(-E).*sum(E.^(0:T-1)./factorial(0:T-1))
PoissonProb = 0.0081 >> ErlangBProb=(E.^T/factorial(T))./(sum(E.^(0:T)./factorial(0:T)))
ErlangBProb = 0.0053 >> ErlangCProb=(E.^T./(factorial(T).*(T-E)))./((sum(E.^(0:T-1)... ./factorial(0:T-1))+E.^T./(factorial(T).*(T-E))))
ErlangCProb = 8.8852e-004 It should be noted that these traffic models are used differently as described below.
* Of course, this is not a viable solution. When limitations of this nature occur in Stateflow Charts and in Simulink, we would be better off to use just MATLAB.
3−90
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises In the Poisson model, blocked calls are held until a trunk becomes available, and assumes a random call arrival pattern. The caller makes only one attempt to place the call and blocked calls are lost. The Erlang B model is used when blocked calls are rerouted, and they never come back to the original trunk. It assumes a random call arrival pattern. The caller makes only one attempt and if the call is blocked, then it is rerouted. The Erlang C model assumes a random call arrival pattern where the caller makes one call and it is held in a queue until the call is answered. For more information on traffic models for data, the interested reader may refer to: http://www.cisco.com/en/US/tech/tk652/tk701/ technologies_white_paper09186a00800d6b74.shtml
Introduction to Stateflow®with Applications Copyright © Orchard Publications
3−91
Chapter 3 Embedded MATLAB Functions in Stateflow Charts NOTES:
3−92
Introduction to Stateflow®with Applications Copyright © Orchard Publications
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 4 Model Coverage for Embedded MATLAB Functions The Stateflow documentation presents an example model named intersecting_rectangles where the if statement is tested for Decision Coverage. Other statements that can be tested for Decision Coverage are switch, for, and while. However, we can create a model without these statements as illustrated with the example below. Example 4.1 Consider the electric circuit shown in Figure 4.2.
R
IS
C
L
Figure 4.2. A parallel resonant frequency circuit
From electric circuit* theory, we know that the resonant frequency f 0 is found from the relation 1 f 0 = ------------------- † 2π LC
or in terms of the radian frequency ω 0 from the relation 1 ω 0 = ----------LC
Often, we want to adjust the variable capacitor indicated with an arrow in Figure 4.2, to produce a desired resonant frequency. In practice, the value of the inductor L is held fixed and the value of the capacitor is varied. For our model, we want to set the value of the capacitor C so that the radian resonant frequency ω 0 will be 1000 rad ⁄ sec . It is known that the capacitor can be adjusted from 1 μF to 20 μF at increments of 1 μF . We begin by typing sfnew at the MATLAB command prompt. A Stateflow Chart block appears and from the Simulink Sinks Library we drag a Display block. Our model now is as shown in Figure 4.3.
* For a detailed discussion on parallel resonant frequency, please refer to Circuit Analysis II with MATLAB Applications, ISBN 0−9709511−5−9. † The value of the resistor R is independent of the frequency.
4−2
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions
Figure 4.3. The components of the model of Example 4.1
In Figure 4.3 we double−click the Stateflow Chart and in the Stateflow Editor window we use the State tool
to drag a state (rectangle with rounded corners), we drag and attach the Default
Transition tool to it, we drag the Embedded MATLAB Function tool type the labels shown in Figure 4.4.
, and we
Figure 4.4. The Stateflow Chart Editor for Example 4.1
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−3
Chapter 4 Model Coverage for Embedded MATLAB Functions As shown in the Stateflow Editor window in Figure 4.4, the Stateflow Chart has a state with a default transition and en(entry) and du(during) actions. The state executes its entry action for the first time that is entered for the first time sample. Thereafter, each time sample calls the during action of the active state. In the Stateflow Editor window in Figure 4.4, we click the Add drop menu, we select Data>Output to Simulink, we change the name to wout, and in the Scope field we specify Port 1. Our model now appears as shown in Figure 4.5 after connecting the output of the Stateflow Chart to the input of the Display block.
Figure 4.5. The model for Example 4.1 after interconnecting the blocks
In the Stateflow Editor window in Figure 4.4, we click the Explorer tool and the Model Explorer window appears as shown in Figure 4.6. We observe that when the frequency variable is highlighted in the Model Hierarchy pane (left) the variables Cin and woutput are shown in the Contents pane.* Initially, there are no values indicated for the variables Cin and woutput under the Size column. We double−click the Cin row under the Size column and we set the size of Cin to 1,20 as indicated in Figure 4.6. Using the same procedure, we set the size of the variable woutput to 1,20. In the Model Explorer window in Figure 4.6 we click the Chart in the Model Hierarchy pane (left) to select it and we observe that the Contents pane displays the variables wout, C, and valueC as shown in Figure 4.7. Initially, there are no values indicated for these variables under the Size column. We double−click the wout row under the Size column and we set the size of wout to 1,20 as indicated in Figure 4.7. Using the same procedure, we set the sizes of the variables C, and valueC to 1,20.
* If these values are not shown, they can be added using the Add Data tool text editor.
4−4
.They can also be modified using the mouse
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions
Figure 4.6. The Model Explorer for Example 4.1 showing the input and outputs of the frequency function
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−5
Chapter 4 Model Coverage for Embedded MATLAB Functions
Figure 4.7. The Model Explorer for Example 4.1 showing the Chart variables
In the Stateflow Editor window of Figure 4.4, we double−click the eM woutput=frequency(Cin) Embedded MATLAB Function rectangle and we observe that the Embedded MATLAB Editor window appears where line 1 displays function woutput = frequency(Cin). Under this line we add the following script: % The generated plot will display the value of % the capacitance for which the resonant frequency % is 10000 rad/sec. eml.extrinsic('plot','grid','xlabel','ylabel','title'); L=0.1; C=10^(−6):10^(−6):20*10^(−6); woutput=1./sqrt(L.*C); plot(C,'−+'); grid; xlabel('Capacitande in microfarads'); ylabel('Frequency in rads/sec')
The Embedded MATLAB Editor window now appears as shown in Figure 4.8.
4−6
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions
Figure 4.8. The Embedded MATLAB Editor window for the woutput function
In the model of Figure 4.9 we issue the start simulation command and the Display block shows the first four values of the radian frequency corresponding to the capacitance values from 1 μF to 20 μF . Perhaps the reader can think of a method to display the 20 values of the radian frequency in a column. This is left as an exercise for the reader at the end of this chapter. The plot in Figure 4.10 shows the radian frequency versus capacitance and that the resonant frequency occurs when the variable capacitor is set at 10 μF .
Figure 4.9. The values of the radian frequency after the simulation start command
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−7
Chapter 4 Model Coverage for Embedded MATLAB Functions
Figure 4.10.
In Example 4.1 above, we did not use decisions and conditions of Embedded MATLAB functions in Stateflow. We will use decisions and conditions in Example 4.2 below. Example 4.2 From analytic geometry we know that two straight line segments L 1 and L 2 are orthogonal (perpendicular) to each other if their slopes m 1 and m 2 satisfy the relation m 1 m 2 = – 1 as shown in Figure 4.11 below. y
m1 ⋅ m2 = –1
slope = m 1 slope = m 2
x Figure 4.11. Orthogonal straight line segments
4−8
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions We will create a model with Embedded MATLAB Function Decisions. We will name this model orthogonal_segments. It consists of a Stateflow Chart block with no input and its output is sent to a Display block as shown in Figure 4.12 below. As before, the Stateflow Chart was created by typing sfnew in the MATLAB command prompt, and the Display blocks were dragged from the Simulink Sinks Library.
Figure 4.12. The blocks for the model of Example 4.2
In Figure 4.12 we double−click the Stateflow Chart and in the Stateflow Editor window we use the State tool
to drag a state (rectangle with rounded corners), we drag and attach the
Default Transition tool to it, we drag the Embedded MATLAB Function tool and we type the labels shown in Figure 4.13.
,
As shown in the Stateflow Editor window in Figure 4.13, the Stateflow Chart has a state with a default transition and en(entry) and du(during) actions. The state executes its entry action for the first time that is entered for the first time sample. Thereafter, each time sample calls the during action of the active state. In the Stateflow Editor window in Figure 4.13, we click the Add drop menu, we select Data>Output to Simulink, we change the name to m1, and in the Scope field we specify Port 1. Using the same procedure the second output m2. Our model now appears as shown in Figure 4.14 where we have connected the outputs of the Stateflow Chart to the inputs of the Display blocks.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−9
Chapter 4 Model Coverage for Embedded MATLAB Functions
Figure 4.13. The Stateflow Chart Editor for the model of Example 4.2
Figure 4.14. The interconnected blocks for the model of Example 4.2
In the Stateflow Editor window in Figure 4.13, we click the Explorer tool and the Model Explorer window appears as shown in Figure 4.15. We observe that when the Chart is highlighted in the Model Hierarchy pane (left) the variable m2 is shown in the Contents pane.
4−10
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions
Figure 4.15. The Model Explorer showing the Chart variables
We click the slope1 function under Chart in the Model Hierarchy pane (left) and we observe that the argument segment and output m1 and are displayed in the Contents pane as shown in Figure 4.16. We also click slope2 function under Chart in the Model Hierarchy pane (left) and we observe that the argument segment and output m2 are displayed in the Contents pane as shown in Figure 4.17.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−11
Chapter 4 Model Coverage for Embedded MATLAB Functions
Figure 4.16. The Model Explorer showing the slope1 variables
In the Stateflow Editor window of Figure 4.13, we double−click the eM m1=slope1(segment) Embedded MATLAB Function rectangle and we observe that the Embedded MATLAB Editor window appears where line 1 displays function m1=slope1(segment). Under this line we add the following script: % The variable m2 outputs the slope of the % second line segment eml.extrinsic('input','if','else','end'); m1=input('Enter value of the slope of first straight line segment '); if m1>0 m2=−1/m1; else m2=abs(1/m1); end disp('slope of segment 2 is'); disp(m2) end
4−12
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions
Figure 4.17. The Model Explorer showing the slope2 variables
The Embedded MATLAB Editor window for function m1 now appears as shown in Figure 4.18.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−13
Chapter 4 Model Coverage for Embedded MATLAB Functions
Figure 4.18. The Embedded MATLAB Editor for the slope1 function
In the Stateflow Editor window of Figure 4.13, we double−click the eM m2=slope2(segment) Embedded MATLAB Function rectangle and we observe that the Embedded MATLAB Editor window appears where line 1 displays function m2=slope2(segment). Under this line we add the following script: m1=input('Enter value of the slope of first straight line segment '); if m1>0 m2=−1/m1; else m2=abs(1/m1); end disp('slope of segment 2 is'); disp(m2) x=input('Another slope? (<enter>=no, 1=yes)','s'); m1=input('Enter value of the slope of first straight line segment '); if m1>0 m2=−1/m1; else m2=abs(1/m1); end disp('slope of segment 2 is'); disp(m2)
4−14
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions The Embedded MATLAB Editor window for function m2 now appears as shown in Figure 4.19.
Figure 4.19. The Embedded MATLAB Editor for the slope2 function
Our Simulink model now appears as shown in Figure 4.20.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−15
Chapter 4 Model Coverage for Embedded MATLAB Functions
Figure 4.20. The complete model for Example 4.2
With the Command window and the model in Figure 4.20 both visible, we start simulation by clicking the Start Simulation tool
and the Command window returns the message below:
Enter value of the slope of first straight line segment We type 2 and the model displays both slopes as shown in Figure 4.21. We start simulation again, and in response to the message above, we type −0.75 and the model displays both slopes as shown in Figure 4.22.
Figure 4.21. The values of m1 and m2 after the simulation command execution
4−16
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions
Figure 4.22. The model for Example 4.2 with different values of m1 and m2
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−17
Chapter 4 Model Coverage for Embedded MATLAB Functions 4.2 Summary • This chapter describes the procedure for adding Embedded MATLAB functions to Stateflow charts. • The Model Coverage tool in Simulink reports model coverages for the decisions and conditions of Embedded MATLAB functions in Stateflow. • We use the Model Coverage tool for Embedded MATLAB functions to ascertain that all decisions and conditions are in conformance with the simulation objectives in our model. • A description of Model Coverage topics is provided in the Simulink documentation. • During simulation, the following Embedded MATLAB block function statements are tested for Decision Coverage: 1. Function header − Decision coverage is 100% if the function or subfunction is executed. 2. If − Decision coverage is 100% if the if expression evaluates to true at least once and false at least once. 3. switch − Decision coverage is 100% if every switch case is taken, including the fall−through case. 4. for − Decision coverage is 100% if the equivalent loop condition evaluates to true at least once, and false at least once. 5. while − Decision coverage is 100% if the equivalent loop condition evaluates to true at least once, and false at least once. • During simulation, the following logical conditions are tested for Condition Coverage and The Modified Condition Decision Coverage (MCDC)* in the Embedded MATLAB block function: 1. If statement conditions 2. while statement conditions, if present • The Stateflow documentation presents an example model intersecting_rectangles where the if statement is tested for Decision Coverage.
* The MCDC option reports a test's coverage of occurrences in which changing an individual subcondition within a transition results in changing the entire transition trigger expression from true to false or false to true.
4−18
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Exercises for the Reader 4.3 Exercises for the Reader 1.
2.
In Example 4.1 the values of the radian frequency were displayed in a row−wise vector. Can you think of a method that these values will be displayed in a column−wise vector as shown below?
A book distributor offers discounts to booksellers in accordance with the following quantities: Books Sold
Percent Discount
Less than 25
20
Exactly 25
30
More than 25
40
For a book whose retail price is $50.00, create a Simulink model that includes a Stateflow Chart that returns the cost to the booksellers after the discounts shown in the table above have been applied.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−19
Chapter 4 Model Coverage for Embedded MATLAB Functions 4.4 Solution to the End−of−Chapter Exercises 1. One way is to insert the Simulink Reshape block* from the Math Operations library between the Stateflow Chart and the Display block as shown below.
2.
We will create a model with Embedded MATLAB Function Decisions. We will name this model books_stateflow. It will consist of a Stateflow Chart block with no input and its output will be sent to a Display block as shown below. As before, the Stateflow Chart was created by
* This block is discussed in Introduction to Simulink with Engineering Applications, ISBN 0−9744239−7−1.
4−20
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End−of−Chapter Exercises typing sfnew in the MATLAB command prompt, and the Display block was dragged from the Simulink Sinks Library.
In the model above, we double−click the Stateflow Chart and in the Stateflow Editor window we use the State tool
to drag a state (rectangle with rounded corners), we drag and attach the
Default Transition tool to it, we drag the Embedded MATLAB Function tool and we type the labels shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
,
4−21
Chapter 4 Model Coverage for Embedded MATLAB Functions As shown in the Stateflow Editor window above, the Stateflow Chart has a state with a default transition and en(entry) and du(during) actions. The state executes its entry action for the first time that is entered for the first time sample. Thereafter, each time sample calls the during action of the active state. In the Stateflow Editor window above, we click the Add drop menu, we select Data>Output to Simulink, we change the name to cost, and in the Scope field we specify Port 1. Our model now appears as shown below where we have connected the output of the Stateflow Chart to the input of the Display block.
In the Stateflow Editor window, we click the Explorer tool and the Model Explorer window appears as shown below. We observe that the Chart is highlighted in the Model Hierarchy pane (left) the row vector cost is shown in the Contents pane.
4−22
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End−of−Chapter Exercises
Under Chart in the Model Hierarchy pane (left), we click the books function and we observe that the input argument x and output argument cost are displayed in the Contents pane as shown below.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
4−23
Chapter 4 Model Coverage for Embedded MATLAB Functions
In the Stateflow Editor window, we double−click the eM cost=books(x) Embedded MATLAB Function rectangle and we observe that the Embedded MATLAB Editor window appears where line 1 displays function cost=books(x) as shown below.
Under this line we add the following script: % The cost varies with the amount x of the books sold % eml.extrinsic(‘input’, 'if','elseif','end');
4−24
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End−of−Chapter Exercises x=input('Enter number of books sold x: '); cost=50*x; if xNew>Library, we name it library1_stateflow, and we rename the Chart block Library 1 Chart as shown in Figure 5.25.
Figure 5.25. The Library 1 Stateflow chart
As indicated in the lower right corner of the Library 1 Stateflow chart, the Chart is locked* and to access the flow diagram we must unlock it. This is done by selecting Edit>Unlock Library and it is now unlocked as shown in Figure 5.26.
* This occurs whenever we save and close the model and we reopen it at a later time.
5−18
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow
Figure 5.26. The Library 1 Chart Unlocked
In Figure 5.26 above, we double-click the Library 1 Chart block and in the Stateflow Editor we enter the function definition and graphical function shown in the flow diagram in Figure 5.27.* The flow diagram must include a default transition with a terminating junction.
Figure 5.27. The function definition and graphical function for Library 1 Chart
We right-click outside the graphical function box shown in Figure 5.27, and from the pop-up menu shown in Figure 5.28 we select Properties.
* The function box has been enlarged to accommodate the width of the label signature. This can be done by moving the cursor to one of the corners of the box and when it shows as a double-headed arrow we move it to enlarge the box.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−19
Chapter 5 Graphical Functions
Figure 5.28. Selecting Properties from the pop-up menu
The Chart Properties dialog box for Library 1 Chart appears as shown in Figure 5.29 where we have checked the Export Chart Level Functions to enable it.
5−20
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow
Figure 5.29. The Chart Properties dialog box for selecting Export Chart Level Functions
From the Simulink Library Browser, we select File>New>Library, we name it library2_stateflow, and we rename the Chart block Library 2 Chart as shown in Figure 5.30.
Figure 5.30. The Library 2 Stateflow chart
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−21
Chapter 5 Graphical Functions In Figure 5.30 above, we double-click the Library 2 Chart block and in the Stateflow Editor we enter the function definition and graphical function shown in the flow diagram in Figure 5.31.* The flow diagram must include a default transition with a terminating junction.
Figure 5.31. The function definition and graphical function for Library 2 Chart
We right-click outside the graphical function box shown in Figure 5.31, and from the pop-up menu shown in Figure 5.32 we select Properties.
* The function box has been enlarged to accommodate the width of the label signature. This can be done by moving the cursor to one of the corners of the box and when it shows as a double-headed arrow we move it to enlarge the box.
5−22
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow
Figure 5.32. Selecting Properties from the pop-up menu
The Chart Properties dialog box for Library 2 Chart appears as shown in Figure 5.33 where we have checked the Export Chart Level Functions to enable it. In MATLAB’s Command window we type sfnew
We we name it model_stateflow, and we rename the Chart block Main Chart as shown in Figure 5.34.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−23
Chapter 5 Graphical Functions
Figure 5.33. The Chart Properties dialog box for selecting Export Chart Level Functions
Figure 5.34. The Main Chart model
In the model of Figure 5.34 above, we double-click the Main Chart block and in the Stateflow Editor we enter the function definition and graphical function shown in the flow diagram in Figure 5.35. The flow diagram must include a default transition with a terminating junction.
5−24
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow
Figure 5.35. The function definition and graphical function for Model Chart
We right-click outside the graphical function box shown in Figure 5.35, and from the pop-up menu shown in Figure 5.36 we select Properties.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−25
Chapter 5 Graphical Functions
Figure 5.36. Selecting Properties from the pop-up menu
The Chart Properties dialog box for Model Chart appears as shown in Figure 5.37 where we have checked the Export Chart Level Functions to enable it.
5−26
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow
Figure 5.37. The Chart Properties dialog box for selecting Export Chart Level Functions
Figure 5.38 below contains the model model_stateflow , the library Stateflow charts library1_stateflow and library2_stateflow, their function definition, their graphical functions, and their interrelationship.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−27
Chapter 5 Graphical Functions
Figure 5.38. The three charts and their graphical functions
Next, we drag both Library 1 Chart and Library 2 Chart into the model Chart and the Simulink model with the three charts is shown in Figure 5.39.
Figure 5.39. The three charts in one Simulink model
Each chart now defines a graphical function that can be called by any other chart placed in the model where the Main Chart block resides.The sequence of action in simulation of the Main Chart model is as follows: The chart named Main Chart block calls the graphical function library1_func, with the three arguments, x, y, and z. Then, library1_func calls the graphical function library2_func, passing the same three arguments. Finally, library2_func calls the graphical function model_func, and this adds x, y, and z.The result of the addition is assigned to w. We must remember that states are not allowed in graphical functions. This is because a function must execute completely when it is called.
5−28
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Summary 5.5 Summary • 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 discussed 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. • To create a Stateflow graphical function in Stateflow diagrams 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. • 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 )
• A graphical function can reside anywhere in a chart, state, or subchart. The location of a function determines its scope, that is, the set of states and transitions that can call the function. Graphical functions are visible to the chart, to the parent state and its parents, and to sibling transitions and states with the following exceptions: a. If the chart containing the function exports its graphical functions, the scope of the function is the entire Stateflow machine, which encompasses all the charts in the model. b. A function defined in a state or subchart overrides any functions of the same name defined in the parents and ancestors of that state or subchart. • A subchart is a chart that is embedded in another chart. A subcharted state is a superstate of the states and charts that it contains, and it appears as a block with its name in the block center. • To convert a graphical function to a subchart, we right-click the graphical function block, from the pop-up menu we select Make Contents and from the submenu we select Subcharted. This makes the graphical function opaque, and it appears as a block with its name in the block center. • We can export the root-level functions of a chart to the remaining charts in the chart's model. Exporting a chart's functions extends their scope to include all other charts in the same model.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−29
Chapter 5 Graphical Functions • We can also export functions in library charts to a model as long as the library charts are present in the model. • States are not allowed in graphical functions. This is because a function must execute completely when it is called.
5−30
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Exercise for the Reader 5.6 Exercise for the Reader Using the graphical function method, create a Simulink model that includes a Stateflow Chart to approximate the roots accurate to two decimal places of the function y = cos 2x + sin 2x + x – 1
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−31
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
Solution to the End-of-Chapter Exercise We double click the Chart block and Simulink displays the Stateflow Editor with the contents that we have added after selecting and moving the graphical function tool area as shown below.
in the empty
To convert the graphical function to a subchart, we right-click the graphical function block and the pop-up menu shown below appears. In that menu, we select Make Contents and from the submenu we select Subcharted. This has made the graphical function opaque as shown in Figure 5.19, and it appears as a block with its name in the block center.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−33
Chapter 5 Graphical Functions
5−34
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercise In the Stateflow Chart Editor above, we click the Model Explorer icon and in the Model Hierarchy pane (left), we select Chart, and when it is highlighted, it appears as shown below.
In the toolbar of the Model Explorer window above, we click Add, we select , in the Contents pane we change data to xin, from the Scope column we choose Input, and with this , in row selected, under the Size column we enter 1,6.* We click Add again, we select the Contents pane we change data to yout, from the Scope column we choose Output, and with this row selected, under the Size column we enter 1,6. The Model Explorer now appears as shown below.
* We specified six values, 0 through 5 for the input x and therefore the input size must be specified as a row vector of size (1,6). The same is true for the output y.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−35
Chapter 5 Graphical Functions
The Simulink model is shown in Figure 5.22 with the blocks interconnected.
5−36
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Solution to the End-of-Chapter Exercise We name this model polynomial02_stateflow and in the MATLAB command window we enter x=1.27:0.01:1.32; % This is the range where the second root is located
We issue the simulation command and the model displays the input and corresponding output values.
From the input and output values in the model above, we observe that at x = 1.28 , y = – 0.006 , and thus we can say that the second root of the given function is approximately x = 1.28 . To find the third root, we use the same model and at the MATLAB command prompt we enter x=2.19:0.01:2.24; % This is the range where the third root is located
Introduction to Stateflow®with Applications Copyright © Orchard Publications
5−37
Chapter 5 Graphical Functions
From the input and output values in the model above, we observe that at x = 2.23 , y ≈ 0.012 , and thus we can say that the second root of the given function is approximately x = 2.23 .
5−38
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Chapter 6 Connective Junctions
T
his chapter 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.
6.1 The Stateflow Connective Junction Tool Figure 6.1 is our familiar Stateflow Editor window, and when we place the mouse cursor over the Connective Junction tool
, its name appears at the bottom of the window.
Figure 6.1. The Stateflow Editor window
Introduction to Stateflow®with Applications Copyright © Orchard Publications
6−1
Chapter 6 Connective Junctions 6.2 Creating a Connective Junction To create a connective junction, we do the following: 1. In the diagram toolbar, we click the Connective Junction tool
.
2. We move the cursor into the diagram editor.The cursor takes on the shape of a connective junction as shown in Figure 6.2. We click to place a connective junction in the desired location in the drawing area.
Figure 6.2. Placing a connective junction in the drawing area
To create multiple connective junctions, we do the following: 1. In the diagram toolbar, we double−click the Connective Junction tool tive junction is now in multiple object mode.
and the connec-
2. We click anywhere in the drawing area to place a connective junction in the drawing area. We move to and click another location to create an additional connective junction. We click the Connective Junction tool or we press the Esc key to terminate the operation. To move a connective junction to a new location, we click and we drag it to the new position.
6−2
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Changing Connective Junction Size
Figure 6.3.
6.3 Changing Connective Junction Size To change the size of connective junctions, we do the following: 1. We select the connective junctions whose size we want to change. 2. We place the cursor over one of the connective junctions and we right−click. In the resulting pop−up menu shown in Figure 6.4, we place the cursor over Junction Size. A submenu of junction sizes appears as shown in Figure 6.5, and we select a size from the menu of junction sizes.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
6−3
Chapter 6 Connective Junctions
Figure 6.4. Pop-up menu for changing the size of a connective junction
6−4
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Changing Connective Junction Size
Figure 6.5. Pop up menu and submenu for selecting connective junction sizes
We selected Size 10 for the connective junction on the left, and we changed the size to 10 as shown in Figure 6.6.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
6−5
Chapter 6 Connective Junctions
Size 7 Size 10
Size 7
Figure 6.6. Larger size for a connective junction
6.4 Changing Connective Junction Properties To edit the properties for a connective junction, we do the following: 1. We right−click a connective junction. In the resulting pop−up menu shown in Figure 6.4 above, we select Properties. The Connective Junction dialog box appears as shown in Figure 6.7 below.
Figure 6.7. The Connective Junction dialog box
6−6
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Uses of Connective Junctions 2. We edit the fields in the properties dialog, which are described in the table below. Field
Description
Parent
Parent of this state; read−only; click the hypertext link to bring the parent to the foreground.
Description
Textual description/comment.
Document Link
Enter a URL address or a general MATLAB command. Examples are www.mathworks.com, mailto:email_address, and edit/spec/data/speed.txt.
6.5 Uses of Connective Junctions We use connective junctions to represent common code structures like for loops and if−then− else constructs without the use of states. This reduces the number of states in our Stateflow diagrams, and the flow diagram notation produces more efficient generated code that optimizes memory use. With flow diagram notation we use combinations of the following: • Transitions to and from connective junctions • Self−loops to connective junctions • Inner transitions to connective junctions One Stateflow diagram can include flow diagram notation, states, and state−to−state transitions. It is imperative that we represent flow diagram notation with action language as illustrated in the examples that follow. In all examples, the rectangles with rounded corners represent states, the letter e represents events, and the letter c followed by a number, both enclosed in brackets, represents a condition. The general label format for a transition entering a state is shown in Figure 6.8* below.
Figure 6.8. The general label format for a transition entering a state
Execution of a transition from State S1 to State S2 in Figure 6.8 occurs as follows: 1. When an event (event) occurs, state S1 is checked for an outgoing transition with a matching event specified. * We recall from Chapter 1 that to draw transitions between states, we move the cursor to an edge of the origination state until the cursor shape changes to crosshairs, we hold down the left mouse button, we drag the cursor to an edge of the destination state, and we release the mouse button.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
6−7
Chapter 6 Connective Junctions 2. If a transition with a matching event is found, the condition for that transition ([condition]) is evaluated. 3. If the condition condition evaluates to true, the condition action ({condition_action}) is executed. 4. If the destination state (S2) is determined to be a valid destination, the transition occurs. 5. State S1 is exited. 6. The transition action (transition_action) is executed when the transition occurs. 7. State S2 is entered. The general label format for a transition segment entering a junction is the same as for transitions entering states, as shown in Figure 6.9 below.
Figure 6.9. The general label format for a transition segments
1. In Figure 6.9, when an event occurs, state S1 is checked for an outgoing transition with a matching event specified. 2. If a transition with a matching event is found, the transition condition for that transition (in brackets) is evaluated. 3. If condition_1 evaluates to true, the condition action condition_action (in braces) is executed. 4. The outgoing transitions from the junction are checked for a valid transition. Assuming that condition_2 is true, a valid state−to−state transition (S1 to S2) is found. 5. State S1 is exited and this includes the execution of S1's exit action.
6−8
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Uses of Connective Junctions 6. The transition action transition_action is executed. 7. The completed state−to−state transition (S1 to S2) is taken. 8. State S2 is entered and this includes the execution of S2's entry action. Example 6.1 This is a connective junction example with all conditions specified. Let us consider the flow diagram notations in Figure 6.10.
Figure 6.10. Flow diagram notations for Example 6.1
In the flow diagram on the left, if state D is active when event e occurs, the transition from state D to any of states E, F, or G takes place if one of the conditions [c1], [c2], or [c3] is met. In the equivalent representation on the right, a transition from the source state to a connective junction is labeled by the event. Transitions from the connective junction to the destination states are labeled by the conditions. If state D is active when event e occurs, the transition from D to the connective junction occurs first. The transition from the connective junction to a destination state follows based on which of the conditions [c1], [c2], or [c3] is true. If none of the conditions is true, no transition occurs and state D remains active. Example 6.2 This is a connective junction example with one unconditional transition specified. Let us consider the flow diagram notations in Figure 6.11.*
* We could have used the simpler notations e, [c1], and [c2].
Introduction to Stateflow®with Applications Copyright © Orchard Publications
6−9
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 * Inner matrix dimensions must agree. Here, because we have used the matrix multiplication operator (*) in A*B, MATLAB expects vector B to be a column vector, not a row vector. It recognizes that B is a row vector, and warns us that we cannot perform this multiplication using the matrix multiplication operator (*). Accordingly, we must perform this type of multiplication with a different operator. This operator is defined below. 2. Element−by−Element Multiplication (multiplication of a row vector by another row vector) Let C = [ c1 c2 c3 … cn ]
and D = [ d1 d2 d3 … dn ]
be two row vectors. Here, multiplication of the row vector C by the row vector D is performed with the dot multiplication operator (.*). There is no space between the dot and the multiplication symbol. Thus, C.∗ D = [ c 1 d 1
A−20
c2 d2
c3 d3
…
cn dn ]
(A.6)
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Multiplication, Division, and Exponentiation This product is another row vector with the same number of elements, as the elements of C and D . As an example, let C = [1 2 3 4 5]
and
D = [ –2 6 –3 8 7 ]
Dot multiplication of these two row vectors produce the following result. C.∗ D = 1 × ( – 2 ) 2 × 6 3 × ( – 3 ) 4 × 8 5 × 7 = – 2 12 – 9 32 35
Check with MATLAB: C=[1 2 3 4 5]; D=[−2 6 −3 8 7]; C.*D
% Vectors C and D must have % same number of elements % We observe that this is a dot multiplication
ans = -2
-9
12
32
35
Similarly, the division (/) and exponentiation (^) operators, are used for matrix division and exponentiation, whereas dot division (./) and dot exponentiation (.^) are used for element− by−element division and exponentiation, as illustrated in Examples A.11 and A.12 above. We must remember that no space is allowed between the dot (.) and the multiplication, division, and exponentiation operators. Note: A dot (.) is never required with the plus (+) and minus (−) operators. Example A.13 Write the MATLAB script that produces a simple plot for the waveform defined as y = f ( t ) = 3e
–4 t
cos 5t – 2e
–3 t
2
t sin 2t + ---------t+1
(A.7)
in the 0 ≤ t ≤ 5 seconds interval. Solution: The MATLAB script for this example is as follows: t=0: 0.01: 5; % Define t−axis in 0.01 increments y=3 .* exp(−4 .* t) .* cos(5 .* t)−2 .* exp(−3 .* t) .* sin(2 .* t) + t .^2 ./ (t+1); plot(t,y); grid; xlabel('t'); ylabel('y=f(t)'); title('Plot for Example A.13')
The plot for this example is shown in Figure A.8. Introduction to Stateflow®with Applications Copyright © Orchard Publications
A−21
Appendix A Introduction to MATLAB® Plot for Example A.13
5 4
y=f(t)
3 2 1 0 -1
0
0.5
1
1.5
2
2.5 t
3
3.5
4
4.5
5
Figure A.8. Plot for Example A.13
Had we, in this example, defined the time interval starting with a negative value equal to or less than – 1 , say as – 3 ≤ t ≤ 3 , MATLAB would have displayed the following message: Warning: Divide by zero. This is because the last term (the rational fraction) of the given expression, is divided by zero when t = – 1 . To avoid division by zero, we use the special MATLAB function eps, which is a number approximately equal to 2.2 × 10
– 16
. It will be used with the next example.
The command axis([xmin xmax ymin ymax]) scales the current plot to the values specified by the arguments xmin, xmax, ymin and ymax. There are no commas between these four arguments. This command must be placed after the plot command and must be repeated for each plot. The following example illustrates the use of the dot multiplication, division, and exponentiation, the eps number, the axis([xmin xmax ymin ymax]) command, and also MATLAB’s capability of displaying up to four windows of different plots. Example A.14 Plot the functions y = sin 2x,
z = cos 2x,
w = sin 2x ⋅ cos 2x,
v = sin 2x ⁄ cos 2x
in the interval 0 ≤ x ≤ 2π using 100 data points. Use the subplot command to display these functions on four windows on the same graph.
A−22
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Multiplication, Division, and Exponentiation Solution: The MATLAB script to produce the four subplots is as follows: x=linspace(0,2*pi,100); y=(sin(x).^ 2); z=(cos(x).^ 2);
% Interval with 100 data points
w=y.* z; v=y./ (z+eps);% add eps to avoid division by zero subplot(221);% upper left of four subplots plot(x,y); axis([0 2*pi 0 1]);
title('y=(sinx)^2');
subplot(222); plot(x,z); axis([0 2*pi 0 1]);
% upper right of four subplots
subplot(223); plot(x,w); axis([0 2*pi 0 0.3]);
% lower left of four subplots
subplot(224); plot(x,v); axis([0 2*pi 0 400]);
% lower right of four subplots
title('z=(cosx)^2');
title('w=(sinx)^2*(cosx)^2'); title('v=(sinx)^2/(cosx)^2'); These subplots are shown in Figure A.9. y=(sinx)2
1
0.5
0
z=(cosx)2
1
0.5
0
2
4 2
6
0
0
2
2
4 2
w=(sinx) *(cosx)
6 2
v=(sinx) /(cosx)
400
0.2 200 0.1 0
0
2
4
6
0
0
2
4
6
Figure A.9. Subplots for the functions of Example A.14
The next example illustrates MATLAB’s capabilities with imaginary numbers. We will introduce the real(z) and imag(z) functions that display the real and imaginary parts of the complex quantity z = x + iy, the abs(z), and the angle(z) functions that compute the absolute value (magnitude) and phase angle of the complex quantity z = x + iy = r ∠θ. We will also use the polar(theta,r) function that produces a plot in polar coordinates, where r is the magnitude, theta Introduction to Stateflow®with Applications Copyright © Orchard Publications
A−23
Appendix A Introduction to MATLAB® is the angle in radians, and the round(n) function that rounds a number to its nearest integer. Example A.15 Consider the electric circuit of Figure A.10. a
10 Ω 10 Ω
Z ab
10 μF 0.1 H
b
Figure A.10. Electric circuit for Example A.15
With the given values of resistance, inductance, and capacitance, the impedance Z ab as a function of the radian frequency ω can be computed from the following expression: 4
6
10 – j ( 10 ⁄ ω ) Z ab = Z = 10 + -------------------------------------------------------5 10 + j ( 0.1ω – 10 ⁄ ω )
(A.8)
a. Plot Re { Z } (the real part of the impedance Z) versus frequency ω. b. Plot Im { Z } (the imaginary part of the impedance Z) versus frequency ω. c. Plot the impedance Z versus frequency ω in polar coordinates. Solution: The MATLAB script below computes the real and imaginary parts of Z ab which, for simplicity, are denoted as z , and plots these as two separate graphs (parts a & b). It also produces a polar plot (part c). w=0: 1: 2000; % Define interval with one radian interval;... z=(10+(10 .^ 4 −j .* 10 .^ 6 ./ (w+eps)) ./ (10 + j .* (0.1 .* w −10.^5./ (w+eps))));... % % The first five statements (next two lines) compute and plot Re{z} real_part=real(z); plot(w,real_part);... xlabel('radian frequency w'); ylabel('Real part of Z'); grid
A−24
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Multiplication, Division, and Exponentiation 1200 1000
Real part of Z
800 600 400 200 0
0
200
400
600
800 1000 1200 radian frequency w
1400
1600
1800
2000
Figure A.11. Plot for the real part of the impedance in Example A.15 % The next five statements (next two lines) compute and plot Im{z} imag_part=imag(z); plot(w,imag_part);... xlabel('radian frequency w'); ylabel('Imaginary part of Z'); grid 600
Imaginary part of Z
400 200 0 -200 -400 -600
0
200
400
600
800 1000 1200 radian frequency w
1400
1600
1800
2000
Figure A.12. Plot for the imaginary part of the impedance in Example A.15 % The last six statements (next five lines) below produce the polar plot of z mag=abs(z); % Computes |Z|;... rndz=round(abs(z)); % Rounds |Z| to read polar plot easier;... theta=angle(z); % Computes the phase angle of impedance Z;... polar(theta,rndz); % Angle is the first argument ylabel('Polar Plot of Z'); grid
Introduction to Stateflow®with Applications Copyright © Orchard Publications
A−25
Appendix A Introduction to MATLAB® 90
1500
120
60
1000
Polar Plot of Z
150
30 500
180
0
210
330 240
300 270
Figure A.13. Polar plot of the impedance in Example A.15
Example A.15 clearly illustrates how powerful, fast, accurate, and flexible MATLAB is.
A.10 Script and Function Files MATLAB recognizes two types of files: script files and function files. Both types are referred to as m−files since both require the .m extension. A script file consists of two or more built−in functions such as those we have discussed thus far. Thus, the script for each of the examples we discussed earlier, make up a script file. Generally, a script file is one which was generated and saved as an m−file with an editor such as the MATLAB’s Editor/Debugger. A function file is a user−defined function using MATLAB. We use function files for repetitive tasks. The first line of a function file must contain the word function, followed by the output argument, the equal sign ( = ), and the input argument enclosed in parentheses. The function name and file name must be the same, but the file name must have the extension .m. For example, the function file consisting of the two lines below function y = myfunction(x) y=x.^ 3 + cos(3.* x)
is a function file and must be saved as myfunction.m For the next example, we will use the following MATLAB functions: fzero(f,x) − attempts to find a zero of a function of one variable, where f is a string containing the name of a real−valued function of a single real variable. MATLAB searches for a value near a point where the function f changes sign, and returns that value, or returns NaN if the search fails.
A−26
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Script and Function Files Important: We must remember that we use roots(p) to find the roots of polynomials only, such as those in Examples A.1 and A.2. fplot(fcn,lims) − plots the function specified by the string fcn between the x−axis limits specified by lims = [xmin xmax]. Using lims = [xmin xmax ymin ymax] also controls the y−axis limits. The string fcn must be the name of an m−file function or a string with variable x . NaN (Not−a−Number) is not a function; it is MATLAB’s response to an undefined expression such as 0 ⁄ 0 , ∞ ⁄ ∞ , or inability to produce a result as described on the next paragraph. We can avoid division by zero using the eps number, which we mentioned earlier.
Example A.16 Find the zeros, the minimum, and the maximum values of the function 1 1 f ( x ) = --------------------------------------- – --------------------------------------- – 10 2 2 ( x – 0.1 ) + 0.01 ( x – 1.2 ) + 0.04
(A.9)
in the interval – 1.5 ≤ x ≤ 1.5 Solution: We first plot this function to observe the approximate zeros, maxima, and minima using the following script. x=−1.5: 0.01: 1.5; y=1./ ((x−0.1).^ 2 + 0.01) −1./ ((x−1.2).^ 2 + 0.04) −10; plot(x,y); grid
The plot is shown in Figure A.14. 100 80 60 40 20 0 -20 -40 -1.5
-1
-0.5
0
0.5
1
1.5
Figure A.14. Plot for Example A.16 using the plot command
Introduction to Stateflow®with Applications Copyright © Orchard Publications
A−27
Appendix A Introduction to MATLAB® The roots (zeros) of this function appear to be in the neighborhood of x = – 0.2 and x = 0.3 . The maximum occurs at approximately x = 0.1 where, approximately, y max = 90 , and the minimum occurs at approximately x = 1.2 where, approximately, y min = – 34 . Next, we define and save f(x) as the funczero01.m function m−file with the following script: function y=funczero01(x) % Finding the zeros of the function shown below y=1/((x−0.1)^2+0.01)−1/((x−1.2)^2+0.04)−10;
To save this file, from the File drop menu on the Command Window, we choose New, and when the Editor Window appears, we type the script above and we save it as funczero01. MATLAB appends the extension .m to it. Now, we can use the fplot(fcn,lims) command to plot f ( x ) as follows: fplot('funczero01', [−1.5 1.5]); grid
This plot is shown in Figure A.15. As expected, this plot is identical to the plot of Figure A.14 which was obtained with the plot(x,y) command as shown in Figure A.14. 100 80 60 40 20 0 -20 -40 -1.5
-1
-0.5
0
0.5
1
1.5
Figure A.15. Plot for Example A.16 using the fplot command
We will use the fzero(f,x) function to compute the roots of f ( x ) in Equation (A.9) more precisely. The MATLAB script below will accomplish this. x1= fzero('funczero01', −0.2); x2= fzero('funczero01', 0.3); fprintf('The roots (zeros) of this function are r1= %3.4f', x1); fprintf(' and r2= %3.4f \n', x2)
A−28
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Script and Function Files MATLAB displays the following: The roots (zeros) of this function are r1= -0.1919 and r2= 0.3788 The earlier MATLAB versions included the function fmin(f,x1,x2) and with this function we could compute both a minimum of some function f ( x ) or a maximum of f ( x ) since a maximum of f ( x ) is equal to a minimum of – f ( x ) . This can be visualized by flipping the plot of a function f ( x ) upside−down. This function is no longer used in MATLAB and thus we will compute the maxima and minima from the derivative of the given function. From elementary calculus, we recall that the maxima or minima of a function y = f ( x ) can be found by setting the first derivative of a function equal to zero and solving for the independent variable x . For this example we use the diff(x) function which produces the approximate derivative of a function. Thus, we use the following MATLAB script: syms x ymin zmin; ymin=1/((x−0.1)^2+0.01)−1/((x−1.2)^2+0.04)−10;... zmin=diff(ymin)
zmin = -1/((x-1/10)^2+1/100)^2*(2*x-1/5)+1/((x-6/5)^2+1/25)^2*(2*x-12/5) When the command solve(zmin)
is executed, MATLAB displays a very long expression which when copied at the command prompt and executed, produces the following: ans = 0.6585 + 0.3437i ans = 0.6585 - 0.3437i ans = 1.2012 The real value 1.2012 above is the value of x at which the function y has its minimum value as we observe also in the plot of Figure A.15. To find the value of y corresponding to this value of x, we substitute it into f ( x ) , that is, x=1.2012; ymin=1 / ((x−0.1) ^ 2 + 0.01) −1 / ((x−1.2) ^ 2 + 0.04) −10
ymin = -34.1812 We can find the maximum value from – f ( x ) whose plot is produced with the script x=−1.5:0.01:1.5; ymax=−1./((x−0.1).^2+0.01)+1./((x−1.2).^2+0.04)+10; plot(x,ymax); grid and the plot is shown in Figure A.16. Introduction to Stateflow®with Applications Copyright © Orchard Publications
A−29
Appendix A Introduction to MATLAB® 40 20 0 -20 -40 -60 -80 -100 -1.5
-1
-0.5
0
0.5
1
1.5
Figure A.16. Plot of – f ( x ) for Example A.16
Next we compute the first derivative of – f ( x ) and we solve for x to find the value where the maximum of ymax occurs. This is accomplished with the MATLAB script below. syms x ymax zmax; ymax=−(1/((x−0.1)^2+0.01)−1/((x−1.2)^2+0.04)−10); zmax=diff(ymax)
zmax = 1/((x-1/10)^2+1/100)^2*(2*x-1/5)-1/((x-6/5)^2+1/25)^2*(2*x-12/5) solve(zmax)
When the command solve(zmax)
is executed, MATLAB displays a very long expression which when copied at the command prompt and executed, produces the following: ans = 0.6585 + 0.3437i ans = 0.6585 - 0.3437i ans = 1.2012 ans = 0.0999 From the values above we choose x = 0.0999 which is consistent with the plots of Figures A.15 and A.16. Accordingly, we execute the following script to obtain the value of ymin .
A−30
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Display Formats x=0.0999; % Using this value find the corresponding value of ymax ymax=1 / ((x−0.1) ^ 2 + 0.01) −1 / ((x−1.2) ^ 2 + 0.04) −10
ymax = 89.2000
A.11 Display Formats MATLAB displays the results on the screen in integer format without decimals if the result is an integer number, or in short floating point format with four decimals if it a fractional number. The format displayed has nothing to do with the accuracy in the computations. MATLAB performs all computations with accuracy up to 16 decimal places. The output format can changed with the format command. The available MATLAB formats can be displayed with the help format command as follows: help format FORMAT Set output format. All computations in MATLAB are done in double precision. FORMAT may be used to switch between different output display formats as follows: FORMAT FORMAT FORMAT FORMAT FORMAT FORMAT FORMAT FORMAT FORMAT
Default. Same as SHORT. SHORT Scaled fixed point format with 5 digits. LONG Scaled fixed point format with 15 digits. SHORT E Floating point format with 5 digits. LONG E Floating point format with 15 digits. SHORT G Best of fixed or floating point format with 5 digits. LONG G Best of fixed or floating point format with 15 digits. HEX Hexadecimal format. + The symbols +, - and blank are printed for positive, negative, and zero elements.Imaginary parts are ignored. FORMAT BANK Fixed format for dollars and cents. FORMAT RAT Approximation by ratio of small integers. Spacing: FORMAT COMPACT Suppress extra line-feeds. FORMAT LOOSE Puts the extra line-feeds back in. Some examples with different format displays age given below. format format format format format format
short 33.3335 Four decimal digits (default) long 33.33333333333334 16 digits short e 3.3333e+01 Four decimal digits plus exponent short g 33.333 Better of format short or format short e bank 33.33 two decimal digits + only + or - or zero are printed
Introduction to Stateflow®with Applications Copyright © Orchard Publications
A−31
Appendix A Introduction to MATLAB® format rat 100/3 rational approximation
The disp(X) command displays the array X without printing the array name. If X is a string, the text is displayed. The fprintf(format,array) command displays and prints both text and arrays. It uses specifiers to indicate where and in which format the values would be displayed and printed. Thus, if %f is used, the values will be displayed and printed in fixed decimal format, and if %e is used, the values will be displayed and printed in scientific notation format. With this command only the real part of each parameter is processed. This appendix is just an introduction to MATLAB.* This outstanding software package consists of many applications known as Toolboxes. The MATLAB Student Version contains just a few of these Toolboxes. Others can be bought directly from The MathWorks,™ Inc., as add−ons.
* For more MATLAB applications, please refer to Numerical Analysis Using MATLAB and Spreadsheets, ISBN 0−9709511−1−6.
A−32
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Appendix B Introduction to Simulink®
T
his appendix is a brief introduction to Simulink. This author feels that we can best introduce Simulink with a few examples. Some familiarity with MATLAB is essential in understanding Simulink, and for this purpose, Appendix A is included as an introduction to MATLAB.
B.1 Simulink and its Relation to MATLAB The MATLAB® and Simulink® environments are integrated into one entity, and thus we can analyze, simulate, and revise our models in either environment at any point. We invoke Simulink from within MATLAB. We will introduce Simulink with a few illustrated examples. Example B.1 For the circuit of Figure B.1, the initial conditions are i L ( 0 − ) = 0 , and v c ( 0 − ) = 0.5 V . We will compute v c ( t ) .
+ −
R
L
1Ω
1⁄4 H
i(t)
+ C
4⁄3 F
vs ( t ) = u0 ( t )
vC ( t ) −
Figure B.1. Circuit for Example B.1
For this example, dv i = i L = i C = C --------Cdt
(B.1)
and by Kirchoff’s voltage law (KVL), di Ri L + L ------L- + v C = u 0 ( t ) dt
(B.2)
Substitution of (B.1) into (B.2) yields
Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−1
Introduction to Simulink® 2
d vC dv - + vC = u0 ( t ) RC --------C- + LC ---------2 dt dt
(B.3)
Substituting the values of the circuit constants and rearranging we obtain: 2
1 d v C 4 dv C --- ----------- + --- --------- + v C = u 0 ( t ) 3 dt 2 3 dt 2
dv d vC ----------- + 4 --------C- + 3v C = 3u 0 ( t ) 2 dt dt 2 dv d vC ----------- + 4 --------C- + 3v C = 3 2 dt dt
(B.4)
t>0
(B.5)
To appreciate Simulink’s capabilities, for comparison, three different methods of obtaining the solution are presented, and the solution using Simulink follows. First Method − Assumed Solution Equation (B.5) is a second−order, non−homogeneous differential equation with constant coefficients, and thus the complete solution will consist of the sum of the forced response and the natural response. It is obvious that the solution of this equation cannot be a constant since the derivatives of a constant are zero and thus the equation is not satisfied. Also, the solution cannot contain sinusoidal functions (sine and cosine) since the derivatives of these are also sinusoids. – at
However, decaying exponentials of the form ke where k and a are constants, are possible candidates since their derivatives have the same form but alternate in sign. –s t
–s t
It can be shown* that if k 1 e 1 and k 2 e 2 where k 1 and k 2 are constants and s 1 and s 2 are the roots of the characteristic equation of the homogeneous part of the given differential equation, the natural response is the sum of the terms k 1 e be
–s1 t
and k 2 e
–s2 t
. Therefore, the total solution will
v c ( t ) = natural response + forced response = v cn ( t ) + v cf ( t ) = k 1 e
–s1 t
+ k2 e
–s2 t
+ v cf ( t )
(B.6)
The values of s 1 and s 2 are the roots of the characteristic equation
* Please refer to Circuit Analysis II with MATLAB Applications, ISBN 0−9709511−5−9, Appendix B for a thorough discussion.
B−2
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulink and its Relation to MATLAB 2
(B.7)
s + 4s + 3 = 0
Solution of (B.7) yields of s 1 = – 1 and s 2 = – 3 and with these values (B.6) is written as –t
vc ( t ) = k1 e + k2 e
–3 t
+ v cf ( t )
(B.8)
The forced component v cf ( t ) is found from (B.5), i.e., 2 dv d vC ----------- + 4 --------C- + 3v C = 3 2 dt dt
t>0
(B.9)
Since the right side of (B.9) is a constant, the forced response will also be a constant and we denote it as v Cf = k 3 . By substitution into (B.9) we obtain 0 + 0 + 3k 3 = 3
or (B.10)
v Cf = k 3 = 1
Substitution of this value into (B.8), yields the total solution as –t
v C ( t ) = v Cn ( t ) + v Cf = k 1 e + k 2 e
–3 t
+1
(B.11)
The constants k 1 and k 2 will be evaluated from the initial conditions. First, using v C ( 0 ) = 0.5 V and evaluating (B.11) at t = 0 , we obtain 0
0
v C ( 0 ) = k 1 e + k 2 e + 1 = 0.5 k 1 + k 2 = – 0.5
Also,
(B.12)
dv C dv C i i L = i C = C ---------, --------- = ---Ldt dt C
and dv --------Cdt
t=0
iL ( 0 ) 0 = ----------- = ---- = 0 C C
(B.13)
Next, we differentiate (B.11), we evaluate it at t = 0 , and equate it with (B.13). Thus, dv --------Cdt
= – k 1 – 3k 2
(B.14)
t=0
By equating the right sides of (B.13) and (B.14) we obtain Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−3
Introduction to Simulink® (B.15)
– k 1 – 3k 2 = 0
Simultaneous solution of (B.12) and (B.15), gives k 1 = – 0.75 and k 2 = 0.25 . By substitution into (B.8), we obtain the total solution as –t
v C ( t ) = ( – 0.75 e + 0.25e
–3 t
+ 1 )u 0 ( t )
(B.16)
Check with MATLAB: syms t y0=−0.75*exp(−t)+0.25*exp(−3*t)+1; y1=diff(y0)
% Define symbolic variable t % The total solution y(t), for our example, vc(t) % The first derivative of y(t)
y1 = 3/4*exp(-t)-3/4*exp(-3*t) y2=diff(y0,2)
% The second derivative of y(t)
y2 = -3/4*exp(-t)+9/4*exp(-3*t) y=y2+4*y1+3*y0
% Summation of y and its derivatives
y = 3 Thus, the solution has been verified by MATLAB. Using the expression for v C ( t ) in (B.16), we find the expression for the current as dv C 4 3 –t – 3t – t – 3t i = i L = i C = C ---------- = --- ⎛ --- e – 3 --- e ⎞ = e – e A ⎠ dt 3⎝ 4 4
(B.17)
Second Method − Using the Laplace Transformation The transformed circuit is shown in Figure B.2. R 1
Vs ( s ) = 1 ⁄ s
+
−
L
+
0.25s C 3 ⁄ 4s
I(s) 0.5 ⁄ s
VC ( s )
+ V (0) C −
−
Figure B.2. Transformed Circuit for Example B.1
B−4
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulink and its Relation to MATLAB By the voltage division* expression, 2 3 ⁄ 4s 0.5s + 2s + 31.5 - + 0.5 ------- = ------------------------------------- – 0.5 -------⎞ + 0.5 ------- = -------------------------------V C ( s ) = ---------------------------------------------- ⋅ ⎛ 1 2 ( 1 + 0.25s + 3 ⁄ 4s ) ⎝ s s s ⎠ s s(s + 1)(s + 3) s ( s + 4s + 3 )
Using partial fraction expansion,† we let 2 r2 r3 0.5s + 2s + 3- = r---1- + --------------- + ------------------------------------------------s (s + 1) (s + 3) s(s + 1 )( s + 3) 2
0.5s + 2s + 3 r 1 = ---------------------------------(s + 1)(s + 3)
= 1 s=0
2
+ 2s + 3--------------------------------r 2 = 0.5s s(s + 3)
= – 0.75 s = –1
2
0.5s + 2s + 3r 3 = --------------------------------s(s + 1)
(B.18)
= 0.25 s = –3
and by substitution into (B.18) 2
0.25 – 0.75- + --------------0.5s + 2s + 3- = 1 --- + --------------V C ( s ) = ----------------------------------s (s + 1) (s + 3) s(s + 1)(s + 3)
Taking the Inverse Laplace transform‡ we find that –t
v C ( t ) = 1 – 0.75e + 0.25e
– 3t
Third Method − Using State Variables di Ri L + L ------L- + v C = u 0 ( t ) ** dt
* For derivation of the voltage division and current division expressions, please refer to Circuit Analysis I with MATLAB Applications, ISBN 0−9709511−2−4. † Partial fraction expansion is discussed in Chapter 3, this text. ‡ For an introduction to Laplace Transform and Inverse Laplace Transform, please refer Chapters 2 and 3, this text. ** Usually, in State−Space and State Variables Analysis, u ( t ) denotes any input. For distinction, we will denote the Unit Step Function as u0 ( t ) . For a detailed discussion on State−Space and State Variables Analysis, please refer to Chapter 5, this text.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−5
Introduction to Simulink® By substitution of given values and rearranging, we obtain 1--- di ------L- = ( – 1 )i L – v C + 1 4 dt
or di ------L- = – 4i L – 4v C + 4 dt
(B.19)
Next, we define the state variables x 1 = i L and x 2 = v C . Then, di x· 1 = ------L- * dt
(B.20)
dv x· 2 = --------Cdt
(B.21)
and
Also, and thus,
dv i L = C --------Cdt dv 4 x 1 = i L = C --------C- = Cx· 2 = --- x· 2 3 dt
or 3 x· 2 = --- x 1 4
(B.22)
Therefore, from (B.19), (B.20), and (B.22), we obtain the state equations x· 1 = – 4x 1 – 4x 2 + 4 3 x· 2 = --- x 1 4
and in matrix form, x x· 1 = –4 –4 1 + 4 u0 ( t ) ·x 2 3 ⁄ 4 0 x2 0
(B.23)
Solution† of (B.23) yields
* The notation x· (x dot) is often used to denote the first derivative of the function x , that is, x· = dx ⁄ dt . † The detailed solution of (B.23) is given in Chapter 5, Example 5.10, Page 5−23, this text.
B−6
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulink and its Relation to MATLAB x1 x2
=
–t
e –e
– 3t
–t
1 – 0.75 e + 0.25e
– 3t
Then, –t
x1 = iL = e –e
– 3t
(B.24)
and –t
x 2 = v C = 1 – 0.75e + 0.25e
– 3t
(B.25)
Modeling the Differential Equation of Example B.1 with Simulink To run Simulink, we must first invoke MATLAB. Make sure that Simulink is installed in your system. In the MATLAB Command prompt, we type: simulink
Alternately, we can click on the Simulink icon shown in Figure B.3. It appears on the top bar on MATLAB’s Command prompt.
Figure B.3. The Simulink icon
Upon execution of the Simulink command, the Commonly Used Blocks appear as shown in Figure B.4. In Figure B.4, the left side is referred to as the Tree Pane and displays all Simulink libraries installed. The right side is referred to as the Contents Pane and displays the blocks that reside in the library currently selected in the Tree Pane. Let us express the differential equation of Example B.1 as 2 dv d vC ----------- = – 4 --------C- – 3v C + 3u 0 ( t ) 2 dt dt
(B.26)
A block diagram representing relation (B.26) above is shown in Figure B.5. We will use Simulink to draw a similar block diagram.*
* Henceforth, all Simulink block diagrams will be referred to as models.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−7
Introduction to Simulink®
Figure B.4. The Simulink Library Browser 2
u0 ( t )
3
Σ
d vC ----------2 dt
∫ dt
dv --------Cdt
∫ dt
vC
−4 −3 Figure B.5. Block diagram for equation (B.26)
To model the differential equation (B.26) using Simulink, we perform the following steps: 1. On the Simulink Library Browser, we click on the leftmost icon shown as a blank page on the top title bar. A new model window named untitled will appear as shown in Figure B.6.
B−8
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulink and its Relation to MATLAB
Figure B.6. The Untitled model window in Simulink.
The window of Figure B.6 is the model window where we enter our blocks to form a block diagram. We save this as model file name Equation_1_26. This is done from the File drop menu of Figure B.6 where we choose Save as and name the file as Equation_1_26. Simulink will add the extension .mdl. The new model window will now be shown as Equation_1_26, and all saved files will have this appearance. See Figure B.7.
Figure B.7. Model window for Equation_1_26.mdl file
2. With the Equation_1_26 model window and the Simulink Library Browser both visible, we click on the Sources appearing on the left side list, and on the right side we scroll down until we see the unit step function shown as Step. See Figure B.8. We select it, and we drag it into the Equation_1_26 model window which now appears as shown in Figure B.8. We save file Equation_1_26 using the File drop menu on the Equation_1_26 model window (right side of Figure B.8). 3. With reference to block diagram of Figure B.5, we observe that we need to connect an amplifier with Gain 3 to the unit step function block. The gain block in Simulink is under Commonly Used Blocks (first item under Simulink on the Simulink Library Browser). See Figure B.8. If the Equation_1_26 model window is no longer visible, it can be recalled by clicking on the white page icon on the top bar of the Simulink Library Browser. 4. We choose the gain block and we drag it to the right of the unit step function. The triangle on the right side of the unit step function block and the > symbols on the left and right sides of the gain block are connection points. We point the mouse close to the connection point of the unit step function until is shows as a cross hair, and draw a straight line to connect the two Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−9
Introduction to Simulink® blocks.* We double−click on the gain block and on the Function Block Parameters, we change the gain from 1 to 3. See Figure B.9.
Figure B.8. Dragging the unit step function into File Equation_1_26
Figure B.9. File Equation_1_26 with added Step and Gain blocks * An easy method to interconnect two Simulink blocks by clicking on the source block to select it, then hold down the Ctrl key and left−click on the destination block.
B−10
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulink and its Relation to MATLAB 5. Next, we need to add a thee−input adder. The adder block appears on the right side of the Simulink Library Browser under Math Operations. We select it, and we drag it into the Equation_1_26 model window. We double click it, and on the Function Block Parameters window which appears, we specify 3 inputs. We then connect the output of the of the gain block to the first input of the adder block as shown in Figure B.10.
Figure B.10. File Equation_1_26 with added gain block
6. From the Commonly Used Blocks of the Simulink Library Browser, we choose the Integrator block, we drag it into the Equation_1_26 model window, and we connect it to the output of the Add block. We repeat this step and to add a second Integrator block. We click on the text “Integrator” under the first integrator block, and we change it to Integrator 1. Then, we change the text “Integrator 1” under the second Integrator to “Integrator 2” as shown in Figure B.11.
Figure B.11. File Equation_1_26 with the addition of two integrators
7. To complete the block diagram, we add the Scope block which is found in the Commonly Used Blocks on the Simulink Library Browser, we click on the Gain block, and we copy and paste it twice. We flip the pasted Gain blocks by using the Flip Block command from the Format drop menu, and we label these as Gain 2 and Gain 3. Finally, we double−click on these gain blocks and on the Function Block Parameters window, we change the gains from to −4 and −3 as shown in Figure B.12.
Figure B.12. File Equation_1_26 complete block diagram
Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−11
Introduction to Simulink® dv dt
8. The initial conditions i L ( 0 − ) = C --------C-
−
t=0
= 0 , and v c ( 0 ) = 0.5 V are entered by double
clicking the Integrator blocks and entering the values 0 for the first integrator, and 0.5 for the second integrator. We also need to specify the simulation time. This is done by specifying the simulation time to be 10 seconds on the Configuration Parameters from the Simulation drop menu. We can start the simulation on Start from the Simulation drop menu or by clicking on the
icon.
9. To see the output waveform, we double click on the Scope block, and then clicking on the Autoscale
icon, we obtain the waveform shown in Figure B.13.
Figure B.13. The waveform for the function v C ( t ) for Example B.1
Another easier method to obtain and display the output v C ( t ) for Example B.1, is to use State− Space block from Continuous in the Simulink Library Browser, as shown in Figure B.14.
Figure B.14. Obtaining the function v C ( t ) for Example B.1 with the State−Space block.
B−12
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulink and its Relation to MATLAB The simout To Workspace block shown in Figure B.14 writes its input to the workspace. The data and variables created in the MATLAB Command window, reside in the MATLAB Workspace. This block writes its output to an array or structure that has the name specified by the block's Variable name parameter. This gives us the ability to delete or modify selected variables. We issue the command who to see those variables. From Equation B.23, Page B−6, x· 1 x = –4 –4 1 + 4 u0 ( t ) ·x 2 3 ⁄ 4 0 x2 0
The output equation is
y = Cx + du
or y = [0 1]
x1 x2
+ [ 0 ]u
We double−click on the State−Space block, and in the Functions Block Parameters window we enter the constants shown in Figure B.15.
Figure B.15. The Function block parameters for the State−Space block.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−13
Introduction to Simulink® The initials conditions [ x1 x2 ]' are specified in MATLAB’s Command prompt as x1=0; x2=0.5;
As before, to start the simulation we click clicking on the
icon, and to see the output wave-
form, we double click on the Scope block, and then clicking on the Autoscale obtain the waveform shown in Figure B.16.
icon, we
Figure B.16. The waveform for the function v C ( t ) for Example B.1 with the State−Space block.
The state−space block is the best choice when we need to display the output waveform of three or more variables as illustrated by the following example. Example B.2 A fourth−order network is described by the differential equation 3
2
4 d y d y dy d y --------- + a 3 --------3- + a 2 -------2- + a 1 ------ + a 0 y ( t ) = u ( t ) 4 dt dt dt dt
(B.27)
where y ( t ) is the output representing the voltage or current of the network, and u ( t ) is any input, and the initial conditions are y ( 0 ) = y' ( 0 ) = y'' ( 0 ) = y''' ( 0 ) = 0 . a. We will express (B.27) as a set of state equations
B−14
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulink and its Relation to MATLAB b. It is known that the solution of the differential equation 2
4 d y d y -------- + 2 -------2- + y ( t ) = sin t 4 dt dt
(B.28)
subject to the initial conditions y ( 0 ) = y' ( 0 ) = y'' ( 0 ) = y''' ( 0 ) = 0 , has the solution 2
y ( t ) = 0.125 [ ( 3 – t ) – 3t cos t ]
(B.29)
In our set of state equations, we will select appropriate values for the coefficients a 3, a 2, a 1, and a 0 so that the new set of the state equations will represent the differential equation of (B.28), and using Simulink, we will display the waveform of the output y ( t ) . 1. The differential equation of (B.28) is of fourth−order; therefore, we must define four state variables that will be used with the four first−order state equations. We denote the state variables as x 1, x 2, x 3 , and x 4 , and we relate them to the terms of the given differential equation as x1 = y ( t )
We observe that
2
dy x 2 = -----dt
d y x 3 = --------2 dt
3
d y x 4 = --------3 dt
x· 1 = x 2 x· 2 = x 3 x· 3 = x 4
(B.30)
(B.31)
4
d y = x· = – a x – a x – a x – a x + u ( t ) --------4 0 1 1 2 2 3 3 4 4 dt
and in matrix form x· 1 x· 2 x· 3 x· 4
0 0 = 0 –a0
1 0 0 –a1
0 1 0 –a2
0 0 1 –a3
x1
0 x2 + 0 u(t) x3 0 1 x4
(B.32)
In compact form, (B.32) is written as Also, the output is
x· = Ax + bu
(B.33)
y = Cx + du
(B.34)
where
Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−15
Introduction to Simulink®
x· =
x· 1 x· 2 x· 3 x· 4
0 0 A= 0 –a0
,
1 0 0 –a1
0 1 0 –a2
x1
0 0 , 1 –a3
x2
x=
x3 x4
,
0 b= 0, 0 1
and u = u ( t )
(B.35)
and since the output is defined as y ( t ) = x1
relation (B.34) is expressed as x1 x2
y = [1 0 0 0] ⋅
x3
+ [ 0 ]u ( t )
(B.36)
x4
2. By inspection, the differential equation of (B.27) will be reduced to the differential equation of (B.28) if we let a3 = 0
a2 = 2
a1 = 0
a0 = 1
u ( t ) = sin t
and thus the differential equation of (B.28) can be expressed in state−space form as x· 1 x· 2
0 0 = 0 –a0
x· 3 x· 4
1 0 0 0
0 1 0 –2
0 0 1 0
x1
0 + 0 sin t x3 0 1 x4 x2
(B.37)
where
x· =
x· 1 x· 2 x· 3 x· 4
,
0 0 A= 0 –a0
1 0 0 0
0 1 0 –2
0 0 , 1 0
x1 x=
x2 x3
,
x4
0 b= 0, 0 1
and u = sin t
(B.38)
Since the output is defined as y ( t ) = x1
in matrix form it is expressed as
B−16
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulink and its Relation to MATLAB x1 y = [1 0 0 0] ⋅
x2 x3
+ [ 0 ] sin t
(B.39)
x4
We invoke MATLAB, we start Simulink by clicking on the Simulink icon, on the Simulink Library Browser we click on the Create a new model (blank page icon on the left of the top bar), and we save this model as Example_1_2. On the Simulink Library Browser we select Sources, we drag the Signal Generator block on the Example_1_2 model window, we click and drag the State−Space block from the Continuous on Simulink Library Browser, and we click and drag the Scope block from the Commonly Used Blocks on the Simulink Library Browser. We also add the Display block found under Sinks on the Simulink Library Browser. We connect these four blocks and the complete block diagram is as shown in Figure B.17.
Figure B.17. Block diagram for Example B.2
We now double−click on the Signal Generator block and we enter the following in the Function Block Parameters: Wave form: sine Time (t): Use simulation time Amplitude: 1 Frequency: 2 Units: Hertz Next, we double−click on the state−space block and we enter the following parameter values in the Function Block Parameters: A: [0 1 0 0; 0 0 1 0; 0 0 0 1; −a0 −a1 −a2 −a3] B: [0 0 0 1]’ C: [1 0 0 0] D: [0]
Initial conditions: x0 Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−17
Introduction to Simulink® Absolute tolerance: auto Now, we switch to the MATLAB Command prompt and we type the following: >> a0=1; a1=0; a2=2; a3=0; x0=[0 0 0 0]’; We change the Simulation Stop time to 25 , and we start the simulation by clicking on the icon. To see the output waveform, we double click on the Scope block, then clicking on the Autoscale
icon, we obtain the waveform shown in Figure B.18.
Figure B.18. Waveform for Example B.2
The Display block in Figure B.17 shows the value at the end of the simulation stop time. Examples B.1 and B.2 have clearly illustrated that the State−Space is indeed a powerful block. We could have obtained the solution of Example B.2 using four Integrator blocks by this approach would have been more time consuming. Example B.3 Using Algebraic Constraint blocks found in the Math Operations library, Display blocks found in the Sinks library, and Gain blocks found in the Commonly Used Blocks library, we will create a model that will produce the simultaneous solution of three equations with three unknowns. The model will display the values for the unknowns z 1 , z 2 , and z 3 in the system of the equations a1 z1 + a2 z2 + a3 z3 + k1 = 0 a4 z1 + a5 z2 + a6 z3 + k2 = 0
(B.40)
a7 z1 + a8 z2 + a9 z3 + k3 = 0
B−18
Introduction to Stateflow®with Applications Copyright © Orchard Publications
Simulink and its Relation to MATLAB The model is shown in Figure B.19.
Figure B.19. Model for Example B.3
Next, we go to MATLAB’s Command prompt and we enter the following values: a1=2; a2=−3; a3=−1; a4=1; a5=5; a6=4; a7=−6; a8=1; a9=2;... k1=−8; k2=−7; k3=5;
After clicking on the simulation icon, we observe the values of the unknowns as z 1 = 2 , z 2 = – 3 , and z 3 = 5 .These values are shown in the Display blocks of Figure B.19.
The Algebraic Constraint block constrains the input signal f ( z ) to zero and outputs an algebraic state z . The block outputs the value necessary to produce a zero at the input. The output must affect the input through some feedback path. This enables us to specify algebraic equations for index 1 differential/algebraic systems (DAEs). By default, the Initial guess parameter is zero. We can improve the efficiency of the algebraic loop solver by providing an Initial guess for the algebraic state z that is close to the solution value.
Introduction to Stateflow®with Applications Copyright © Orchard Publications
B−19
Introduction to Simulink® An outstanding feature in Simulink is the representation of a large model consisting of many blocks and lines, to be shown as a single Subsystem block.* For instance, we can group all blocks and lines in the model of Figure B.19 except the display blocks, we choose Create Subsystem from the Edit menu, and this model will be shown as in Figure B.20† where in MATLAB’s Command prompt we have entered: a1=5; a2=−1; a3=4; a4=11; a5=6; a6=9; a7=−8; a8=4; a9=15;... k1=14; k2=−6; k3=9;
Figure B.20. The model of Figure B.19 represented as a subsystem
The Display blocks in Figure B.20 show the values of z 1 , z 2 , and z 3 for the values specified in MATLAB’s Command prompt.
B.2 Simulink Demos At this time, the reader with no prior knowledge of Simulink, should be ready to learn Simulink’s additional capabilities. It is highly recommended that the reader becomes familiar with the block libraries found in the Simulink Library Browser. Then, the reader can follow the steps delineated in The MathWorks Simulink User’s Manual to run the Demo Models beginning with the thermo model. This model can be seen by typing thermo
in the MATLAB Command prompt.
* The Subsystem block is described in detail in Chapter 2, Section 2.1, Page 2−2, Introduction to Simulink with Engineering Applications, ISBN 0−9744239−7−1. † The contents of the Subsystem block are not lost. We can double−click on the Subsystem block to see its contents. The Subsystem block replaces the inputs and outputs of the model with Inport and Outport blocks. These blocks are described in Section 2.1, Chapter 2, Page 2−2, Introduction to Simulink with Engineering Applications, ISBN 0−9744239−7−1.
B−20
Introduction to Stateflow®with Applications Copyright © Orchard Publications
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
Appendix C Masked Subsystems Mask Parameter Dialog Box − The mask parameter dialog box contains controls that enable a user to set the values of the mask's parameters and hence the values of any internal parameters linked to the mask parameters. The mask parameter dialog box replaces the subsystem's standard parameter dialog box, i.e., clicking on the masked subsystem's icon causes the mask dialog box to appear instead of the standard parameter dialog box for a Subsystem block Mask Initialization Code − The initialization code is MATLAB code that you specify and that Simulink runs to initialize the masked subsystem at critical times, such as model loading and the start of a simulation run (see Initialization Pane). You can use the initialization code to set the initial values of the masked subsystem's mask parameters. Mask Workspace − Simulink associates a workspace with each masked subsystem that you create. Simulink stores the current values of the subsystem's parameters in the workspace as well as any variables created by the block's initialization code and parameter callbacks. You can use model and mask workspace variables to initialize a masked subsystem and to set the values of blocks inside the masked subsystem, subject to the following rules. A block parameter expression can refer only to variables defined in the mask workspaces of the subsystem or nested subsystems that contain the block or in the model's workspace. A valid reference to a variable defined on more than one level in the model hierarchy resolves to the most local definition. For example, let us suppose that model M contains masked subsystem A, which contains masked subsystem B. Also, let us suppose that B refers to a variable x that exists in both A's and M's workspaces. In this case, the reference resolves to the value in A's workspace. A masked subsystem's initialization code can refer only to variables in its local workspace. The mask workspace of a Model block is not visible to the model that it references. Any variables used by the referenced model must resolve to workspaces defined in the referenced model or to the base (i.e., the MATLAB) workspace.
C.4 Creating a Masked Subsystem It is best to illustrate the creation of a masked subsystem with an example. Example C.1 2
The Simulink model in Figure C.1 below implements the quadratic equation y = ax + bx + c .
C−2
Introduction to Stateflow® with Applications Copyright © Orchard Publications
Creating a Masked Subsystem
Figure C.1. Simulink model for Example C.1
To create a subsystem, we encircle all blocks except the Unknown x and Display blocks, and from the Edit drop menu we select Create Subsystem. The model now appears as shown in Figure C.2.
Figure C.2. The model for Example C.1 shown as a subsystem block
To see the contents of the Subsystem in Figure C.2, we double−click the Subsystem block and now the model appears as shown in Figure C.3.
Introduction to Stateflow® with Applications Copyright © Orchard Publications
C−3
Appendix C Masked Subsystems
Figure C.3. The contents of the subsystem block
From the Edit drop menu we click on the Mask Subsystem and the Mask Editor window appears as shown in Figure C.4. With the Icon tab selected as shown in Figure C.4, we position the text cursor in the Drawing commands pane, and we enter the MATLAB command image(imread(‘quadratic.jpg’));, we press Enter, and we click OK. It is assumed that this image was previously created and saved in MATLAB’s saved files path. The Mask Editor now appears as shown in Figure C.5.
C−4
Introduction to Stateflow® with Applications Copyright © Orchard Publications
Creating a Masked Subsystem
Figure C.4. The Mask Editor window for Example c.1
Figure C.5. The masked subsystem with an imported image
Introduction to Stateflow® with Applications Copyright © Orchard Publications
C−5
Appendix C Masked Subsystems We right−click on the Subsystem block in Figure C.5, and from the drop menu we select Edit Mask. From the Mask Editor window which appears, we select the Parameters tab shown in Figure C.6 below.
Figure C.6. The Parameters tab for the Mask Editor window
We select the Add
C−6
tool and the Mask Editor window now appears as shown in Figure C.7.
Introduction to Stateflow® with Applications Copyright © Orchard Publications
Creating a Masked Subsystem
Figure C.7. The Mask Editor window for specifying the attributes of the masked parameters
The Mask Editor in Figure C.7 is used to specify the attributes of the masked parameters. The Prompt column under Dialog parameters is used as a text label to describe the parameter. For our example we enter Constant a, Constant b, and Constant c. The Variable column is used to enter the names of the variables that store the parameter values. For this example we enter a, b, and c as shown in Figure C.8.
Introduction to Stateflow® with Applications Copyright © Orchard Publications
C−7
Appendix C Masked Subsystems
Figure C.8. The Masked Editor with the equation constants specified
We right−click on the masked subsystem block shown in Figure C.5, Page C−5, and in the Function Block Parameters dialog box we enter the values 1, −5, and 6 for the variables a, b, and c respectively, as shown in Figure C.9.
C−8
Introduction to Stateflow® with Applications Copyright © 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 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
Appendix C Masked Subsystems
Figure C.11. The Initialization tab for the Mask Editor Window
Figure C.12. The Documentation tab for the Mask Editor window.
C−10
Introduction to Stateflow® with Applications Copyright © Orchard Publications
References and Suggestions for Further Study A. The following publications by The MathWorks, are highly recommended for further study. They are available from The MathWorks, 3 Apple Hill Drive, Natick, MA, 01760, www.mathworks.com. 1. Getting Started with MATLAB® 2. Using MATLAB® 3. Using MATLAB® Graphics 4. Using Simulink® 5. Sim Power Systems for Use with Simulink® 6. Fixed−Point Toolbox 7. Simulink® Fixed−Point 8. Real−Time Workshop 9. Signal Processing Toolbox 10. Getting Started with Signal Processing Blockset 10. Signal Processing Blockset 11. Control System Toolbox 12. Stateflow® B. Other references indicated in text pages and footnotes throughout this text, are listed below. 1. Mathematics for Business, Science, and Technology, ISBN 0−9709511−0−8 2. Numerical Analysis Using MATLAB® and Spreadsheets, ISBN 0−9709511−1−6 3. Circuit Analysis I with MATLAB® Applications, ISBN 0−9709511−2−4 4. Circuit Analysis II with MATLAB® Applications, ISBN 0−9709511−5−9 5. Signals and Systems with MATLAB Computing and Simulink Modeling, ISBN 0-9744239-9-8 6. Electronic Devices and Amplifier Circuits with MATLAB® Applications, ISBN 0−9709511−7−5 7. Digital Circuit Analysis and Design with Simulink Modeling and Introduction to CPLDs and FPGAs, ISBN 978-1-934404-05-8 Introduction to Stateflow®with Applications Copyright © Orchard Publications
R−1
8. Introduction to Simulink® with Engineering Applications, ISBN 0−9744239−7−1 9. Reference Data for Radio Engineers, ISBN 0−672−21218−8, Howard W. Sams & Co. 10.Electronic Engineers’ Handbook, ISBN 0−07−020981−2, McGraw−Hill 11. Network Analysis and Synthesis, L. Weinberg, McGraw−Hill 12. Elecrronic Filter Design Handbook, Williams and Taylor, McGraw−Hill
R−2
Introduction to Stateflow®with Applications Copyright © Orchard Publications
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