Home
Stateflow User's Guide
Contents
1. 2 eee 2 4 SOOM BaS ssrssrsrrka alee Gcuade RE AEE EEEE RE hag 4 Maa eg 2 4 Stateflow Diagram Stateflow Block Name 05 2 4 Modified Flag 0 0 00 cece eee 2 5 Menu Bar cece ete 2 5 Toolbar 0 ccc eee eee eee 2 6 Productivity BoostS 0 0c cece te eas 2 7 Virtual Scrollbar 2 0 cee 2 7 Contents Shortcut Menus 0 0 cee eee 2 10 OVERVIEW cio sk oii Bh eds Bi A ee eis 2 10 Menu Options Available on All Shortcut Menus 2 10 General Shortcut Menu 0 0002 c eee ee 2 12 State Shortcut Menu 0 0 cee ee 2 13 Transition Shortcut Menu 0 00 0 eee 2 14 J unction Shortcut Menu 0 0 ees 2 14 Using the Graphics Editor 05 2 15 Object Button Modes cece ee eens 2 15 Canceling OperationS 00 0 cee ee 2 15 Selecting and Deselecting ObjectS 00000 0s 2 15 Cutting and Pasting Objects 0 cece ee 2 16 Copying Obes 5s ene wes daw cea eee Re Bho ow ets 2 16 Working with Charts Stateflow Diagrams 2 18 OVERVICW eea anhe baw mace wie Saad eal Paw ale Aa oe bd 2 18 What Can You Do with Charts 00000000 2 18 Editing Chart Stateflow Diagram Properties 2 19 Chart Hyperlinks Example 0 00 cece eee eee 2 21 Chart Update Methods cece eee eee 2 22 Printing Large Stateflow Diagrams 20005 2 23 Working with St
2. 10 18 What is a Conflicting Transition 00 10 18 xviii Contents Detecting Conflicting Transitions 4 10 18 Example Conflicting Transition 000005 10 18 Debugging Data Range Violations 10 20 What is a Data Range Violation 2 055 10 20 Detecting Data Range Violations 20055 10 20 Example Data Range Violation 2 000 10 20 Debugging Cyclic Behavior 005 10 21 What is Cyclic Behavior 0 0 0 cee ee 10 21 Detecting Cyclic Behavior 000 c eee ee 10 21 Example CyclicBehavior 0 00 e eee eee 10 22 Example Flow Cyclic Behavior Not Detected 10 23 Example Noncyclic Behavior Flagged as a Cyde 10 24 Reference SEW oe i a ae Ove st cee ee Ne se ae oe ee E Y 11 3 SEXIE co coer a bene deh ae doa eo eee ld eet eee 26 Pe Paes 11 4 SISAVE eee 11 5 Statehlow wisaseesiee rae Oe Gee week we ade weeds Meee EES 11 6 STOICA a5 Se castes ea ho ose ese ena oe xa gine eee eee la nal aAA 11 9 SHAD 22 i oricare ara a eeemad be bee boa E a eee owe wes 11 10 Glossary xix XX Contents Before You Begin Related Products and Documentation Requirements How to Use This Guide Chapter Quick Reference Typographical Conventions Installation Xxii XX Xxvi Xxvi XXxvii XXV Before You Begin R
3. D data attribute properties initial value 3 34 maximum value 3 34 minimum value 3 34 type 3 34 units 3 33 constant 3 31 definition 1 15 description property 3 24 exported 4 28 exported to an external code source 3 31 getting started 3 23 getting started example 5 16 glossary definition A 4 imported 4 29 imported from an external code source 3 31 input from Simulink 3 27 local 3 27 name property 3 24 output to Simulink 3 28 parent property 3 25 port property 3 32 properties 3 23 properties dialog box 5 12 apply button 5 15 close button 5 15 description field 5 14 document link field 5 14 initial value 5 14 maximum field 5 14 minimum field 5 14 name field 5 12 parent field 5 12 port field 5 13 revert button 5 15 scope field 5 12 type field 5 14 units field 5 12 scope property 3 27 temporary 3 29 what is a data object 3 22 workspace 3 30 data attributes 3 33 data dictionary definition 6 4 glossary definition A 4 data input from Simulink add and choose a parent task 4 18 apply and save task 4 19 choose scope task 4 18 specify data attributes task 4 19 tasks 4 18 data output to Simulink add and choose a parent task 4 22 apply and save task 4 23 choose scope task 4 22 specify data attributes task 4 23 tasks 4 22 data range violation 10 20 data scope and parent combinations 3 32 1 3 Index data hierarchy and scope 3 26 Debugger action control buttons 10 9 active states display 10 11 animation contr
4. 7 Semantics Transitions to and from Exclusive OR States Example Processing of One Event This example shows the semantics of a simple transition focusing on the implications of states being active or inactive On State On is active entry entOn E one E one during durOn exit exitOn Off entry entOffg during durOffQ exit exitOff Initially the Stateflow diagram is asleep StateOn and state Of f are OR states State 0n is active Event E_ one occurs and awakens the Stateflow diagram Event _ one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_ one A valid transition from state 0n to state Of f is detected 2 State On exit actions execute and complete Exit On 3 State On is marked inactive 4 Theevent E_one is broadcast as the transition action The second generation of event E_one is processed but because neither state is active it has no effect Had a valid transition been possible as a result of the broadcast of 7 8 Transitions to and from Exclusive O R States E_one the processing of the first broadcast of E_ one would be preempted by the second broadcast of E_one 5 State Off is marked active 6 StateOff entry actions execute and complete ent Of f 7 TheStateflow diagram goes back tosleep waiting to be awakened
5. Click on the Apply button to save the changes Click on the Revert button to cancel any changes and return to the previous settings Click on the Close button to save the changes and close the dialog box Click on the Help button to display the Stateflow online help in an HTML browser window 2 41 2 Using the Graphics Editor Main Editor Menus Overview The menu choices provide the ability to operate on the graphical Stateflow diagram objects and perform operations on the Stateflow diagram itself The menu bar consists of these menus e File e Edit see Edit Menu on page 2 45 Simulation see Simulation Menu on page 2 45 e Style see Style Menu on page 2 46 e Tools see Tools Menu on page 2 47 Add see Add Menu on page 2 48 e Help see Help Menu on page 2 49 2 42 M ain Editor M enus File Menu The File menu provides these options Menu Choice Description New Model Ctrl N Open Model Ctrl O Save Model Ctrl S Save Model As Close Ctrl W Close All Charts Print Ctrl P Print As Printer Setup Exit MATLAB Ctrl Q Creates and displays a new untitled Simulink model and an untitled Stateflow block Displays a navigational file manager dialog box you use to choose the Simulink model to open Saves the current Simulink model and any Stateflow blocks within the model Displays a navigational dialog box for you t
6. Finder Display Area The Finder display area looks like this EJ Stateflow Finder fuelsys ol x String Criteria Search Method Look for OF Normal Wildcard regular expression elas Look in Any Fl C Exact Word match a Object Type Refine W States Transitions Junctions W Events V Data Targets Clear Matches Search History All objects with O Help Type Label Chart Parent Source Destination Oxygen Sensor Mode logic State O OZ fail Dentry o28 logic Oxygen_ Sensor Mode State O O02 normal Oentry o logic Oxygen_Sensor Mode State O O02 warmup Dentry o logic Oxygen_Sensor Mode State O Overspeed logic g_Mode Fuel_Disabled J The display area is divided into these fields Field Description Type The object type is listed in this field States with exclusive OR decomposition are followed by an O States with parallel AND decomposition are followed by A Label The string label of the object is listed in this field Chart The title of the Stateflow diagram Stateflow block is listed in this field Parent This object s parent in the hierarchy Source Source object of a transition Destination Destination object of a transition All fields are truncated to maintain column widths The Parent Source and Destination fields are truncated from the left so that the name at the end of 5 23 5 Exploring and Searching 5 24 the hierarchy is readable The entire fie
7. If the external source is another machine most common scenario then one machine defines an Exported data object and the other machine defines the same data object to be Imported Stateflow generates the appropriate export and import data code for both machines See Exported Data on page 4 28 for an example showing the imported data format required if an external code source is used Imported An Imported data object is defined external to the machine the parent is consequently external to the machine Importing a data object provides access to the data object It is the responsibility of the external source to make the Imported data available in the manner appropriate to the source to make use of these rights If the external source is another machine most common scenario then one machine defines an Imported data object and the other machine defines the same data object to be Exported Stateflow generates the appropriate import and export data code for both machines See Imported Data on page 4 29 for an example showing the exported data format required if an external code source is used 3 31 3 Events and Data Table of Data Scope and Parent Combinations This table summarizes who can access the data Offspring is defined as all substates of a parent Scope Can be Parented Access Rights by Local machine chart Parent and any of its offspring state Input from chart Simulink and any offspring of t
8. If the external source is another machine most common scenario then one machine defines as Imported event and the other machine defines the same event to be Exported Stateflow generates the appropriate import and export event code for both machines See Imported Events on page 4 27 for an example showing the exported event format required in the external code source Events Table of Event Parent and Scope Combinations This table summarizes the answers to these access questions e Who can broadcast the event has send rights e Who can trigger on the event has receive rights Offspring is defined as all substates of a parent Scope Can be Send Rights Receive Rights Parented by Local machine Any offspring of the Parent and any chart state machine offspring Input chart Simulink model and Chart and all its from any offspring of the offspring Simulink chart Output chart Simulink model and Simulink model to any offspring of the Simulink chart Exported machine Any offspring of the Any offspring of machine and the machine external sources Imported machine Any offspring of the External tothe machine machine The Scope determines send rights The parent primarily determines receive rights Events are broadcast in a top down manner starting from the event s parent in the hierarchy Thes end action language function allows refinement of the receive rights associated with the specified event The send action lan
9. You can define parents for events and data Being able to define parents hierarchy and scope provides simulation and prototyping flexibility and efficient generated code Most important of the benefits is the ability to optimize event processing through directed event broadcasting Directed event broadcasting is the ability to qualify who can send and receive event broadcasts The ability to scope data using hierarchy is also of significant importance By choosing a parent and scope you can specify where the data resides and qualify who can access it O verview This figure shows the objects in the Stateflow machine hierarchy that can parent events and data Stateflow data dictionary machine Events and data have hierarchy and can be parented by a machine a chart or a state Through the Explorer and the Event and Data properties dialog boxes you can specify variations of parent and scope 3 Events and Data 3 4 Where to Find More Information on Creating Modifying and Deleting Events and Data For information on creating modifying and deleting event and data objects see these sections Stateflow E xplorer User Interface on page 5 5 Example Getting Started Adding Events and Data on page 5 16 and Stateflow Finder User Interface on page 5 20 For information on data and events relevant to defining Stateflow interfaces see Chapter 4 Defining Stateflow Interfaces Events
10. matlab MATLAB_workspace_data ml Action specifies a call using themi name space notation U se of these keywords in any way other than their intended meaning within the rules of the notation will cause unpredictable results How Is Hierarchy Represented The notation supports the representation of object hierarchy in Stateflow diagrams Some of the objects are graphical while others are nongraphical An example of a graphical hierarchy is the ability to draw one state within the boundaries of another state Such a representation indicates that the inner state is a substate or child of the outer state or superstate The outer state is the parent of the inner state In the simple case of a Stateflow diagram with a single state the Stateflow diagram is that state s parent Transitions are another example of graphical hierarchy A transition s hierarchy is represented O verview by determining its parent source and destination In a Stateflow diagram you can see a transition s parent source and destination Data and event object are nongraphical and their hierarchy is represented differently using the Explorer from the graphical object hierarchy using the graphics editor All of the objects in the notation support the representation of hierarchy See Chapter 3 Events and Data and Chapter 4 Defining Stateflow Interfaces for information and examples of representing data and event objects For more
11. 20 cece eee eae 6 42 Objects with ActionS 0 c eee 6 42 Transition Action Notation 0000 cee eee eee 6 43 State Action Notation 0 2 0 0 cece ee 6 43 Action Language Components 0 0 eee eee eae 6 44 Bit Operations ays nerina an E e EE o a e n e 6 44 Binary Operations aeua aae 6 45 Uinary Operations ic ica 4 ees neva eos Sa cca Pee 6 47 Unary ACtiONS 1 2 2 cee 6 48 Assignment Operations 00 0 cece ee 6 48 User Written Functions 0 0 02 00 cece ee 6 49 Mmi FUNCEIONS gt i it eee hin ae ed ce a Ried dele 6 50 ml Name Space Operator 0 00 cee eee 6 53 Choosing Between the ml function and the ml Name Space Operator 0 eee ee 6 55 Data and Event Arguments 0 0 e eee eee 6 56 ATCAYS ri E AE OE AS OR E a 6 56 Event Broadcasting 00 ce eee eee eee 6 56 Directed Event Broadcasting s s sasae 6 58 Example Directed Event Broadcast Using send 6 59 xii Contents Example Directed Event Broadcast Using Qualified Event Names 0 0 cee eee eee eee 6 60 Conditions 0 0 eee eee eee eee eens 6 61 Time Symbol 0 0 6 0 eae 6 61 IRCEAIS jannik ac cittven edi way naa at wan eek tee oes aust en 6 62 Continuation Symbols 0 0 00 cece eee 6 62 Comments 0 ccc ee eee eee teens 6 62 Use of the Semicolon 000 cece eee 6 62 Semantics Overview 256565666 ke i eh ee eee Rees 7
12. 5 22 Search Button Click on the Search button toinitiatethe search operation Thedata dictionary is queried and the results are listed in the display area Matches The Matches field displays the number of objects that match the specified search criteria Refine Button After the results of a search are displayed enter additional search criteria and click on the Refine button to narrow the previously entered search criteria An ampersand amp is prepended to the search criteria in the Search History field to indicate a logical AND with any previously specified search criteria Search History The Search History text box displays the current search criteria Click on the pull down list to display search refinements An ampersand is prepended tothe search criteria to indicate a logical AND with any previously specified search criteria You can undo a previously specified search refinement by selecting a previous entry in the search history By changing the Search History selection you force the Finder to use the specified criteria as the current most refined search output Clear Button Click the Clear button to clear any previously specified search criteria Results are removed and the search criteria is reset to the default settings Close Button Click the Close button to close the Finder Help Button Click the Help button to display theStateflow online help in an HTML browser window Stateflow Finder User Interface
13. 6 24 Transitions the event that has occurred In another situation you may want to have specific actions take place that are dependent upon the destination of the transition Example Use of Default Transitions This example shows a use of default transitions When the Stateflow diagram is first awakened the default transition to superstates defines that of states 5 and 8 the transition to states is valid States has twosubstates A and D Which substate does the system transfer to It cannot transfer to both of them sinceA and D are not parallel AND states Again this kind of ambiguity is cleared up by defining a default transition to substate D Suppose at a different execution point the Stateflow diagram is awakened by the occurrence of event d and stateB is active The transition BS is valid When the system enters states it enters substate D because the default transition is defined See the section titled Default Transitions on page 7 18 for more information on the semantics of this notation The default transitions are required for the Stateflow diagram to execute Without the default transition to state S when the Stateflow diagram is awakened none of the states become active You can detect this situation at runtime by checking for state inconsistencies See Dynamic Checker Options on page 10 10 for more information 6 25 6 N otations Example Default Transition to a J unction This
14. When you define a data object to be an Output to Simulink a Simulink output port is added to the Stateflow block Output data objects from the Stateflow block to the Simulink model are scalar Data O utputs to Simulink Specify Data Attributes If you want to change the defaults you can specify data Units Type Initial Minimum and Maximum values Apply the Changes Click on the Apply button to save the properties Click on the Close button to save the properties and close the dialog box 4 23 4 Defining Stateflow Interfaces 4 24 MATLAB Workspace What Is the MATLAB Workspace The MATLAB workspace is the area of memory accessible from the MATLAB command line The workspace maintains the set of variables built up during a MATLAB session See Getting Started with MATLAB and Using MATLAB for more information Using the MATLAB Workspace You can define data objects to have a Workspace Scope Any data objects defined with Workspace Scope must have value assigned in the MATLAB command window prior to starting a simulation Two commands who and whos show thecurrent contents of the workspace The who command gives a short list whilewhos also gives size and storage information To delete all the existing variables from the workspace enter cl ear at the MATLAB command line Using the Workspace data Scope is only meaningful for sf un simulation and RTW targets Defining the Interface to External Sources
15. 6 30 Transitions See the section titled Example Inner Transition to a History J unction on page 7 31 for more information on the semantics of this notation What Is a Self Loop Transition A transition segment from a statetoa connectivejunction that has an outgoing transition segment from the connectivejunction back toitself is a self loop This is an example of a self loop See these sections for examples of self loops e Example Connective unction Special Case Self Loop on page 6 34 See the section titled Example Self Loop on page 7 34 for information on the semantics of this notation e Example Connective unction and For Loops on page 6 35 See the section titled Example For Loop Construct on page 7 35 for infor mation on the semantics of this notation 6 31 6 Notations 6 32 Connective J unctions What Is a Connective J unction A connective junction is used to represent a decision point in the Stateflow diagram The connectivejunction enables representation of different transition paths Connective junctions are used to help represent Variations of ani f t hen el se decision construct by specifying conditions on some or all of the outgoing transitions from the connective junction A self loop back to the source state if none of the outgoing transitions is valid Variations of af or loop construct by having a self loop transition from the connective junction b
16. Event only That event occurs Event and condition That event occurs and the condition is true Condition only Any event occurs and the condition is true Action only Any event occurs Not specified Any event occurs Types of Transitions The notation supports these transition types Transitions to and from exclusive OR states See the sections titled Example Transitions to and from Exclusive OR States on page 6 21 for an example of this type of transition Transitions to and from junctions See the section titled Example Transitions to and from J unctions on page 6 21 for an example of this type of transition Transitions to and from exclusive OR superstates See the section titled Example Transitions to and from Exclusive OR Superstates on page 6 22 for an example of this type of transition Transitions from no source to an exclusive OR state default transitions See the section titled What is a Default Transition on page 6 24 for exam ples of this type of transition Inner state transitions See the section titled What Is an Inner Transition on page 6 27 for exam ples of this type of transition Self loop transitions See the section titled What Is a Self Loop Transition on page 6 31 for examples of this type of transition 6 20 Transitions Example Transitions to and from Exclusive OR States This example shows simple transitions to and from exclusive OR s
17. Power_off Power_on port c rrr rrr reece eee A o aioe aa z Timer s f Ride sot 1 I 1 j i i i 1 On l G eae Bii i i Stopped oe ae i i i l 1 a ee ET 1 t 1 a a 1 t Tr a aie a a a yo i i i Counting l 1 I Create and Label the AND States 1 Double click on the State button B in the toolbar The button appears depressed and is now in multiple object mode U sing the sample solution Stateflow diagram as a guide click in the drawing area to place the Audi o and Vi deo states in the drawing area The states are created as AND states since the decomposition of Ri de is already set Press the Escape key or click on the State button to toggle the button out of multiple object mode Click on the character within each state to enter each state label Use the sample solution to label the states based on their placement in the drawing area Deselect the state press the Escape key to exit the edit Sample Snapshot Your Stateflow diagram should look similar to this Stateflow diagram Procedure Power_on m S EEEE EE Timer Ride eee Stopped i On j amenasm ee i Stopped 1 i Bae a S ee DEEE Countin ne Video bf j i Create the Transitions These steps show how to create the transitions 1 Start with thetransitions within theRi de superstate U sing the solution as a guide place the cursor at a straight portion of the side border of the Power_on Rid
18. exit exitA C entry entC during durCQ exit exitC Initially the Stateflow diagram is asleep State A is active Event E_t wo occurs and awakens the Stateflow diagram Event E_t wo is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_t wo Thereis a valid transition segment from state A to the connective junction Given that the transition segments are equivalently labeled evaluation begins from a twelve o clock position on the connective junction and progresses clockwise The first transition segment labeled with event E_one is not valid The next transition segment labeled with event E_two is valid The complete transition from state A to state C is valid 2 Statea executes and completes exit actions exit A 3 Stated is marked inactive 4 Statec is marked active 5 Statec executes and completesentry actions ent C 6 TheStateflow diagram goes back tosleep waiting to be awakened by another event 7 39 7 Semantics 7 40 This sequence completes the execution of this Stateflow diagram associated with event E_t wo Example Transitions from Multiple Sources to a Common Destination This example shows the semantics of transitions from multiple sources to a single destination State A is active entry entA during durA exit exitAG Ci entry en
19. ml x ml a d1 d2 ml y These data objects are defined in the Stateflow diagram e d1 and d2 are Local data objects e a x andy must be defined in the MATLAB workspace prior to starting the simulation otherwise a runtime error is generated at the execution time of the transition The values of a andy are accessed in the MATLAB workspace and used in the expression with the Local data objects d1 and d2 The result of the expression is assigned to the MATLAB workspace variablex If x does not exist it is automatically created in the MATLAB workspace Example Using the ml Operator to Access MATLAB Functions This is an example of using the ml operator to access MATLAB functions ml v 5 6 7 ml my_func ml x 1 3 ml y 3 ml z d1 d2 string 6 54 Action Language These data objects are defined e di and d2 are Local data objects defined in the Stateflow diagram e x is assumed to be a two dimensional array in the MATLAB workspace e y is assumed to bea MATLAB workspace vector e z is assumed to be a MATLAB workspace scalar variable x y andz must be defined in the MATLAB workspace prior to starting the simulation otherwise a runtime error is generated at the execution time of the transition A MATLAB function named my_f unc is called with these arguments 1 x 1 3 2 y 3 32 4 dl 5 d2 6 string abcdefgh The result of my_func if it isa scalar is assigned to element 5 6 7 of a multi dimensi
20. on page 6 42 for more information Connective J unction Connectivejunctions are decision points in the system A connective junction is a graphical object that simplifies Stateflow diagram representations and facilitates generation of efficient code Connectivejunctions providealternative ways to represent desired system behavior A 3 G lossary This example shows how connective junctions displayed as small circles are used to represent the flow of ani f code structure if cl c1 at a if c2 a2 else if c3 a3 c2 a2 c3 a3 i Name Button Icon Description Connective One use of a Connective junction is to junction handle situations where transitions out of one state into two or more states are taken based on the same event but guarded by different condi tions See the section titled Connective J unctions on page 6 32 for more information Data Data objects store numerical values for reference in the Stateflow diagram See Data on page 3 22 for more information on representing data objects Data Dictionary The data dictionary is a database where Stateflow diagram information is stored When you create Stateflow diagram objects the information about those objects is stored in the data dictionary once you save the Stateflow diagram Debugger See Stateflow Debugger Decomposition A state has a decomposition when it consists of one or more substates A S
21. 11 The Stateflow diagram goes back to sleep waiting to be awakened by another event Parallel AN D States This sequence completes the execution of this Stateflow diagram associated with event E_one andtheon event broadcast toa parallel state of event E_two The final Stateflow diagram activity looks like this State Alb is active s entry entA during durAg exit exitAG entry entAi during durA1 on E_one E_two exit exitA1 Ala entry entA lat during dura 1a exit exitA1a entry entA1b during durAib exit exitA 1b 11 entry entA2 11 during durA2 1 exit exitA2 A2al entry entA2a during durA2a exit exitA2a A2b State A2b entry entA2b during durA2b exit exitA2b is active 7 49 7 Semantics 7 50 Example Event Broadcast Transition Action Nested Event Broadcast This example shows the semantics of an event broadcast transition action that includes nested event broadcasts State Ala is active Al entry entA during durA exit exitAQ entry entA1 during dura 1 exit exitA 1 1 entry entAla during durA tat exit exitA1a E_one E_two 1 Atb i entry entATbt 1 during durA1b i exit exitA1b entry entA2 11 during durA2 exit exitA2 State A2a entry entA2a is active during durA2a exit exitA2a A2b entry e
22. 3 StateA checks itself for valid transitions and detects there is a valid inner transition to a connective junction The conditions are evaluated to deter mineif one of thetransitions is valid The segments labeled with a condition are evaluated before the unlabeled segment The evaluation starts froma twelve o clock position on thejunction and progresses in a clockwise manner Inner Transitions Since C_t wo is true the inner transition to the junction and then to state A A2 is valid 4 StateA Al exit actions execute and complete exit A1 5 StatedA Al is marked inactive 6 StateA A2 is marked active 7 StateA A2 entry actions execute and complete ent A2 8 TheStateflow diagram goes back tosleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one when condition C_t wo is true Example Processing a Second Event with an Inner Transition to a Connective J unction This example shows the semantics of an inner transition to a junction when a second event E_ one occurs A entry entA during durAQ exit exitAG Al entry entA1 A2 AQ during dura 10 entry entA2 entry entA3 exit exitA1 during durA2 during durA3 l exit extA2 exit extA3 State A2 is active 7 29 7 Semantics 7 30 Initially the Stateflow diagram is asleep Stated is active Event _one occurs and awakens the Stateflow
23. 7 58 Example Directed Event Broadcast Using send This example shows the semantics of directed event broadcast using send event name state name in atransition action State Al is active data1 1 send E_one B entry entA1 exit exitA1 A2 entry entA2 exit exitA2 State B1 is active entryentB1 exit exitB1 entry entB2 exit exitB2 se Initially the Stateflow diagram is asleep Parallel substatesA Al and8 B1 are active By definition this implies parallel AND superstates A andB areactive An event occurs and awakens the Stateflow diagram The condition Directed Event Broadcasting datal 1 is true The event is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of the event There is no valid transition 2 State A s children are parallel AND states They are evaluated and exe cuted from left to right and top to bottom State A A1 is evaluated first 3 StateA Al checks for any valid transitions as a result of the event Since the condition datal 1 is true there is a valid transition from state A A1 to stateA A2 4 Stated Al exit actions execute and complete exit A1 Start of 5 Stated Al is marked inactive event E_one processing 6 Thetransition action send _one B is executed and comple
24. A data object s scope defines to what extent the object is known relative to the Stateflow block the Simulink model and sources external to the Simulink model These are the options for the Scope property e Local Input from Simulink Output to Simulink Temporary Workspace Constant Exported Imported Local A Local data object resides and is accessible only within the hierarchy of the parent Valid Parent types are machine chart and state Input from Simulink A data object that originates from the Simulink model and is an input to the Stateflow block is an Input from Simulink data Input from Simulink data must be parented by the chart Input from Simulink data objects are accessible by the chart and its offspring Data defined to be an input is also an interface to the Simulink model of which the Stateflow block is a part When you define a data object as an Input from Simulink the appropriate notation is automatically added to the Stateflow block in the Simulink model Each data Input from Simulink is represented 3 27 3 Events and Data by a Simulink input port Multiple data inputs to the Stateflow block must be scalar they cannot be vectorized sf_ev_d_inout_ex File Edit Simulation Format Tools Input from Simulink data o Input fom E Simulink data inout ex2 O utput to Simulink A data object that originates from the Stateflow block and is an output to its Simulink model is an Output
25. Condition C_one is false Event E_one is processed from the root of the Stateflow diagram down through thehierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_one A potentially valid transition from state A to state B is detected H owever the transition is not valid because C_one is false 2 StateA during actions execute and complete dur A 3 Stated checks its children for a valid transition and detects a valid inner transition 4 Stated remains active The inner transition action A_t wo is executed and completed Becauseit is aninner transition stateA sexit andentry actions are not executed 5 TheStateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one 7 25 7 Semantics 7 26 Example Processing a Second Event Within an Exclusive OR State Using the same example what happens when a second event E_one occurs JA_four Stated isstill a eer ee active entry entA JA_two during durAG exit exitAG By entry entB during durB exit exitB E_two C_two A_three Initially the Stateflow diagram is asleep Stated is still active Event E_one occurs and awakens the Stateflow diagram Condition C_one is true Event E_one is processed from the root of the Stateflow diagram down through the hi
26. Data Scope on page 3 27 Table of Data Scope and Parent Combinations on page 3 32 Data Ports on page 3 32 Data Attributes on page 3 33 For information on creating modifying and deleting event and data objects see these sections Stateflow Explorer User Interface on page 5 5 Example Getting Started Adding Events and Data on page 5 16 and Stateflow Finder User Interface on page 5 20 4 3 4 Defining Stateflow Interfaces Defining the Stateflow Block Update Method Stateflow Block Update Methods Stateflow blocks are Simulink subsystems You have some flexibility in defining the type of Simulink subsystem of a particular Stateflow block The chart is awakened when an event occurs You can choose from these methods of having the chart awakened entered and executed Triggered l nherited This is the default update method Triggered The Stateflow block is explicitly triggered by a signal originating from a connected Simulink block The edge trigger can be set to Rising Falling Either or Function Call Inherited The Stateflow block inherits implicitly triggers from the Simulink model Theseimplicit events are the sample times discrete time or continuous of the Simulink signals providing inputs to the chart The sample times are determined by Simulink to be consistent with various rates of all the incoming signals Sampled Simulink will awaken Sample the Stateflow block at
27. Example Description a b Comparison of equality of two operands a amp amp b Logical AND of two operands a amp b Bitwise AND of two operands a b Logical OR of two operands a b Bitwise OR of two operands Action Language Example Description a Comparison of inequality of two operands a l a lt gt b a gt b Comparison of the first operand greater than the second operand a lt b Comparison of the first operand less than the second operand a gt b Comparison of the first operand greater than or equal to the second operand a lt b Comparison of the first operand less than or equal to the second operand a b Bitwise XOR of two operands Unary Operations These unary operations are supported Example Description a Logical not of a Complement ofa ifbitops is enabled Logical not of a Negative of a 6 47 6 N otations Unary Actions These unary actions are supported Example Description att Increment a a Decrement a Assignment Operations These assignment operations are supported Example Description a expression Simple assignment a expression Equivalent toa a expression a expression Equivalent toa a expression a expression Equivalent toa a expression a expression Equivalent toa a expression These additional assignment operations are supported when bit operations are enabled Example Desc
28. Power_off Shift 1 Switch Switch Shift 1 Shift 1 10 12 Debugging Runtime Errors The Stateflow diagram has two states at the highest level in the hierarchy Power_off andPower_ on By default Power off is active The event Switch toggles the system between beingin Power off andPower_on Switch is defined as an Input from Simulink event Power _on has three substates First Second andThird By default when Power _on becomes active Fi rst also becomes active Shi f t is defined as an Input from Simulink data object When Shi ft equals 1 the system transitions fromFirst toSecond Second to Third Third toFirst and then the pattern repeats In the Simulink model there is an event input and a data input A Sine wave block is used to generate a repeating input event that corresponds with the Stateflow event Swi t ch The Step block is used to generate a repeating pattern of 1 and 0 that corresponds with the Stateflow data object Shi f t Ideally the Swi tch event occurs in a frequency that allows at least onecyclethrough First Second andThird Typical Scenario to Debug Runtime Errors These steps describe a typical debugging scenario to resolve runtime errors in the example model 1 Create the Simulink model and Stateflow diagram including defining the event and data objects 2 Ensurethesfun target includes debugging options 3 Invoke the Debugger and choose debugging options 4 Sta
29. Sf pri Sf pri nt nt nt nt nt diagram name ps diagram_name psc diagram name tif diagram name clipboard nt prints the visible portion of the current Stateflow diagram A read only preview window appears while the print operation is in progress An informational box appears indicating the printing operation is starting See Printing Large Stateflow Diagrams on page 2 23 for information on printing Stateflow diagrams that are larger than the editor display area sfprint diagram Stateflow sfprint diagram Stateflow sfprint diagram Stateflow sfprint diagram nam nam nam e ps prints the visible portion of the specified diagram to a postscript file e psc prints the visible portion of the specified diagram to a color postscript file e tif prints the visible portion of the specified diagram toa tif file nam e clipboard prints the visible portion of the specified Stateflow diagram to a clipboard bitmap PC version only 11 9 sfhelp Purpose Syntax Description 11 10 Display Stateflow online help in an HTML browser sf help sf hel p invokes your HTML browser Netscape Navigator Internet Explorer etc displaying the Stateflow online help An online version of the Stateflow User s Guideis also accessible from the online help Your HTML browser must support HTML fram
30. The character is the default empty label for transitions Transitions and default transitions follow the same labeling format Select the transition to display the character Click on the to edit the label Transition labels have this general format event condition condition_action transition_ action Specify as appropriate relevant names for event condition condition_action andtransition_action Transitions do not have to have labels You can specify some all or none of the parts of the label Label Field Description event Event that causes the transition to be evaluated condition Defines what if anything has to be true for the condition action and transition to take place condition_action If the condition is true the action specified executes and completes transition_action After a valid destination is found and the transition is taken this action executes and completes Toapply and exit the edit deselect the object See these sections in Chapter 6 Notations for more information e Transitions on page 6 17 e Action Language on page 6 42 2 33 2 Using the Graphics Editor 2 34 Valid Labels Labels can consist of any alphanumeric and special character combination with the exception of embedded spaces Labels cannot begin with a numeric character The length of a label is not restricted Carriage returns are allowed in most cases Within a condition you must specify an e
31. Typical Parsing Error Messages Parse errors are usually caused by misrepresentations in the notation essentially syntax errors A common error in the notation is tousea backward slash instead of a forward slash to separate thetransition action from the condition action This will generate a general parse error 9 30 Typical Code Generation Related Error M essages Typical parse error messages include Invalid state name xxx or lnvalid event name yyy or Invalid data name zzz These parse errors are generated because non alphanumeric characters Such as spaces etc were used in state data or event names The only non alphanumeric character allowed in state data or event names is an underscore State name xxx is not unique in objects yyy and zzz This parse error is generated because there are two or more states at the same hierarchy level with the same name Invalid transition out of AND state xxx yy This parse error is generated because there is a transition originating from an AND parallel state The notation does not support this kind of transition Invalid intersection between states xxx and yyy This parse error is generated because neighboring state borders are intersecting If the intersection is not apparent consider the state to bea cornered rectangle instead of a rounded rectangle Ensure that the borders of the state if it were a cornered rectangle are not intersecting Junction
32. during durA entry entB exit exitA during durB exit exitBQ i lt 10 i funci Initially the Stateflow diagram is asleep Stated is active Event _one occurs and awakens the Stateflow diagram Event E_ one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_one Thereis a valid transition segment from state A tothe connective junction The transition segment condition action i 0 is 7 35 7 Semantics 7 36 executed and completed Of the two transition segments leaving the connective junction the transition segment that is a self loop back to the connective junction is evaluated next for validity That segment takes priority in evaluation because it has a condition specified whereas the other segment is unlabeled 2 Thecondition i lt 10 is evaluated as true The condition actions i and a call tof unc1 are executed and completed until the condition becomes false A connective junction is not a final destination thus the transition destina tion remains to be determined 3 Theunconditional segment to stateB is now valid The complete transition from stated to stateB is valid 4 StateA executes and completes exit actions exit A 5 Stated is marked inactive 6 StateB is marked active 7 StateB executes and completes entry actions ent B
33. from the drawing area to the Stateflow clipboard Copy Copies selected object s to the Stateflow clipboard Paste Pastes object s from the Stateflow clipboard to the drawing area at the current mouse location 2 10 Shortcut M enus Menu Choice Description Fit to View Select All Explore Debug Find Properties Applies panning and the maximum zoom that includes all selected objects If there is no selection list all objects are fit to the view see Zooming Options on page 2 4 Selects all object s in the Stateflow diagram Invokes the Stateflow Explorer Invokes the Debugger Invokes the Stateflow Finder Displays the selected object s properties dialog box See these sections for descriptions of the specific behavior General Shortcut Menu on page 2 12 State Shortcut Menu on page 2 13 Transition Shortcut Menu on page 2 14 and J unction Shortcut Menu on page 2 14 Menu options specific to an object type are available only from that object s shortcut menu The Font Size menu option is the only exception font size is modified via a virtual scrollbar on the General State and Transition shortcut menus and is modified to a discrete value via the graphics editor Style menu 2 11 2 Using the Graphics Editor 2 12 General Shortcut Menu Move the cursor to an open area of the drawing area and click the right mouse button to display the General shortcut men
34. subsystems and event detection You can design a model starting with a Stateflow control perspective and then later build the Simulink model You can also design a model starting froma Simulink algorithmic perspective and then later add Stateflow diagrams Y ou may havean existing Simulink model that would benefit by replacing Simulink logic blocks with Stateflow diagrams The approach you use determines how and in what sequence you develop various parts of the model The collection of all Stateflow blocks in the Simulink model isa machine When using Simulink together with Stateflow for simulation Stateflow generates an S function MEX file for each Stateflow machine to support model simulation This generated code is a simulation target and is called thes f un target within Stateflow Stateflow Coder generates integer or floating point code based on the Stateflow machine RTW generates code from the Simulink portion of the model and provides a framework for running generated Stateflow code in real time The code generated by Stateflow Coder is seamlessly incorporated into code generated by RTW You may want to design a solution that targets code generated from both products for a specific platform This generated code is specifically a RTW target and within Stateflow is called ther t w target Using Stateflow and Stateflow Coder you can generate code exclusively for the Stateflow machine portion of the Simulink model This generated co
35. the chart Stateflow diagram consists of a set of graphical states transitions connective junctions and history junctions and nongraphical events and data objects Within a chart this level is called the root of the hierarchy What Can You Do with Charts One of the most significant chart specific tasks is defining the interface between the chart and the Simulink model and or external sources See Chapter 4 Defining Stateflow Interfaces for detailed information At the chart level you can e Invoke the chart properties dialog box to Usethehypertext link to the Stateflow diagram the Simulink subsystem or the parent s property dialog box Specify which method will be used to awaken the chart Specify debugger breakpoints Add a description Link toa document e Explicitly print a chart 2 18 W orking with Charts Stateflow Diagrams Editing Chart Stateflow Diagram Properties Click the right mouse button in an open area of the Stateflow diagram to display the General shortcut menu This is the Chart properties dialog box a Chart action_ex Triggered or Inherited Sample Iimes a0 2 19 2 Using the Graphics Editor This table lists and describes the chart object fields Field Description Name Stateflow diagram name read only click on this hypertext link to bring the chart tothe foreground Simulink Subsystem Simulink subsystem name read only click on this hypertext link
36. the full names are unique because of the hierarchy of the Stateflow diagram The example intentionally contains only states for simplification purposes 6 16 Transitions Transitions What Is a Transition In most cases a transition represents the passage of the system from a source object to a destination object There are transitions between states There are also transitions between junctions and states A transition is represented by a line segment ending with an arrow drawn from a source object to the destination object This is an example of a transition from a source state 0n to a destination state Of f J unctions divide a transition into segments Each segment is evaluated in the process of determining the validity of the transition from a source toa destination This is an example of a transition with segments A default transition is one special type of transition that has no source object 6 17 6 Notations Labeling a Transition A transition is characterized by its laba The label can consist of an event a condition a condition action and or a transition action The character is the default transition label Transition labels have this general format event condition condition_action transition_action Replace as appropriate your names for event condition condition action and transition action Each part of the label is optional Example Transition Label This example shows the format
37. x is sourcing more than one unconditional transition The notation specifies that only one transition originating from a connective junction can be unconditional that is without a condition as part of its label Multiple history junctions in the same state xxx The notation specifies there can be only one history junction within a particular state 9 31 9 Generating Code 9 32 Code Generation Error Messages Typical code generation error messages include e Failed to create file model Name sfun c This code generation error message is generated if you do not have write permission for the current directory Either change directory to a writeable one or change the permissions on the current directory to fix this error Another unconditional transition of higher priority shadows transition xx This code generation error message is generated if there is more than one unconditional inner default or outer transition originating from the same source Default transition cannot end on a state that is not a substate of the originating state This code generation error is generated when a transition path starting from a default transition segment in one state completes at a destination state that is not a substate of the original state This notation is not supported because it causes infinite recursions in the generated code The solution is to change the design so that the above rule is not violated input data xxx
38. 27 4 Defining Stateflow Interfaces 4 28 This example shows the format required in the external code source custom code to make the event available sf_ev_d_inout_ex File Edit Simulation Format Tools Sine Wave Sine Wawet e is exported in the external code source fo e is added and external code source defined as an Imported event void external _broadcast_e void Stateflow generates this code for the Imported event extern void external broadcast_e void Exported Data You may want an external source outside the Stateflow diagram the machine and the Simulink model to be able to access a data object By defining a data object s scope to be Exported that data is made accessible to external sources Exported data must be parented by the machine because the machine is the highest level in the Stateflow hierarchy that can interface to external sources The machine also retains the ability to access the Exported data object Exporting the data object does not imply anything about what the external source does with the data It is the responsibility of the external source to Defining the Interface to External Sources include the Exported data object in the manner appropriate to the source to make use of the right to access the data If the external source is another machine then one machine defines an Exported data object and the other machine defines the same data o
39. 3 34 Type These data types are supported Real double Real float Integer long Integer short Boolean unsigned char Word unsigned long Word unsigned short Byte unsigned char Initial Value Scalar initial value of the data object 0 by default Minimum Value Smallest scalar value of the data object inf negative infinity by default Maximum Value Largest scalar value of the data object inf positive infinity by default Defining Stateflow nterfaces Overview Defining the Stateflow Block Update Method Defining Output to Simulink Event Triggers Event Inputs from Simulink Data Inputs from Simulink Event Outputs to Simulink Data Outputs to Simulink MATLAB Workspace Defining the Interface to External Sources 4 10 4 16 4 18 4 20 4 22 4 24 4 25 4 Defining Stateflow Interfaces 4 2 Overview Interfaces to Stateflow Each Stateflow block interfaces to its Simulink model Each Stateflow block may interface to sources external to the Simulink model data events custom code Events and data are the Stateflow objects that define the interface from the Stateflow block s point of view Events can be local to the Stateflow block or can be propagated to and from Simulink and sources external to Simulink Data can be local to the Stateflow block or can be shared with and passed to the Simulink model and to sources external to the Simulink mo
40. 5 typical tasks 9 4 using notation efficiently 9 7 code generation related error messages 9 30 coder command customization 9 23 coder file 9 5 combination state definition 6 12 notation 6 12 compilation error messages 9 32 condition definition 1 16 glossary definition A 3 notation overview 6 61 condition action actions specified as condition actions seman tics example 7 13 actions specified as condition and transition actions semantics example 7 14 cyclic behavior to avoid semantics example 7 17 using condition actions in f or loop construct semantics example 7 15 conflicting transitions 10 18 connective junction common destination notation example 6 38 common events notation example 6 38 definition 1 21 flow diagram semantics example 7 37 for loop construct semantics example 7 35 for loops notation example 6 35 from a common source notation example 6 37 glossary definition A 3 if then else decision construct semantics ex ample 7 33 notation overview 6 32 self loop notation example 6 34 self loop semantics example 7 34 transitions based on a common event semantics example 7 41 transitions from a common source to multiple destinations semantics example 7 39 transitions from multiple sources semantics ex ample 7 40 with all conditions specified notation example 6 33 with one unconditional transition notation ex ample 6 33 continuation symbols 6 62 custom code customization 9 25 cycle detection 10 21 Index
41. 6 42 for information on these operations Make Command Customization By default the command to generate an executable file for thes f un target is mex v AttheMATLAB prompt typehel p mex 9 23 9 Generating Code 9 24 for information on the MEX command and flags Also see the MATLAB Application Program Interface Guide for more information For thesf un target you can customize the MEX command flags but do not change the command itself By default the command to generate an executable file for ther t w target is sfc rtw TheMake Command field for ther t w target is read only You can fully customize the Make Command field for stand alone targets including specifying inclusion of external code sources A make utility may be included with your operating system such as on UNIX systems supplied with your compiler package such as the WATCOM wmake utility or part of a separate package like GNU gmake utility Whilethereare differences between various make utilities their operation is similar See the Real Time Workshop User s Guidefor more information Enable Debugging Animation If you want debugging animation options to be available during simulation you need to include them by clicking in the Enable Debugging Animation checkbox Enabling debugging animation options adds instrumentation codeto the target Generally speaking Debugging Animation should be disabled for stand alone targets The Debugger does not inte
42. 7 18 for more information on the semantics of this notation Example Transitions to and from Substates This example shows transitions to and from exclusive OR substates Waiting N Selection_made select 1 Restocking Orange Me State Ready is active initially State Wai ting is active initially Two of the substates of the 0n superstate are further defined to be superstates of their own The Stateflow diagram shows a transition from one OR substate to another OR substate Thetransition Wai ting Ready Orange n_motionis valid when state Wai ting Ready is active and event Sel ection_made occurs providing that theselect variable equals one This transition defines an explicit exit from the Wai ti ng Ready state and an implicit exit from the Wai ti ng superstate On the destination side this transition defines an implicit entry 6 23 6 Notations into the Or ange superstate and an explicit entry intotheOrange n_motion substate See the section titled Example Transition from a Substate to a Substate on page 7 11 for more information on the semantics of this notation What is a Default Transition Default transitions are primarily used to specify which exclusive OR state is to be entered when there is ambiguity among two or more neighboring exclusive OR states For example default transitions specify which substate of a superstate with exclusive OR decomposition the sy
43. Debugging 2 cee eee ee 10 4 Stateflow Debugger User Interface 10 6 Debugger Main Window 0 0c eee eee eee 10 6 Status Display Area 0 00 c cee 10 8 Break On Controls usses 000 c eee eee 10 8 Debugger Action Control Buttons 00 00 eae 10 9 Dynamic Checker Options 00 000 eee eee eee 10 10 Animation Controls 00000 c eee ee 10 10 Display Controls 20 00 cece eee 10 11 MATLAB Command Field 0000 eee eee 10 11 Debugging Runtime Errors 0005 10 12 Example Stateflow Diagram 02 cea eee ee 10 12 Typical Scenario to Debug Runtime Errors 10 13 Create the Model and Stateflow Diagram 10 13 Define the sfun Target 20 eee 10 14 Invoke the Debugger and Choose Debugging Options 10 14 Start the Simulation 0 2 0 c eee 10 14 Debug the Simulation Execution 0c eee eee 10 14 Resolve Runtime Error and Repeat 0 10 15 Solution Stateflow Diagram 20 2 cece ee 10 15 Debugging State Inconsistencies 10 16 What is a State Inconsistency 20 00 cee eee 10 16 Causes of State Inconsistency 020 cece ees 10 16 Detecting State Inconsistency 0 0c eee ee 10 16 Example Statelnconsistency 002 eee eee eee 10 17 Debugging Conflicting Transitions
44. Events What Is an Event Events drive the Stateflow diagram execution All events that affect the Stateflow diagram must be defined Each event has a parent The occurrence of an event causes the status of the states in the Stateflow diagram to be evaluated The broadcast of an event can trigger a transition to occur and or can trigger an action to be executed In this example if state Of f is active and the event swi tch_on is broadcast the transition from Of f toOn is triggered If stateOn is active and the event switch_off is broadcast the transition from 0n to Of f is triggered i switch_on Off a a switch_off Event Properties All events have these properties Name see Event Name on page 3 6 Description see Event Description on page 3 7 Parent see Event Parent Types on page 3 7 Events Hierarchy and Scope on page 3 9 Scope see Event Scope on page 3 10 Table of Event Parent and Scope Combinations on page 3 15 Port if Scope is Output to Simulink see Event Ports on page 3 16 Index if Scopeis Input from Simulink see E vent ndices on page 3 16 Trigger if Scope is Input from Simulink see Event Triggers on page 3 17 Determining Overall Input Trigger Type on page 3 18 3 Events and Data 3 6 See the section titled Action Language on page 6 42 for more information on the action language How Are Events Broadcast If ev
45. File Edit Simulation Format Tools Sine Wave inout e2 Multiple event inputs from the Simulink model to the Stateflow block must be vectored into that single port using the Simulink MUX block You must make 3 11 3 Events and Data 3 12 sure that the order of the input elements in the vector correspond properly to the index numbers defined in the event s property dialog box sf_ev_d_evwec EE x File Edit Simulation Format Tools Three Input from Simulink events are defined all Either Edge triggered O utput to Simulink An event that originates from the Stateflow block and is an output to its Simulink model is an Output to Simulink event Output to Simulink events must be parented by the chart Output to Simulink events are broadcast using a port and connection to a Simulink block or another Stateflow block Events that are defined to be outputs are also interfaces tothe Simulink model of which the Stateflow block is a part When you define an event to be an Output to Simulink the appropriate notation is automatically added to the Stateflow block in the Simulink model Each event output is represented by a Events Simulink output port Output events from the Stateflow block to the Simulink model are scalar sf_ev_d_inout_ex Eile Edit Simulation Format Tools Sine Wave Sine Wavet inout ex2 Output to Simulink event Exported Consider a real world example to clarify when
46. Parsing on page 9 11 for more information Some aspects of the notation are verified at runtime Using the Debugger you can detect runtime errors such as e State inconsistencies e Conflicting transitions e Data range violations e Cyclic behavior You can modify the notation to resolve runtime errors See Chapter 10 Debugging for more information on debugging runtime errors What Are the Graphical Objects These are the graphical objects in the notation that are on the toolbar Name Notation Toolbar Icon State History junction Default transition Connective junction 6 3 6 Notations A transition is a curved line with an arrowhead that links one graphical object to another Either end of a transition can be attached toa source anda destination object The sourceis where the transition begins and the destination is where the transition ends What Are the Nongraphical Objects Event and data objects do not have graphical representations These objects are defined using the Stateflow E xplorer See Chapter 3 Events and Data and Chapter 5 Exploring and Searching for more information What Is the Data Dictionary The data dictionary is a database containing all the information about the graphical and nongraphical objects Data dictionary entries for graphical objects are created automatically as the objects are added and labeled You explicitly define nongraphical objects in t
47. Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_one A valid transition segment from state A to a connective junction is detected The condition action A_one is detected on the valid 7 13 7 Semantics transition segment and is immediately executed and completed State A is still active 2 Since the conditions on thetransition segments to possible destinations are false none of the complete transitions is valid 3 StateA remains active StateA during action executes and completes dur A 4 TheStateflow diagram goes back tosleep waiting to beawakened by another event This sequence completes the execution of the Stateflow diagram associated with event E_one when stated was active Example Actions Specified as Condition and Transi tion Actions This example shows the semantics of a simple condition and transition action specified on a transition from one exclusive OR state to another Stated is active entry entA during durAQ exit exitAQ E_one C_one A_one A_two Bs entry entB during durB exit exitB Initially the Stateflow diagram is asleep Stated is active Event _one occurs and awakens the Stateflow diagram Condition C_one is true Event E_one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid t
48. Stateflow diagram in an existing Simulink model 1 23 1 Introduction These steps describe how to create a Simulink model with a Stateflow block label the Stateflow block and save the model 1 Display the Stateflow model window At the MATLAB prompt enter st at ef ow Here is the Stateflow model window stlib ojx Eile Edit Simulation Format Tools mm AOA Untitled Double click to open the This is a manual Statefloay Examples Library switch convenient for genersting events The window consists of untitled Stateflow block icon an Examples block and a manual switch This is the untitled Simulink model window with an untitled Stateflow block ke untitled iol x Eile Edit Simulation Format Tools Untitled 1 24 Using Stateflow 2 Label the Stateflow block Label the Stateflow block in the new untitled model by clicking in the text area and replacing the text Untitled with the text On off 3 Save the model Choose Save As from the File menu of the Simulink model window Enter a model title You can also save the model by choosing Save or Save As from the Stateflow graphics editor File menu Saving the model either from Simulink or from the graphics editor saves all contents of the Simulink model 1 25 1 Introduction Creating a Stateflow Diagram These steps describe how to create a simple Stateflow diagram using the graphics editor 1 Invoke the graphics editor Do
49. Thereis a valid transition from state A to superstateB Stated exit actions execute and complete exi t A Stated is marked inactive The transition action A is executed and completed StateB is marked active StateB entry actions execute and complete ent B StateB detects a valid default transition tostateB B1 State B B1 is marked active StateB B1 entry actions execute and complete ent B1 10 The Stateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one 7 19 7 Semantics Example Default Transition to a J unction This example shows the semantics of a default transition to a connective junction y By entry entB P A during durB exit exit emo C_one State B1is Bi B2 active entry entB1 entry entB2 during durB1 during durB2 exit exitB1 exit exitB2 Initially the Stateflow diagram is asleep State B B1 is active An event occurs and awakens the Stateflow diagram Condition C_t wo is true The event is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of any event There is none 2 StateB during actions execute and complete dur B 3 StateB checks for valid transitions and detects a valid transition se
50. These are the options for the Scope property Local Input from Simulink Output to Simulink Temporary Workspace Constant Exported Imported See Data Scope on page 3 27 for more information Port The Port field is relevant for data objects with Input from Simulink or Output to Simulink Scope otherwise the field is grayed out The Port number options are displayed in a pull down menu See Data Ports on page 3 32 for more information 5 13 5 Exploring and Searching 5 14 Type Type is the data type of the data object The default data type is Real double These Type options are displayed in a pull down menu Real double Real float Integer long Integer short Boolean unsigned char Word unsigned long Word unsigned short Byte unsigned char Initial Value The Initial Value is the user entered intial value of the data object 0 by default Minimum The Minimum is the user entered smallest scalar value of the data object inf negative infinity by default Maximum The Maximum is the user entered largest scalar value of the data object inf negative infinity by default Description Click in the text field area labeled Description and enter any textual comments or descriptions for the object Document Link Enter a web URL address or a general MATLAB command in the Document Link field Examples of links are www mat hworks com mailto email _address edit spec
51. This Stateflow diagram has a state inconsistency In the absence of a default transition indicating which substate is to become active the simulation encounters a runtime state inconsistency error Adding a default transition to one of the substates resolves the state inconsistency 10 17 10 Debugging Debugging Conflicting Transitions What is a Conflicting Transition A transition conflict exists if at any step in the simulation there are two equally valid transition paths from a source to a destination In the case of a conflict equivalent transitions based on their labels are evaluated based on the geometry of the outgoing transitions See Execution Order on page 7 62 for more information Detecting Conflicting Transitions To detect conflicting transitions during a simulation e Enable Debugging Animation and the Transition Conflict check in the Target Configuration sfun property dialog box e Build the target with the debugging options e Invoke the Debugger and enable Transition Conflict checking e Start the simulation Example Conflicting Transition This Stateflow diagram has a conflicting transition a 1 b 10 Af during a b 10 18 Debugging Conflicting Transitions The default transition to state A assigns data a equal to 1 and data b equal to ten State A s during action increments a and decrements b The transition from state A to state B is valid if the condition a gt
52. Wildcard radio box 5 Ensurethat the Events object typeis checked Event and data objects must already be defined using either the Explorer or the graphics editor Add menu A checkmark indicates that object is included in the search criteria 5 34 Searching for an O bject to Edit Properties By default all object types are included in the search criteria Deselect all other objects 6 Click on the Search button These are the results of the search za Stateflow Finder sf_exp_srch lol x sf_exp_srch Therearethree matches The Search History shows that the current search criterion iSEvents with name E The display shows the matches 7 Double dick on eventE_one to display the Event properties dialog box Eq Event E_one Rie pede macnine searcnir Local Port Ai inigger J E 5 35 5 Exploring and Searching 8 Add a description Click on the Close button to save the changes and close the Event properties dialog box An event s parent can be changed only through the Explorer 5 36 Notations Overview 2 2 ee a 6 2 States 6 kok we we 6 10 Transitions 0 0 248 6 17 Connective J unctions 6 32 History 2 a 6 40 6 Notations 6 2 Overview What Is Meant by Notation A notation defines a set of objects and the rules that govern the relationships between those objects Stateflow notation provides a common language to commun
53. awakens the Stateflow diagram a second time The Stateflow diagram root checks to see if there is a valid transi tion as a result of E_t wo Thereis no valid transition b State A executes and completes during actions dur A c StateA s children are evaluated starting with state A A1 StateA Al exe cutes and completes during actions dur A1 StateA Al is evaluated for 7 55 7 Semantics 7 56 valid transitions There are no valid transitions as a result of E_t wo within state Al d StateA A2 is evaluated StateA A2 executes and completes during actions dur A2 StateA A2 checks for valid transitions State A A2 has a valid transition as a result of E_t wo from state A A2 A2a tostateA A2 A2b e StateA A2 A2a exit actions execute and complete exit A2a f StateA A2 A2a is marked inactive g StateA A2 A2b is marked active h StateA A2 A2b entry actions execute and complete ent A2b The State flow diagram activity now looks like this Af entry entA during durA Q exit exitAG entry entA1 1 entry entA2 during durA 10 1 during durA2 exit exitA1 exit exitA2 StateAla A Li A2al is active entry entAta anty aneay ing ii during durA2a during durAta ring exit exitAla 13 exit exitA2a E_one E_two fatb tt A2b State A2b i entry entA1b entry entA2b i 1 during durA1b during durA2b is active i exit ex
54. be broadcast in the action language Events have hierarchy a parent and scope The parent and scope together define a range of access to events It is primarily the event s parent that determines who can trigger on the event has receive rights See Table of Event Parent and Scope Combinations on page 3 15 for more information Broadcasting an event in the action language is most useful as a means of synchronization amongst AND parallel states Recursive event broadcasts can lead to definition of cyclic behavior Cyclic behavior can be detected only during simulation 6 56 Action Language Example Event Broadcast State Action This is an example of the event broadcast state action notation Seethesection titled Example Event Broadcast State Action on page 7 45 for information on the semantics of this notation Example Event Broadcast Transition Action This is an example of the event broadcast transition action notation 6 57 6 Notations See the section titled Example Event Broadcast Transition Action Nested Event Broadcast on page 7 50 for information on the semantics of this notation Directed Event Broadcasting You can specify a directed event broadcast in the action language Usinga directed event broadcast you can broadcast a specific event to a specific receiver state Directed event broadcasting is a more efficient means of synchronization amongst AND parallel states Using direc
55. by another event This sequence completes the execution of the Stateflow diagram associated with event E_one when state 0n was active Example Processing of a Second Event Using the same example what happens when the next event E_ one occurs Oni entry entOn during durOng exit exitOn E_one E_one Off entry T State Off is active during durCfftQ exit exitOff Again initially the Stateflow diagram is asleep State Off is active Event E_one occurs and awakens the Stateflow diagram Event E_one is processed 7 9 7 Semantics 7 10 from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_ one A valid transition from state 0f f to state 0n is detected 2 State Off exit actions execute and complete exit Of f 3 State Off is marked inactive 4 State 0n is marked active 5 StateOn entry actions execute and complete ent On 6 TheStateflow diagram goes back tosleep waiting to be awakened by another event This sequence completes the execution of the Stateflow diagram associated with the second event E_one when state Of f was active Example Processing of a Third Event Using the same example what happens when a third event E_t wo occurs e State 0n is active entry en during durOn ESTERS exit exitOn Off entry entOff during d
56. c3 is met With the alternative representation using a connective junction the transition from A to the connective junction occurs first provided the event has occurred A destination state is then determined based on which of the conditions 1 2 or 3 is satisfied Thetransition from the source state to the connective junction is labeled by the event and those from the connective junction to the destination states by the conditions No event is applicable in a transition from a connective junction to a destination state See the section titled E xample f Then Else Decision Construct on page 7 33 for information on the semantics of this notation Example Connective J unction with One Unconditional Transition The transition A 8 is valid when A is active event E_one occurs and C_one is true The transition AC is valid when A is active event E_one occurs and C_two is true Otherwise given A is active and event E_one occurs the 6 33 6 Notations 6 34 transition AD is valid If you do not explicitly specify condition C_three it is implicit that the transition condition is not C_one and not C_two See the section titled Example I f Then Else Decision Construct on page 7 33 for information on the semantics of this notation Example Connective J unction Special Case Self Loop In some situations the transition event occurs but the condition is not met Thetransition cannot be tak
57. cist sch wtisteticn aR R aac fat cal E E R 8 25 Run the Carousel Demo 0000 0 8 27 OVEFVIEW 20 eee eee enn ene 8 27 Carousel Operator s Console 00 c eee ee ees 8 27 Generating Code Overview 25 2256 6e5snn de SASS ehhh ele cheba het ened 92 OVEFVIEW 2 nee ene ene 9 2 Stateflow Coder 0 0 ccc eee eee 9 2 Stateflow Dynamic Checker 0 0 cece eee 9 3 Compile Build Options 0 a 9 3 Typical Tasks to Generate Code 0 ees 9 4 Typical Code Generation Sequence 0 0 c eee eee 9 5 Coder File and Coder Function sssa uaaa 9 5 Using the Notation Efficiently 9 7 Where to Find Information on Creating a Stateflow Diagram 9 7 Designing for Efficiency 2 aa 9 7 Optimizing for Speed 0 0 0 cee 9 7 Optimizing for Code Size 1 2 cee ees 9 8 Optimizing for Memory Use 000 cee ee 9 9 Parsing soeke eee ce ae Re eee a eS 9 11 PA SON ea aa aai E EAE a i E E tel gest aera E a deb 9 11 Parse the Machine or the Stateflow Diagram 9 11 Adding and Specifying a Stand Alone Target 9 16 Stand Alone Targets 00 c cece tees 9 16 Invoke the Explorer 0 000 eects 9 16 Adda Stand Alone Target cece eee eee 9 17 Customizing the Target 0 cee eee eee 9 20 OVERVICW cee eR Pei Saree Wi ae fans een We eae seat a Wane a aoe A 9 20 Potential Cus
58. condition condition_action Aransition_action When the event occurs the transition is evaluated The condition action is executed as soon as the condition is evaluated as true and before the transition destination has been determined to be valid Enclose the condition action in curly brackets Specifying a transition action means that the action is executed when the transition is taken provided the condition if specified is true State Action Notation Actions can be associated with states via the state s label by definingent ry during exit andon event name keywords The general format of a state label is state_name entry actioni action20 during action30 exit action4d action5d on event_name action60 See the section titled Semantics of State Actions on page 7 7 for information on the semantics of state actions See the examples in Chapter 7 Semantics for examples of the semantics of state actions 6 43 6 Notations Action Language Components The action language defines usage rules for these components Bit operations Binary operations Unary operations Assignment operations User written function calls ml function ml Name space operator Data and event arguments Arrays Event broadcasting Directed event broadcasting Conditions Time t Literals Continuation symbols Comments Semicolon Bit Operations You can enable C like bit operations by adding thebi tops
59. data speed txt Stateflow Explorer User Interface Apply Revert and Close Buttons Click on the Apply button to save the current values Click on the Revert button to go back to the original values after changes have been applied but before the dialog box has been closed The Revert button is grayed out until a change has been applied Click on the Close button to save the current values and close the dialog box 5 15 5 Exploring and Searching Example Getting Started Adding Events and Data 5 16 Task Overview The flexibility and power provided by parenting and scoping events and data can be overwhelming and complex to begin with The simplest case to consider is e Create a Simulink model containing a single Stateflow diagram e Use the Simulink implicit event broadcast to awaken the Stateflow diagram e Define events and data parented by the chart e Define events and data scope as Local e Broadcast any Local events within the Stateflow diagram Events and data are typically added using the Explorer The graphics editor Add menu provides a shortcut method to quickly add new events and data Usingthe Add menu creates the object with the chart as the parent By default the object s scope is Local Solution Model and Stateflow Diagram The Simulink model contains a single Stateflow diagram and uses the Simulink implicit event broadcast to awaken the Stateflow diagram and trigger transitions labeled to be valid on any ev
60. defining output event 4 10 example output event semantics 4 12 output event example 4 11 function call and edge triggers combining 3 19 function call triggered 3 18 functions sfexit 11 4 sfhel p 11 10 sfnew 11 3 sfprint 11 9 sfsave 11 5 stateflow 11 6 user written 6 49 G graphical objects copying 2 16 cutting and pasting 2 16 selecting and deselecting 2 15 graphics editor add menu 2 48 drawing area 2 3 edit menu 2 45 file menu 2 43 help menu 2 49 main window components overview 2 2 menu bar 2 5 menus overview 2 42 message area 2 3 modified flag 2 5 object button modes 2 15 overview 2 2 print as submenu 2 44 productivity boosts 2 7 scroll bars 2 4 shortcut menus overview 2 10 simulation menu 2 45 Stateflow diagram name 2 4 style menu 2 46 toolbar 2 6 tools menu 2 47 using 2 15 virtual scrollbar 2 7 zooming options 2 4 hierarchy 1 15 definition 1 15 events 6 9 events and data 3 3 glossary definition A 6 state 6 7 transition 6 8 history junction and a default transition semantics example 7 21 and an inner transition semantics example 7 31 definition 1 17 glossary definition A 6 notation overview 6 40 use of history junctions notation example 6 40 Index l if then else another notation example 6 33 notation example 6 33 semantics example 7 33 implicit local events example 3 21 overview 3 20 types 3 20 imported data 4 29 event 4 27 inner transition before using an inner trans
61. detection at runtime Cycle detection does not require any instrumented code and is thus controlled solely by the Debugger The cycle detection algorithm can detect certain classes of runtime infinite loops recursions that repeat forever These loops are caused by recursive event broadcasts See Chapter 10 Debugging and specifically Dynamic Checker Options on page 10 10 for information on how to use the Debugger in conjunction with these options and also the cycle detection option Add Customized Code You can add customized code that is prepended to the generated target code in the Custom Code field For example you might want to specify inclusion of custom header files and declarations of user written functions Any code specified here is considered external to the Stateflow diagram the machine and the Simulink model Specify a Document Link For convenience enter a web URL address or a general MATLAB command Examples are www mathworks com mailto email address edit spec data speed txt Thecontents of this field are not represented in the generated code 9 25 9 Generating Code 9 26 Compiling Code Building Targets Compile Build Options These options exist for compiling code and building targets sf un simulation target generation Stateflow generates the simulation target Stateflow and Simulink are required Thereis asinglesfun target provided by default with Stateflow The target code in this ca
62. diagram Neither C_one nor C_two is true Event E_ one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition at the root level as a result of E_ one There is no valid transition State A during actions execute and complete dur A Stated checks itself for valid transitions and detects a valid inner transition to a connective junction The segments labeled with a condition are evalu ated before the unlabeled segment The evaluation starts from a twelve o clock position on the junction and progresses in a clockwise manner Since neither C_one nor C_two is true the unlabeled transition segment is evaluated and is determined to be valid The full transition from the inner transition to state A A3 is valid State A A2 exit actions execute and complete exit A2 State A A2 is marked inactive State A A3 is marked active State A A3 entry actions execute and complete ent A3 The Stateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one when neither C_one nor C_two is true Inner Transitions Example Inner Transition to a History J unction This example shows the semantics of an inner transition to a history junction Al entry entA during durA exit exitA AQ
63. dialog box This operation implicitly parses the machine and generates the S function code 3 Click on the Build Stateflow Target button in the Target Configuration sfun dialog box to build the simulation target This operation implicitly parses the machine generates code and generates an executable image You can build one target at a time Alternatively you can build thes fun target through either of these options e Choosing Start from the graphics editor Simulation menu e Choosing Start from the Simulink model Simulation menu e Choose Debug from the graphics editor Tools menu choose debugging options and click on the Go button Each of these options implicitly parses the machine generates code and generates an executable image Informational and any error messages related to the S function code generation are displayed in a pop up window and alsoin the MATLAB command window See the Application Program Interface Guide for information on proper installation of the C compiler for integration into the MATLAB environment Compiling Building Targets with RTW RTW performs the target generation of a Simulink model that contains a Stateflow machine When an RTW build is initiated RTW automatically detects the presence of a Stateflow machine RTW creates a Stateflow target titled r tw on Stateflow s behalf 9 27 9 Generating Code 9 28 These steps show how to build a target with RTW 1 Choose Parameters fro
64. during dur_action exit exit_action on Switch_off on_action The action language defines the types of actions you can specify and their associated notations An action can bea function call an event to be broadcast a variable to be assigned a value etc Stateflow supports both Mealy and Moore finite state machine modeling paradigms In the Mealy model actions are associated with transitions whereas in the Moore model they are associated with states Stateflow supports state actions transition actions and condition actions For more information see the section titled What Is an Action Language on page 6 42 Parallelism A system with paralldism has twoor more states that can be active at the same time The activity of each parallel state is essentially independent of other states In the Graphical Components figure St ateA2a andStateA2b are parallel AND states St ateA2 has parallel AND state decomposition 1 19 1 Introduction For example this Stateflow diagram has parallel superstate decomposition a gout Transmission Heat Clutch_engaged Switch_on a engaged 5 Switch_off ua first speed gt threshold 1 s 00 ee io Switch_off lt Thetransmission heating and light systems are parallel subsystems in a car They exist in parallel and are physically independent of each other There are many other parallel components in a car such as the braking and windshield w
65. eee 8 5 What Are the State LabelS 0 cee eee 8 6 Will J unctions Simplify the Design 0 8 6 What Are the Transitions 0 000 ccc ee eee eee 8 6 Are There Default Transitions 0 0 ee eee 8 7 AreThereEventS ideeautot aa ao aE eee eee ee eens 8 7 Is There Data ccc eee eee 8 7 Procedure 0 0 ccc cette eee teen ens 3 8 OVER VIGW i iip m i teo a Baek ot bac Sian a day d at a a apa eK a ade bib A 8 8 Create a Simulink Model 0 0 cc eee eee 8 9 Sample Stateflow Diagram 0000s 8 10 Create and Label the OR States 0000 0c aes 8 10 Create and Label the Superstates 00005 8 13 Create and Label the AND States 0000005 8 14 Create the Transitions 0 ccc ee ee eee 8 15 Label the TransitionS 0 0 0 cece eee ee eee 8 16 Create Default Transitions 0000s 8 17 Add and Define Event Objects 0c eee eee 8 18 Add and Define Data Objects 0c eee eee 8 20 Save th Model ss wiikey he tices oa de cece ea Bai Bohl cop pick endo a 8 23 xvi Contents Run the Simulation for the Provided Solution 8 24 OVEIVIEW essas Cede a eS eee ea a NERA 8 24 Carousel Simulink Model Solution 000 8 24 Carousel Operator s Console 00 eee eee eee ee 8 24 Carousel Solution Stateflow Diagram 4 8 25 Produrre aeiississies di
66. embedded spaces The name cannot begin with a numeric character The length of a name is not restricted Events You can qualify an event name by prepending ancestry names In this example the transition action specifies a qualified event nameHeater Heat_switch to be broadcast Peni Heater i 1 i Dn On i Fan_switch Heater Heat_switch Heat_switch Ort Heat_switch Event Description The description can consist of any ASCII text you want to enter to describe the object Event Parent Types You must choose a parent when defining an event You explicitly choose the parent through the Explorer The chart is implicitly the parent if you use the 3 Events and Data graphics editor Add menu The parent and scope together define a range of access to events Events can have parents with these object types e Machine The machine is the collection of all Stateflow blocks in the Simulink model In this example the machineis the collection of syst eml andsystem2 State flow blocks Parent_exnew Bil x Eile Edit Simulation Format Tools chart chart systeme e Chart Stateflow diagram The chart Stateflow diagram refers to the specific Stateflow block The Stateflow blocks titled system1 andsystem2 each represent an underlying chart that can parent objects within the Stateflow diagram 3 8 Events e State The state refers toa specific state within the hierarchy In the example this
67. emergency switch to bring the carousel to an emergency stop Choose Stop from the graphics editor Simulation menu to stop the simulation and unfreeze the graphics editor The simulation must be stopped to be able to close the model Choose Close from the File menu of the carousel demo model window Generating Code Overview Using the Notation Efficiently Parsing Adding and Specifying a Stand Alone Target Customizing the Target Compiling Code Building Targets Typical Code Generation Related Error Messages 9 2 9 11 9 16 9 20 9 26 9 30 9 Generating Code 9 2 Overview Overview Knowledge of the semantics is important to make sound Stateflow diagram design decisions and for code generation The default semantics provided with the product are described in Chapter 7 Semantics The Stateflow notation supports many different ways of representing desired system behavior The representation you choose directly affects the efficiency of the generated code See U sing the Notation Efficiently on page 9 7 for more information The Stateflow simulation code generator generates code for simulation targets Stateflow Coder generates code for stand alone or RTW targets This chapter discusses both types of code generation Stateflow Coder Stateflow Coder is a separately available product for use with Stateflow to generate code for RTW and Stateflow stand alone nonsimulation
68. entry entA20 during durA2 State Al is c exit exitA2 active entry ental during durAd exit exitAd 0 Initially the Stateflow diagram is asleep Stated Al is active Thereis history information since superstate A is active Event E_ one occurs and awakens the Stateflow diagram Event E_one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition asa result of E_ one Thereis no valid transition 2 StateA during actions execute and complete dur A 3 Stated checks itself for valid transitions and detects there is a valid inner transition to a history junction According to the semantics of history junc tions the last active state A A1 is the destination state 4 Stated Al exit actions execute and complete exit A1 5 Stated Al is marked inactive 6 Stated Al is marked active 7 Stated Al entry actions execute and complete ent Al 8 TheStateflow diagram goes back tosleep waiting to be awakened by another event 7 31 7 Semantics This sequence completes the execution of this Stateflow diagram associated with event E_one when thereis an inner transition toa history junction and state A Al is active 7 32 Connective Junctions Connective J unctions Example If Then Else Decision Construct This example shows the semantics of ani f t hen else decision con
69. example shows a default transition to a connective junction Counting select 4 select 1 select 3 f Cola select 2 In this example the default transition to the connective junction defines that upon entering the Counti ng state the destination is determined by the condition on each transition segment Seethe section titled Example Default Transition toa jJ unction on page 7 20 for more information on the semantics of this notation Example Default Transition with a Label This example shows a use of labeling default transitions 6 26 Transitions If stated is initially active and either e1 or e2 occurs the transition from state A to superstate B is valid The substates B1 and B2 both have default transitions The default transitions are labeled to specify the event that triggers thetransition If event e1 occurs thetransition A 81 is valid If event e2 occurs the transition A gt B2 is valid See the section titled Example Labeled Default Transitions on page 7 23 for more information on the semantics of this notation What Is an Inner Transition An inne transition is a transition that does not exit the source state I nner transitions are most powerful when defined for superstates with exclusive OR decomposition Use of inner transitions can greatly simplify a Stateflow diagram Example One Before Using an Inner Transition This is an example of a Stateflow diagram that c
70. executed in a sequence based upon action type The action types are entry during exit oron event _name actions This table shows the button icon and a short description of a state Name Button Icon Description State Use a state to depict a mode of the fe system Superstate A state is a superstate if it contains other states called substates Substate A state is a substate if it is contained by a superstate What Is a State Decomposition A state has a decomposition when it consists of one or more substates A Stateflow diagram that contains at least one state also has decomposition Representing hierarchy necessitates some rules around how states can be grouped in the hierarchy A superstate has either parallel AND or exclusive OR decomposition When looking at any one point in the hierarchy all substates of a superstate must be of the same decomposition States Parallel AN D State Decomposition Parallel AND state decomposition is indicated when states have dashed borders This representation is appropriate if all states at that samelevel in the hierarchy are active at the same time The activity within parallel states is essentially independent The children of parallel AND decomposition parents are AND states Exclusive OR State Decomposition Exclusive OR state decomposition is represented by states with solid borders Exclusive OR decomposition is used to describe system modes that are mutually
71. from off to on This may require switching off then switching on again Ensure that the running speed switch is in the normal position If it is not already visible double click on the Scope block The start switch is a toggle Click the start switch from up to down or from down to up to start the carousel Observe the speed in the Scope block The ride runs for Duration seconds but can be stopped prematurely by changing the running speed switch to overspeed or by clicking the emergency switch Theemergency switch is alsoa toggle Click the emergency switch from up to down or from down to up to bring the carousel to an emergency stop Choose Stop from the graphics editor Simulation menu to stop the simulation and unfreeze the graphics editor The simulation must be stopped to be able to close the model Choose Close from the File menu of the carousel model solution window Run the Carousel Demo Run the Carousel Demo Overview Audio and video have been added to the carousel demo The demo also uses many advanced features that are left to your experimentation and investigation On UNIX systems the audio portion of the demo is disabled Carousel Operator s Console As in the carousel solution example the switches in the Simulink model are used to act as a carousel operator s console The switches allow you to e Turn the carousel power on and off e Start the ride e Stop the ride in case of emergency e Specify
72. have Web access connect to The MathWorks home page http www mat hworks com Look for the license manager and installation information under theTech Notes FAQ link under Tech Support Info XX X Before You Begin Introduction Overview What Is Stateflow ae i Examples of Stateflow Applications Stateflow Components Design Approaches Finite State Machine Concepts What Is a Finite State Machine FSM Representations Stateflow Representations Notations Semantics References Anatomy of a Model and Machine The Simulink Model and Stateflow Machine Defining Stateflow Interfaces Stateflow Diagram Objects Using Stateflow Stateflow Typical Tasks Sample Solution Creating a Simulink Model Creating a Stateflow Diagram Defining the Stateflow Interface Running a Simulation Debugging Generating Code 1 Introduction 1 2 Overview What Is Stateflow Stateflow is a powerful graphical design and development tool for complex control and supervisory logic problems Stateflow supports flow diagram notation as well as state transition notation Using Stateflow you can Visually model and simulate complex reactive systems based on finite state machine theory Design and develop deterministic supervisory control systems Use flow diagram notation and state transition notation seamlessly in the same Stateflow diagram Easily modify your design evaluate the results a
73. how the Simulink model can be combined with a GUI Basic Operation The carousel is divided into these main physical components e Main platform of the ride e Audio e Video The carousel can either be on or off When the carousel is on the platform can be stopped or moving depending on whether a rideisin progress Y ou havethe option of having music play and displaying a video image of the carousel that O verview rotates on the operator s console You enable audio and video before starting the ride When the operator of the ride pushes the start button the platform turns music plays and video rotates if enabled The ride lasts the amount of time the operator specifies If the carousel exceeds a maximum speed it stops automatically There is an emergency stop button on the carousel operator s console if for any reason the operator decides the ride needs to be stopped 8 3 8 Tutorial Entering a Stateflow Diagram Designing the Carousel Stateflow Diagram Overview A Stateflow diagram is only as good as the up front analysis and design work for the desired system behavior Before you can create your Stateflow diagram you need to interpret the verbal description of the system behavior and translate that description into Stateflow notation F or the purposes of this tutorial some aspects of the operation are simplified The Design Questions Addressing these questions helps in creating a Stateflow diagram t
74. in subparagraph a of the Rights in Commercial Computer Software or Commercial Software Documentation Clause at DFARS 227 7202 3 therefore the rights set forth herein shall apply and b For any other unit or agency NOTICE Notwithstanding any other lease or license agreement that may pertain to or accompany the delivery of the computer software and accompanying documentation the rights of the Government regarding its use reproduction and disclo sure are as set forth in Clause 52 227 19 c 2 of the FAR MATLAB Simulink Handle Graphics and Real Time Workshop are registered trademarks and Stateflow and Target Language Compiler are trademarks of The MathWorks Inc Other product or brand names are trademarks or registered trademarks of their respective holders Printing History May 1997 First printing J anuary 1998 Revised for 5 2 online version Before You Begin 1 Related Products and Documentation xxii REQUIRGMENIS ids ohh owe tosk Vee dea ee eae ees xxii How to Use This Guide LL unuau naaa aeaa xxvi Chapter Quick Reference 0 cee xxvi Typographical Conventions ss sssaaa aeaaea xxvii Installation Laa xxviii Introduction OVErVvieW eee eh oo ees oe Sits Pade en week 1 2 What Is Stateflow 0 0 0 eee 1 2 Examples of Stateflow Applications 055 1 3 Stateflow ComponentS 000 e eee eee eee ee 1 3 Design Approaches 0 0 cec
75. is false The condition actions on both the first segment and the self loop to the connective junction effectively execute a f or loop fori values O to 9 executefunci1 Thef or loop is executed outside of the context of a state The remainder of the path is 6 35 6 Notations evaluated Since there are no conditions the transition completes at the destination state B i lt 10 i func1 0 See the section titled Example For Loop Construct on page 7 35 for information on the semantics of this notation Example Flow Diagram Notation This example shows a real world use of flow diagram notation and state transition notation This Stateflow diagram models an 8 bit analog to digital converter ADC Consider the case when stateSensor Low is active and event UPDATE occurs The inner transition from Sensor tothe connective junction is valid The next transition segment has a condition action st art_adc which initiates a reading from the ADC The self loop on the second connective junction repeatedly tests the condition adc_busy This condition evaluates as true once the reading settles stabilizes and the loop completes This self loop is used to introduce the delay needed for the ADC reading to settle The delay could have been represented by using another state with some sort of counter Using flow notation in this example avoids an unnecessary use of a state and produces more efficient code The next tra
76. issysteml s Stateflow diagram Either of these states sys1_on and sysl_off can be parents sysl_on entry sysl_on 1 Switch sys1_off entry sys1_on 0 Events Hierarchy and Scope Events have hierarchy a parent and scope The parent and scope together define a range of access to events Access to events is defined in terms of these two questions Who can broadcast the event sender The event s scope determines who can broadcast the event has send rights The event s parent has no effect on who can broadcast the event By default when you create a new event in the Explorer the event scope is Local A Local event can be broadcast from anywhere in the hierarchy of the machine Changing the scope of the event to a different scope changes this behavior See Event Scope on page 3 10 for the behavior associated with the scope value choices Who can trigger on the event receiver It is primarily the event s parent that determines who can trigger on the event has receive rights You must explicitly choose a parent when defining an event By default when you create a new event in the Explorer the event s scope is Local A Local event can trigger transitions from anywhere in the hierarchy of its parent Changing the scope of the event from the default value of Local to one of the other values changes this default behavior See Event Scope on page 3 10 for the behavior associated with the scope value
77. keyword 2 26 format 2 26 on keyword 2 26 Index Stateflow applications types of 1 3 component overview 1 3 defining interfaces overview 1 10 design approaches 1 4 feature overview 1 2 representations 1 6 stateflow 11 6 Stateflow block considerations in choosing continuous update 4 7 continuous 4 4 continuous example 4 8 defining a continuous 4 7 defining a sampled 4 5 defining a triggered 4 5 defining an inherited 4 6 inherited 4 4 inherited example 4 7 sampled 4 4 sampled example 4 6 triggered 4 4 triggered example 4 5 update methods 4 4 Stateflow Coder overview 9 2 Stateflow diagram glossary definition A 10 graphical components 1 12 objects 1 11 update methods 4 4 Stateflow Dynamic Checker data range violations 9 25 overview 9 3 state inconsistencies 9 24 transition conflicts 9 25 Stateflow interfaces overview 4 2 typical tasks to define 4 2 substate glossary definition A 11 superstate glossary definition A 11 T target build options 9 3 building error messages 9 32 compile options 9 3 customizing 9 20 potential customization 9 20 target configuration sf un dialog box 9 21 target customization add custom code 9 25 coder command 9 23 document link 9 25 enable debugging animation 9 24 enable Dynamic Checker options 9 24 make command 9 23 time 6 61 1 13 Index transition changing arrowhead size 2 34 creating and deleting 2 31 debugger breakpoint property 2 37 debugging conflicting 10 18 def
78. of a self loop using a connective junction State A is active entry entA during durAQ exit exitAQ Bi entry entB during durBO exit exitBQ C_one A_one Initially the Stateflow diagram is asleep Stated is active Event E_one occurs and awakens the Stateflow diagram Condition C_one is false Event _one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_ one Thereis a valid transition segment from state A to the connective junction The transition segment labeled with a condition and action is evaluated for validity Since the condition C_ one is not valid the Connective Junctions complete transition from state A to state B is not valid The transition segment from the connective junction back to state A is valid 2 StateA executes and completes exit actions exit A 3 Stated is marked inactive 4 Thetransition action A_t wo is executed and completed 5 Stated is marked active 6 States executes and completes entr y actions ent A 7 TheStateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one Example For Loop Construct This example shows the semantics of af or loop Stated is active entry entay _E one i 0 By
79. of a transition label E off_count O off_count Light_off Off Event The specified event is what causes the transition to be taken provided the condition if specified is true Specifying an event is optional Absence of an event indicates that the transition is taken upon the occurrence of any event Multiple events are specified using logical operators amp In this example the broadcast of event E triggers thetransition from On toof f provided the condition of f_count 0 is true Condition A condition is a Boolean expression to specify that a transition occurs given that the specified expression is true Enclose the condition in square brackets See the section titled Conditions on page 6 61 for information on the condition notation 6 18 Transitions In this example the condition off _count 0 must evaluate as true for the condition action to be executed and for transition from the source to the destination to be valid Condition Action The condition action is executed as soon as the condition if specified is evaluated as true and before thetransition destination has been determined to be valid If thetransition consists of multiple segments the condition action is executed as soon as the condition if specified is evaluated as true and before the transition segment is determined as valid Enclose the condition action in curly brackets See the section titled Action Language on p
80. of the graphics editor Select the parent for the new data object Double click on the machine name the name you specified when you saved the Simulink model in the Object Hierarchy list Double click on the chart name the name you specified on the Stateflow block The chart will be the parent for all the data in the carousel example Choose New and then Data from the Explorer File menu The Data object properties dialog box is displayed Enter Max_speed in the Name field Select Constant in the Scope field Click on the Close button to save the changes and close the dialog box Save the Model 1 2 Choose Save from the graphics editor File menu to save the entire model If you want to exit from Stateflow and MATLAB choose Exit MATLAB from the File menu of the Stateflow graphics editor 8 23 8 Tutorial Entering a Stateflow Diagram 8 24 Run the Simulation for the Provided Solution Overview The Simulink model and Stateflow diagram created in Procedure on page 8 8 is not complete enough to run a simulation This provided solution is based on the tutorial and extends it Carousel Simulink Model Solution This is the provided carousel Simulink model solution sf_carousel_2 O x File Edit Simulation Format Tools MATLAB h Function mealtime syne hronization running speed overspeed Carousel Operator s Console The switches in the Simulink model are used to act as a ca
81. on left hand side of an expression in yyy This code generation error is generated if the Input from Simulink data object indicated is appearing on the left hand side of the expression specified By definition the value of the data object is assigned in Simulink Stateflow cannot change the value Compilation Error Messages If compilation errors indicate the existence of undeclared identifiers verify that variable expressions in state condition and transition actions are defined Consider for example an action language expression such as a b c In addition to entering this expression in the Stateflow diagram you must create data objects for a b and c using the Explorer If the data objects are not defined the parser assumes that these unknown variables are defined in the Custom code portion of the target which is included at the beginning of the generated code This is why the error messages are encountered at compile time and not at code generation time Debugging Overview Stateflow Debugger User Interface Debugging Runtime Errors Debugging State Inconsistencies Debugging Conflicting Transitions Debugging Data Range Violations Debugging Cyclic Behavior 10 2 10 6 10 12 10 16 10 18 10 20 10 21 Debugging ao 10 2 Overview Debugging Use the Stateflow Debugger to debug and animate the Stateflow diagramsina particular machine It is a good idea to include debugg
82. operator It is useful to define a separate state for the timer that will generate the event indicating when the ride is done The timer is either counting or stopped There are three states associated with the timer Counting Stopped andTi mer The Carousel System The carousel system is either on or off There aretwostates associated with the carousel at the system level Power_on andPower off What Is a State Decomposition The Stateflow diagram level of the hierarchy has exclusive OR decomposition and consists of two OR states Power_on and Power off The Power_on state has parallel AND decomposition and consists of these AND substates Ti mer Audio Video and Ri de When thePower_on stateis active theTi mer Audio Vi deo andRi de states are active They are essentially subsystems of the carousel system TheTi mer Ride Audio and Vi deo states have exclusive OR decomposition See What Is a State Decomposition on page 6 10 for more information 8 5 8 Tutorial Entering a Stateflow Diagram What Are the State Labels Part of the process of defining each state is defining the state label The state name is the part of the label that describes the state in some recognizable way The state labels in the carousel consist of the name of the state See the section titled Labeling a State on page 6 13 for information on valid state labels Will Junctions Simplify the Design The carousel system as des
83. operator 6 53 N notation action language array arguments 6 56 assignment operations 6 48 binary operations 6 45 bit operations 6 44 choosing between ml and ml 6 55 comments 6 62 components 6 44 condition overview 6 61 continuation symbols 6 62 data and event arguments 6 56 directed event broadcasting 6 58 event broadcasting 6 56 literals 6 62 objects with actions 6 42 state action 6 43 time symbol 6 61 transition action 6 43 unary actions 6 48 unary operations 6 47 use of semicolon 6 62 user written functions 6 49 connective junction overview 6 32 1 10 default transition definition 6 24 default transition example 6 25 default transition labeling 6 24 definition 1 7 6 2 designing for efficient code 9 7 flow diagram overview 6 32 glossary definition A 7 graphical objects 6 3 history junction overview 6 40 history junctions and inner transitions overview 6 41 how is the notation checked 6 3 inner transition overview 6 27 keywords 6 5 motivation for 6 2 nongraphical objects 6 4 representing hierarchy 6 6 self loop transition overview 6 31 state during action 6 15 entry action 6 14 exit action 6 15 labeling example 6 14 name 6 14 on action 6 15 transition label example 6 18 labeling 6 18 valid label 6 19 transition definition 6 17 transition label condition 6 18 condition action 6 19 event 6 18 transition action 6 19 transition types 6 20 Index 0 on keyword 2 26 P parallel AND s
84. page 6 59 and Example Directed Event Broadcast Using Qualified Event Names on page 6 60 for examples using thes end action language function Optimizing for Code Size Simplifying Stateflow diagrams results in less generated code The fewer transitions the simpler the Stateflow diagram is Use of hierarchy history junctions and inner transitions reduces the number of transitions In this example if event Reset occurs and any substate of Run is active you want to exit and re enter that same substate For example when the substate Using the N otation Efficiently is re entered its entry action is executed This example uses many transitions to represent the logic Emergency_stop This is an equivalent simpler Stateflow diagram that uses an inner transition toa history junction to optimize for code size Reset Two Optimizing for Memory Use The use of flow diagram notation in a Stateflow diagram can produce efficient code optimized for memory use In some cases specifying actions using flow diagram notation is a closer representation of the system s logic and avoids the use of unnecessary states Reducing the number of states optimizes for memory use 9 9 9 Generating Code 9 10 This example shows the use of flow diagram notation to represent a for loop E_one i 0 et i lt 10 i funct gt fp The transition from state A to state B is divided into segments Two
85. press the Escape key to exit the edit You label onetransition in this step To move a transition label click and drag the left mouse button to the new desired location and then release the mouse button If you mistakenly 8 16 Procedure click and release the left mouse button you will bein label edit mode Dese lect the label and try again 2 Label the remaining transitions in thePower _on Ri de superstate You label three transitions in this step 3 Label thetransitions in theTi mer superstates You label two transitions in this step 4 Label the transitions to and from the Power _of f substate You label two transitions in this step Sample Snapshot Your Stateflow diagram should now look similar to this Stateflow diagram Power_on Switch_on an er i Speed gt Max_speed i Power_off ni von 4 Start_button _ E n Stop Me Switeh_off iya Ride_done Li Emergency_stop i Create Default Transitions There are three Default transitions in the solution Stateflow diagram Double click on the Default transition button in the toolbar The button appears depressed and is now in multiple object mode U sing the sample solution as a guide place the default transitions in the drawing area 8 17 8 Tutorial Entering a Stateflow Diagram This is the final step in creating the graphic objects in the Stateflow diagram Sample Snapshot Your Stateflow diagram should now look similar to this State
86. properties dialog box Select Explore from the graphics editor Tools menu to display the E xplorer Select the chart in the Object Hierarchy that you want to be the event s parent Choose New and then Event from the E xplorer File menu The Event properties dialog box is displayed Replace the contents of the name field with the namefan_off Click on the Close button to save the changes and close the Event properties dialog box Add define and save the remaining Local events Heat_on andHeat_off using either the Add menu or the Explorer What Is the Data There is one Local data object count in the Stateflow diagram count is used as a timer variable Tostart with count is zeroandTi mer Of f is active When Example G etting Started Adding Events and Data any event occurs the transition fromTi mer Of f toTi mer On is valid and the Local event Fan_on is broadcast When count becomes greater than ten the transition fromTi mer On toTi mer Of f is valid and the Local event Fan_off is broadcast Adding Local Data When you create the graphical objects in the Stateflow diagram you use the data nameas part of state actions and a transition label Adding them as labels and actions does not define them as data objects in the data dictionary Use either the graphics editor Add menu or the Explorer to add and define data 1 2 Select Explore from the graphics editor Tools menu to display the E xplorer Select th
87. should be disabled for RTW and stand alone targets The overhead incurred from the added instrumented code is undesirable in these targets Enabling most of the dynamic checking options adds instrumentation code to the target See Enable Dynamic Checker Options on page 9 24 and Dynamic Checker Options on page 10 10 for more information Compile Build Options Using Stateflow and Stateflow Coder you can easily define build and manage a variety of targets using the Explorer and the Target configuration dialog boxes These options exist for compiling code and building targets e sf un simulation target generation Stateflow generates the simulation target Stateflow and Simulink are required There is a singles fun target provided by default with Stateflow The target code in this caseis an S function MEX file See the Using Simulink document for information on S functions See Customizing the Target on page 9 20 and Compiling Building a Simulation Target on page 9 27 for more information RTW target generation RTW generates the target including code generated from Stateflow Coder Stateflow Stateflow Coder Simulink and RTW are required Buildinga RTW target is an example of a prototype target See Customizing the 9 3 9 Generating Code Target on page 9 20 and Compiling Building Targets with RTW on page 9 27 for more information Stand alone nonsimulation non RTW target generation
88. size or to the right to increase the arrowhead size The numeric display adjusts to show the currently selected arrowhead size Moving Transition Labels You can move transition labels to make the Stateflow diagram more readable To move a transition label click on and drag the label to the new location and then release the mouse button If you mistakenly click and release the left mouse button on the label you will be in edit mode Press the Escape key to deselect the label and try again 2 35 2 Using the Graphics Editor Editing Transition Properties Select a transition and click the right mouse button on that transition s border to display the Transition shortcut menu Choose Properties to display the Transition properties dialog box a Transition 2 36 W orking with Transitions This table lists and describes the transition object fields Field Description Source Source of the transition read only click on the hypertext link to bring the transition source to the foreground Destination Destination of the transition read only click on the hypertext link to bring the transition destination to the foreground Parent Parent of this state read only click on the Debugger breakpoints Label Description Document Link hypertext link to bring the parent to the foreground Click on the checkboxes to set debugging breakpoints either when the transition is tested for validity or when it i
89. substate the entry into its substate s is controlled by the transition path explicitly The default paths of the superstate are not processed Tutorial Entering a Stateflow Diagram Overview 2 2 eee a 8 2 Designing the Carousel Stateflow Diagram 8 4 Procedure 2 2 55 4 8 8 Run the Simulation for the Provided Solution 8 24 Run the Carousel Demo 8 Tutorial Entering a Stateflow Diagram 8 2 Overview Objectives After completing this tutorial you should be able to e Understand the Stateflow diagram design process for the carousel e Understand the notation and methods to create a model and Stateflow dia gram using Stateflow e Create an initial model and Stateflow diagram of the carousel e Run the simulation using the provided solution e Run the demo of the solution Provided Models for This Chapter The files associated with the tutorial example the running solution and the demo are included and accessible from the Examples block Carousel Tutorial Example A carousel is a familiar reactive system that you can model with a Stateflow diagram The system reacts based upon the operator s actions This tutorial focuses on learning the notation and the methods to create an initial Stateflow diagram for the carousel The completed tutorial example cannot be simulated The provided solution includes a Simulink model and can be simulated The demo is more elaborate and shows
90. the Event property dialog box sf_ev_d_ports_ex File Edit Simulation Format Tools port 1 port 2 Step port 3 Three Input from Simulink events Either Edge triggered are defined Event Triggers A trigger defines how a Stateflow block s input and output events are handled in the context of their Simulink model The Trigger type indicates what kind of signal has meaning for the input or output event Trigger types fall into two general categories edge or function call triggered Each Stateflow block can have only one overall Trigger type 3 17 3 Events and Data 3 18 The Trigger property can have these values Either Edge Either a rising or a falling trigger where the control signal changes either from 0 to a nonzero value from a positive to a negative value or from a neg ative to a positive value Rising Edge A rising trigger where the control signal changes either from 0 toa positive value or from a negative to a positive value Falling Edge A falling trigger wherethe control signal changes either from 0 toa negative value or from a positive to a negative value Function Call A function call trigger operates essentially like a programming subroutine call When the system executes the step where the function call is specified the triggered subsystem executes and then returns to the next statement in the execution sequence Using function call triggers the Stateflow block can con
91. the Scope is Local The Scope options are displayed in a pull down menu The parent machine chart or state dictates the choice of Scope If the Scope you desire is not an available option for that parent type you may need to move the event so that it is parented by an object that supports that Scope 5 9 5 Exploring and Searching 5 10 If you move an object to a level in the hierarchy that does not support that object s current Scope property the Scope is changed to Local These are all possible options for the Scope property e Local e Input from Simulink e Output to Simulink e Exported Imported See Event Scope on page 3 10 for more information Port The Port field is relevent for events with Output to Simulink Scope The Port number options are displayed in a pull down menu See Event Ports on page 3 16 for more information Index The Index field is relevant for events with Input from Simulink Scope The Index number options are displayed in a pull down menu See Event Indices on page 3 16 for more information Trigger The Trigger field is relevant for events with Input from Simulink or Output to Simulink Scope otherwise the field is grayed out The Trigger options are displayed in a pull down menu A trigger defines how a Stateflow block s input and output events are handled in the context of their Simulink model Each Stateflow block can only have one overall Trigger type T
92. the hierarchy tothestatesfirst andsecond When the event cl ut ch engaged occurs the system transitions out of theneut ral statetotheengaged superstate Transitions within theengaged superstate are intentionally omitted from this example for simplicity A transition out of a higher level or superstate also implies transitions out of any active substates of the superstate Transitions can cross superstate boundaries to specify a substate destination If a substate is active its parent superstate is also active Conditions A condition is a Boolean expression specifying that a transition occurs given that the specified expression is true In the component summary Stateflow diagram condi tion1 represents a Boolean expression that must be true for the transition to occur 1 16 Anatomy of a Model and Machine In the automatic transmission system the transition fromfirst tosecond occurs if the Boolean condition speed gt threshold is true neutral Clutch_engaged engaged speed gt threshold History Junction History provides the means to specify the destination substate of a transition based on historical information If a superstate with exclusive OR decomposition has a history junction thetransition tothe destination substate is defined to be the substate that was most recently visited A history junction applies to the level of the hierarchy in which it appears The history junction overrides any default tr
93. the rate you specify An implicit event is generated by Simulink at regular time intervals corresponding to the specified rate The sample time is in the same units as the Simulink simulation time Note that other blocks in the Simulink model may have different sample times Continuous Simulink will awaken sample the Stateflow block at each step in the simulation as well as at intermediate time points that may be requested by the Simulink solver This method is consistent with the continuous method in Simulink See Using Simulink for more information on these types of Simulink subsystems Defining the Stateflow Block Update M ethod Defining a Triggered Stateflow Block These are essential conditions that define an edge triggered Stateflow block e The chart Update method set in the Chart Properties dialog box is set to Triggered or Inherited See Editing Chart Stateflow Diagram Properties on page 2 19 e The chart has an Input from Simulink event defined and an edge trigger type specified Events are added and defined using either the graphics editor Add menu or the Explorer See Add M enu on page 2 48 or Tasks to Define an Event Input from Simulink on page 4 16 Example Triggered Stateflow Block A Pulse Generator block connected to the trigger port of the Stateflow block is an example of an edge triggered Stateflow block The Input from Simulink event has a Rising Edge trigger type sf_triggered_ex io
94. the specified state is entered The shorthand notation isen state name exit state name Generates a local event when the specified state is exited The shorthand notation isex state name change data_obj ect_name Generates a local event when there is a change to the numeric value of the specified data object name The shorthand notation is chg data_obj ect_name Implicit Local Events Example Implicit Local Event This example uses the implicit local evententry state_ name nn nen be nee ee een F Fan o Heater Et On On en Fan Off Fan_switch g Fan_switch en Fan On Fan andHeater areparallel AND superstates By default the first time the Stateflow diagram is awakened by an event the states Fan Of f and Heater Of f become active The first time event Fan_switch occurs the transition from Fan Off toFan On occurs When Fan 0n s entry action executes an implicit local event is broadcast ie en Fan 0n 1 This event broadcast triggers the transition from Heater Off toHeater On guarded by the condition en Fan On Similarly when the system transitions from Fan On toFan Off and the implicit local event Fan Of f is broadcast the transition fromHeater On toHeater Of f is triggered guarded by the condition en Fan Off 3 21 3 Events and Data Data 3 22 What Is a Data Object Data objects are numerical values in the Stateflow
95. thereis a valid transition at the root level as a result of E_ one There is no valid transition 2 State A executes and completes during actions dur A 3 State A s children are parallel AND states They are evaluated and exe cuted from left to right and top to bottom Stated Al is evaluated first State A A1 executes and completes during actions dur A1 StateA A1 executes and completes theon E_one action and broadcasts event E_two during and on event_name actions are processed based on their order of appearance in the state label a The broadcast of event E_t wo awakens the Stateflow diagram a second time The Stateflow diagram root checks to see if there is a valid transi tion as aresult of E_t wo Thereis no valid transition b State A executes and completes during actions durA c State A checks its children for valid transitions There are no valid tran sitions d StateA s children are evaluated starting with stateA A1 StateA Al exe cutes and completes during actions dur A1 StateA A1 is evaluated for Parallel AN D States valid transitions There are no valid transitions as a result of E_t wo within state Al e StateA A2 is evaluated Stated A2 executes and completes during actions dur A2 State A A2 checks for valid transitions State A A2 has a valid transition as a result of E_t wo from stateA A2 A2a tostateA A2 A2b f StateA A2 A2a exit actions execute and complete exit A2a Sta
96. titled Example Transitions from Multiple Sources toa Common Destination on page 7 40 for information on the semantics of this notation Example Connective J unction Common Events Suppose for example that when event e1 occurs the system whether it isin stateA or B will transfer tostatec Suppose that transitions AC andB gt C are triggered by the same event e1 sothat both destination state and trigger event are common between the transitions There are three ways to represent this e By drawing transitions from A and B toC each labeled with e1 e By placingA andB in onesuperstates and drawing onetransition froms to c labeled with e1 e By drawing transitions from A and B to a connective junction then drawing one transition from the junction toC labeled with e1 6 38 Connective Junctions This Stateflow diagram shows the simplification using a connective junction See the section titled Example Transitions from a Source to a Destination Based on a Common E vent on page 7 41 for information on the semantics of this notation 6 39 6 Notations History What Is a History J unction A history junction is used to represent historical decision points in the Stateflow diagram The decision points are based on historical data relative to state activity Placing a history junction in a superstate indicates that historical state activity information is used to determine the next state to become ac
97. to bring the Simulink subsystem to the foreground Parent Parent name read only click on this hypertext link to display the parent s property dialog box Update Method Choose from Triggered or Inherited Sampled or Continuous Sample Time If Update Method is Sampled enter a sample time Debugger breakpoint Click on the checkbox to set a debugging breakpoint On chart entry Editor Click on the Locked checkbox to mark the Stateflow diagram as read only and prohibit any write operations Description Textual description comment Document Link Enter a web URL address or a general MATLAB command Examples are www mat hworks com mailto email _address edit spec data speed txt Click on the Apply button to save the changes Click on the Revert button to cancel any changes and return to the previous settings Click on the Close button to save the changes and close the dialog box Click on the Help button to display the Stateflow online help in an HTML browser window 2 20 W orking with Charts Stateflow Diagrams Chart Hyperlinks Example This is an example of a chart properties dialog box a Chart action_ex Hypertext link to the chart Triggered or Inherited Sample Iime E m Click on the hypertext in the Name field The chart is brought to the foreground 2 21 2 Using the Graphics Editor Chart Update Methods The chart is awakened when an event occurs You can choose from these me
98. to define an Exported event You have purchased a communications pager There area few people you want to be able to page you so you give those people your personal pager number These people now know your pager number and can call that number and page you whatever you might be doing Y ou do not usually page yourself but you can do so Telling someone the pager number does not mean they have heard and recorded the number It is the other person s responsibility to retain the number Similarly you may want an external source outside the Stateflow diagram the machine and the Simulink model to be able to broadcast an event By defining an event s scope to be Exported that event is made available to external sources for broadcast purposes Exported events must be parented by the machine because the machine is the highest level in the Stateflow hierarchy that can interface to external sources The machine also retains the ability to broadcast the Exported event Exporting the event does not imply anything about what the external source does with the information It is the 3 13 3 Events and Data responsibility of the external source to include the Exported event in the manner appropriate to the source to make use of the right to broadcast the event If the external source is another machine most common scenario then one machine defines an Exported event and the other machine defines the same event to be Imported Stateflow gener
99. whether the speed is in the normal or overspeed range Procedure Follow these steps to run the demo 1 Double click on the Examples block in the Stateflow model window Double click on the Carousel and then Multi Media Carousel block 2 Choose Start from the graphics editor Simulation menu The first time you run the simulation and any time you have modified the Stateflow diagram choosing Start will parse the machine generate simulation code and generate the simulation target If the target build takes 8 27 8 Tutorial Entering a Stateflow Diagram 8 28 place informational messages are displayed in popup windows and in the MATLAB command window In any case the graphics editor is I CE D and modifications to the Stateflow diagram are prohibited during a simulation 3 Turn the power on by clicking the power switch from off to on 4 5 8 Ensure that the running speed switch is in the normal position Click the start switch on to start the carousel The ride runs for Duration seconds but can be stopped prematurely by changing the running speed switch to overspeed or by clicking the emergency switch If you have sound support Sound board driver and speakers you should hear the music You should also see a representation of the carousel platform rotating in XY Graph figure window The Stateflow diagram has animation enabled so you can see the state transitions occur as the simulation executes Click the
100. which Stateflow executes a subsystem essentially outside of Simulink s direct control Use a function call trigger to have the Stateflow block control the execution of the connected Simulink block Function call subsystems are never executed directly by Simulink See these examples for more information e Example Using Function Call Output Events on page 4 11 e Example Function Call Semantics on page 4 12 e Example Edge Triggered Semantics on page 4 13 Defining Function Call Output Events These are essential conditions that define the use of function call output events The chart has an Output to Simulink event with a Function Call trigger type defined added and defined using either the graphics editor Add menu or the Explorer See Add Menu on page 2 48 or Stateflow Explorer User Interface on page 5 5 for more information The Simulink block connected to the function call event Output to Simulink has the Trigger type field set to function call Stateflow blocks that have feedback loops from a block triggered by a func tion call should avoid placing any other blocks in the connection lines between the two blocks Defining O utput to Simulink Event Triggers Example Using Function Call Output Events A function call trigger operates essentially like a programming subroutine call When the system executes the step where the function call is specified the triggered subsystem executes and then
101. will produce speed efficient code Taking advantage of the ability to specify an event s parent within the hierarchy provides speed optimizations You can make sure that an event s broadcast scope is as specific as possible to avoid unnecessary event broadcasting See Events on page 3 5 and Event Inputs from Simulink on page 4 16 for more information Y ou can also use thes end action language function to further qualify the receiver of an event broadcast directed event broadcasting See Directed Event Broadcasting on page 6 58 for more information 9 7 9 Generating Code This example Stateflow diagram shows the use of top down event processing to optimize the event handling speed Run_on Two Emergency_stop If the emergency stop button is pushed the event Emergency_stop occurs and the system should transition to the St op state as quickly as possible By drawingtheEmergency_stop transition from theRun superstate border to the Stop state the transition is evaluated at the highest level in the hierarchy Using this notation if any of Run substates are active and theEmer gency stop event occurs the system transitions to theSt op state The alternative to this notation is to have individual transitions originating from a lower level in the hierarchy from each of Run s substates The event handling of the alternative is less speed efficient See Example Directed Event Broadcast Using send on
102. you might want to accomplish e Animate Stateflow diagrams set breakpoints and debug runtime errors e If you are licensed for the Stateflow Dynamic Checker you can detect these conditions Evaluate code coverage State inconsistencies Conflicting transitions Data range violations Cydic behavior Including Debugging in the Target Build These debugging options require supporting code additions to the target code generated e State inconsistency e Transition conflict e Data range violations Toinclude the supporting code for these debugging options e Enable debugging and animation in the appropriate Target Configuration properties dialog box e Enable the dynamic checking options of interest in the appropriate Target Configuration properties dialog box You must rebuild the target for any changes made to the settings in the Target Configuration properties dialog box to take effect See Stand Alone Targets on page 9 16 and Customizing the Target on page 9 20 for more information Breakpoints A breakpoint indicates where and when the Debugger should break execution of a Stateflow diagram The Debugger supports global and local breakpoints Global breakpoints halt execution on any occurrence of the specific type of 10 3 10 Debugging 10 4 breakpoint Local breakpoints halt execution on a specific object instance When simulation execution is halted at a breakpoint you can e Examine the curr
103. 2 What Are Semantics ananassa aaaeeeaa 7 2 List of Semantic Examples 0000 c eee tees 7 2 Event Driven Effects on Semantics 7 5 What Does Event Driven Mean 0 000 ccc eee eee eee 7 5 Top Down Processing of Events 0 0 eee ences 7 5 Semantics of Active and Inactive States 05 7 5 Semantics of State ACtIONS 0 ccc eee 7 7 Semantics of Transitions 0 0 ccc ee ees 7 7 Transitions to and from Exclusive OR States 7 8 Example Processing of One Event 000 cece 7 8 Example Processing of a Second Event 05 7 9 Example Processing of a Third Event 0 000u 7 10 Example Transition from a Substate to a Substate 7 11 Condition Actions 0 0 00 0 00 0 cee eee 7 13 Example Actions Specified as Condition Actions 7 13 Example Actions Specified as Condition and Transition ACCIONS 3 oa seca nd vere ou eine aah aah ake Ra Pw ad CEAN 7 14 Example Using Condition Actions in For Loop Construct 7 15 Example Using Condition Actions to Broadcast Events to Parallel AND States 0 cece ee eee 7 16 Example Cyclic Behavior to Avoid When Using Condition ACtiONS 0 0 ccc eee eens 7 17 Default Transitions 0 0 0 c cece cee es 7 18 Example Default Transition in an Exclusive OR Decomposition 0 cece ee 7 18 Example Default Transit
104. 2 objects with actions 6 42 state action notation 6 43 time symbol 6 61 transition action notation 6 43 unary operations 6 47 6 48 use of the semicolon 6 62 user written functions 6 49 actions definition 1 18 glossary definition A 2 animation debugger control 10 10 enable 9 24 array arguments 6 56 assignment operations 6 48 B binary operations 6 45 bit operations 6 44 breakpoints global 10 3 chart entry 10 8 event broadcast 10 8 state entry 10 8 local 10 3 overview 10 3 C C compiler requirements xxii canceling operations 2 15 carousel run the demo 8 27 run the provided solution 8 24 Simulink model solution 8 24 solution procedure to run the simulation 8 25 Stateflow diagram 8 25 tutorial tasks 8 8 chapter quick reference xxvi chart Stateflow diagram debugger breakpoint property 2 20 description property 2 20 document link 2 20 editing chart properties 2 19 editor property 2 20 hyperlinks example 2 21 name property 2 20 operations 2 18 overview 2 18 parent property 2 20 printing large 2 23 sample time property 2 20 Simulink subsystem property 2 20 update method property 2 20 update methods 2 22 update methods for defining interface 4 4 l 1 Index code generation adding and specifying a stand alone target 9 16 coder file 9 5 error messages 9 32 notations to optimize code size 9 8 notations to optimize memory use 9 9 notations to optimize speed 9 7 stand alone target 9 16 typical sequence 9
105. 4 is true The transition from stated tostatec is validifthecondition b lt 7 istrue Asthesimulation proceeds there is a point where state A is active and both conditions are true This is a transition conflict Multiple outgoing transitions from states that are of equivalent label priority are evaluated in a clockwise progression starting from the 12 o clock position on the state In this example the transition from stated tostateB is taken Although the geometry is used to continue after the transition conflict it is not recommended to design your Stateflow diagram based on an expected execution order 10 19 10 Debugging Debugging Data Range Violations What is a Data Range Violation Each Data property dialog box has fields for an Initial Minimum and Maximum value If the data object equals a value outside of this range enabling data range checking will detect the error Detecting Data Range Violations To detect data range violations during a simulation e Enable Debugging Animation and Data Range Checking in the Target Configuration sfun property dialog box e Build the target with the debugging options e Invoke the Debugger and enable Data Range checking e Start the simulation Example Data Range Violation This Stateflow diagram has a data range violation a 5 entry a 1 during a a a The data a is defined to have an Initial and Minimal value of 0 anda Maximum value of 2 Each time a
106. 8 TheStateflow diagram goes back tosleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one Connective Junctions Example Flow Diagram Notation This example shows the semantics of a Stateflow diagram that uses flow notation State Al is active C_oneQ Initially the Stateflow diagram is asleep Stated A1 is active The condition C_one is initially true Event E_one occurs and awakens the Stateflow diagram EventE_one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_one Thereis no valid transition 2 Stated checks itself for valid transitions and detects a valid inner transition to a connective junction 3 Thenext possiblesegments of thetransition are evaluated Thereis only one outgoing transition and it has a condition action defined The condition action is executed and completed 4 The next possible segments are evaluated There are two outgoing transi tions one is a conditional self loop and the other is an unconditional transi tion segment The conditional transition segment takes precedence The condition C_one istested and is true the self loop is taken Sincea final 7 37 7 Semantics 7 38 8 9 transition destination has not been reached this self loop co
107. A1b executes and completes entry actions ent A1b 10 Parallel stateA A2 is evaluated next StateA A2 during actions execute and complete dur A2 There are no valid transitions as a result of E_one 11 State A A2 A2b now active as a result of the processing of the transition action event broadcast of E_t wo executes and completes during actions dur A2b 12 TheStateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one and thetransition action event broadcast to a parallel state of event E_t wo The final Stateflow diagram activity now looks like this Al entry entA during durA exit exitA i entry entAi during durA1 exit exitA1 11 entry entA2 11 during durA2 exit exitA2 i A2at Ala ri entry entA lat Vt any m a vt during durA2a during durAta exit exita2a exit exitAla E_one E_two StateA1b i A2b i State A2b is active i entry entA1b 1i entry entA2b k during durA1b 11 during durA2b is active exit exit 1b rt exit exitA2b 7 53 7 Semantics 7 54 Example Event Broadcast Condition Action This example shows the semantics of condition action event broadcast in parallel AND states State Ala is active A entry entAg during durAg exit exitAG entry entA1 during d
108. AND decomposition A B and X Y Using combination state notation the activity of the Stateflow diagram is denoted by A B X Y A state is characterized by its label The label consists of the name of the state optionally followed by a character and additional keywords defined below The label appears on the top left hand corner of the state rectangle 6 12 States Labeling a State The character is the default state label State labels have this general format name entry during exit on event _name The keywords entry shorthand en during shorthand du exit shorthand ex and on identify actions associated with the state You can specify multiple actions by separating them by any of these e Carriage return e Semicolon Comma Specify multipleon event _name actions for different events by adding multiple on event_name lines specifying unique values for event _name Each keyword is optional and positionally independent Y ou can specify none some or all of them The colon after each keyword is required The slash following the state name is optional as long as it is followed by a carriage return If you enter the name and slash followed directly by an action or actions without theent ry keyword the action s are interpreted as entry action s This shorthand is useful if you are only specifying ent ry actions See the section titled What Is an Action Language on page 6 42 for more infor
109. Add any customized code that you want to be prepended to the generated target code in the Custom Code field e Specify a document link Once you have made the customizations click on the Apply button to save changes Click on the Revert button to remove changes and reset the fields with the previous values Click on the Close button to apply changes and close the window Customizing the Target Displaying the Target Configuration sfun Dialog Box Choose Open Simulation Target from the graphics editor Tools menu to display the Target Configuration sfun dialog box a Stateflow Target Configuration sfun Simulink S Fu oO x 9 21 9 Generating Code Displaying the Target Configuration rtw Dialog Box Choose Open RTW Target from the graphics editor Tools menu to display the Target Configuration rtw dialog box a Stateflow Target Configuration rtw Default RTW target DiE Revert 9 22 Customizing the Target Displaying the Target Configuration Dialog Box Choose Explore from the graphics editor Tools menu to display the Explorer Double click on the target you want to customize to display the Target Configuration dialog box Coder Command Customization You can add bi tops tothe code generation command in the Coder Command field to enable C like bit operations Removing the bi tops disables C like bit operations C like bit operations are disabled by default See Action Language on page
110. B command window a Stateflow Parser 2 Fix the parse error In this example there are two states with the name A Edit the Stateflow diagram and label the duplicate state with the text 8 The Stateflow diagram should look similar to this 3 Reparse Choose Parse Diagram from the graphics editor Tools menu This message is displayed in the popup and the MATLAB command window EJ Stateflow Parser 9 13 9 Generating Code 9 14 4 Fix the parse error In this example the state with the question mark needs to be labeled with at least a state name Edit the Stateflow diagram and label the state with the text C The Stateflow diagram should look similar to this 5 Reparse Choose Parse Diagram from the graphics editor Tools menu This message is displayed in the popup window and the MATLAB command window Stateflow Parser 6 Fix the parse error In this example the transition label contains a syntax error The closing bracket of the condition is missing Edit the Stateflow diagram and add the closing bracket so that the label isE_one C_one Parsing Reparse Choose Parse Diagram from the graphics editor Tools menu This message is displayed in the popup window and the MATLAB command window m Stateflow Parser The Stateflow diagram has no parse errors 9 15 9 Generating Code Adding and Specifying a Stand Alone Target 9 16 Stand Alone Targets The Stateflow Coder
111. Create a Simulink Model These steps describe how to invoke Stateflow and save the untitled model and Stateflow diagram 1 Double click on the MATLAB icon to invoke MATLAB 2 At the MATLAB prompt types f new to display an untitled model window Choose Save As from the File menu of the model window Enter a unique model name modify the saved location if desired and click on the OK button 3 Click in the text area of the Stateflow block and enter a unique Stateflow block name Double click on the Stateflow block to invoke the Stateflow graphics editor 8 9 8 Tutorial Entering a Stateflow Diagram Sample Stateflow Diagram This is a sample of what the completed Stateflow diagram should look like Power_on Switch_on ee n a Speed gt Max_speed On lt Start_button CLES Emergency_stop A TEA OEE A E A AA A E EEE EKO p Time gt Duration Ride_done _ a Switch_off Start_button Create and Label the OR States 1 Double click on the State button B in the toolbar The button appears depressed and is now in multiple object mode U sing the sample solution Stateflow diagram as a guide click in the drawing area to place the states in the drawing area The Stateflow diagram is exclusive OR decomposition 8 10 Procedure by default so you do not need to change the decomposition The states cor respond to these states in the solution Power off Power _on
112. Defining the Interface to External Sources What Are External Sources Any code that is not part of a Stateflow diagram the Stateflow machine nor the Simulink model is considered external You can include external source code in either e the Make Command of the Target Configuration dialog box See Make Command Customization on page 9 23 for more information e the Custom Code section of the Target Configuration dialog box See Add Customized Code on page 9 25 See Chapter 3 Events and Data for conceptual information on events and data See Stateflow E xplorer User Interface on page 5 5 for more information on adding and defining events Exported Events Consider a real world example to clarify when to define an Exported event You have purchased a communications pager There area few people you want to be able to page you so you give those people your personal pager number These people now know your pager number and can call that number and page you whatever you might be doing Y ou do not usually page yourself but you can do so Telling someone the pager number does not mean they have heard and recorded the number It is the other person s responsibility to retain the number Similarly you may want an external source outside the Stateflow diagram the machine and the Simulink model to be able to broadcast an event By defining an event s scope to be Exported that event is made available to externa
113. Escape key to deselect all Stateflow diagram objects 2 Double click on the Zoom Factor Selector to fit the Stateflow diagram to the page 3 Choose Print from the File menu or enter a print command from the MATLAB commandline Pressing the Ctrl and P keys simultaneously is the keyboard equivalent to the Print menu item See the section titled File Menu on page 2 43 for more information on printing from the editor window Sees f print in the Reference chapter for more information about printing from the command line 2 23 2 Using the Graphics Editor 2 24 Working with States What Can You Do with States You can Specify decomposition Create delete Label Group ungroup Show hide Resize Change font size Change arrowhead size Move Invoke the state properties dialog box to Usethe hypertext link to the state or the parent Specify debugger breakpoints Add or modify the label Add a description Link toa document Specifying Decomposition States that contain other states are called superstates A superstate has either Parallel AND or Exclusive OR decomposition The decomposition of the Stateflow diagram can be set if it contains at least one state Specify state decomposition by selecting the superstate and choosing either the Parallel AND or Exclusive OR menu items from the right mouse button shortcut menu In the case of the Stateflow diagram display the shortcut menu by click
114. License File or Personal License Password from The MathWorks The License File or Personal License Password identifies the products you are permitted to install and use As the installation process proceeds a screen similar to this where you can indicate which products to install is displayed Select MATLAB components Xi A check mark beside an item means you wish to install it Clicking in the box will toggle the check mark Only help items you install will be in HelpDesk To use help from the CD select no items Components vI SIMULINK v Simulink help PDF 2448 K v Simulink help HTML 6992 K vV Stateflow 7264 K v Stateflow help PDF 16K Stateflow help HTML 5520K v Stateflow Coder 592K Real Time Workshop 3328 Destination Directory caras Bosen Space Required 75760K Space Available 575040 K Disk pace lt Back Next gt Cancel Installation Stateflow and Stateflow Coder have certain product prerequisites that must be met for proper installation and execution Licensed Prerequisite Additional Information Product Products Simulink 2 2 MATLAB 5 2 Allows installation of Simulink and Stateflow in Demo mode Stateflow Simulink 2 2 Requires a C or C compiler for creating MATLAB ME X files on your platform see page xxii Stateflow Stateflow Same as Statefl ow Coder If you experience installation difficulties and
115. One Before Using an Inner Transition 6 27 Example One Inner Transition to a Connective unction 628 Example Two Before Using an Inner Transition 6 29 Example Two Inner Transition to a Connective unction 6 29 Example Inner Transition toa History J unction 6 30 What Is a Sef Loop Transition 00 022 ee ae 6 31 Connective unctions anaua 6 32 What Is a Connective unction 0 0 ce ee 6 32 What Is Flow Diagram Notation 200000 6 32 Example Connective J unction with All Conditions Specified 6 33 Example Connective J unction with One Unconditional TRANSITION es ce Bde as eden wad Ra ae SN eek ed ee 6 33 Example Connective unction Special Case Self Loop 6 34 Example Connective unction and For Loops 6 35 Example Flow Diagram Notation 20000 6 36 Example Connective J unction from a Common Source to Multiple Destinations 0 0 c eee eee 6 37 Example Connective unction Common Destination 6 38 Example Connective unction Common Events 6 38 HIStory occ scenes kean Sein DAME MO Alia Baa Dulas weeded RS 6 40 What Is a History J unction 0 000 6 40 Example Use of History J unctionS 00 cee eae 6 40 History J unctions and Inner Transitions 6 41 Action Language cece ete teens 6 42 What Is an Action Language
116. Ride On Power_on Ride Stopped Power_on Timer Stopped e Power _on Timer Counti ng Press the Escape key or click on the State button to toggle the button out of multiple object mode 2 Click on the character within each state to enter each state label The final text after the last period is the individual state s name There are some states that have the same text as their label This is ok since the hierarchy of the state is used to create a unique label For example both theRi de and Ti mer Superstates haveaSt opped substate Reading the Stateflow diagram you can see that these states are uniquely described by the text Power_on Ride Stopped andPower_on Timer Stopped Use the sample solution to label the states based on their placement in the drawing area Deselect the state press the Escape key to exit the edit Sample Snapshot Your Stateflow diagram should look similar to this Stateflow diagram 8 11 8 Tutorial Entering a Stateflow Diagram Power_off Stopped P m Counting 8 12 Procedure Create and Label the Superstates Tocreatea superstate create a state and resize so that it includes or surrounds the desired substates These steps show how to create and label the superstates 1 Click on the State button B from the toolbar U sing the sample solution as a guide place the Ri de superstate in the drawing area Resize the state to create the superstate Dragging any one of the state s c
117. STATEFLOW_ for Use with Simulink Modeling Simulation Implementation User s Guide Version 1 X OD oe 6 How to Contact The MathWorks 508 647 7000 Phone 508 647 7001 Fax The MathWorks Inc Mail 24 Prime Park Way Natick MA 01760 1500 http www mathworks com Web ftp mathworks com Anonymous FTP server comp soft sys matlab Newsgroup support mat hworks com Technical support suggest mat hworks com Product enhancement suggestions bugs mat hworks com Bug reports doc mathworks com Documentation error reports subscribe mathworks com Subscribing user registration service mathworks com Order status license renewals passcodes info mat hworks com Sales pricing and general information Stateflow User s Guide COPYRIGHT 1997 1998 by The MathWorks Inc All Rights Reserved The software described in this document is furnished under a license agreement The software may be used or copied only under the terms of the license agreement No part of this manual may be photocopied or repro duced in any form without prior written consent from The MathWorks Inc U S GOVERNMENT If Licensee is acquiring the Programs on behalf of any unit or agency of the U S Government the following shall apply a For units of the Department of Defense the Government shall have only the rights specified in the license under which the commercial computer software or commercial software documentation was obtained as set forth
118. Stateflow For more information see the Using Simulink document Semantics Semantics describe how the notation is interpreted and implemented behind the scenes A completed Stateflow diagram communicates how the system will behave A Stateflow diagram contains actions associated with transitions and states The semantics describe in what sequence these actions take place during Stateflow diagram execution Simulink Simulink is a software package for modeling simulating and analyzing dynamic systems It supports linear and nonlinear systems modeled in contin uous time sampled time or a hybrid of the two Systems can also be multirate i e have different parts that are sampled or updated at different rates It allows you to represent systems as block diagrams that you build using your mouse to connect blocks and your keyboard to edit block parameters Stateflow is part of this environment The Stateflow block is a masked Simulink model Stateflow builds an S function that corresponds to each Stateflow machine This S function is the agent Simulink interacts with for simulation and analysis The control behavior that Stateflow models complements the algorithmic behavior modeled in Simulink block diagrams By incorporating Stateflow diagrams into Simulink models you can add event driven behavior to Simulink simulations You create models that represent both data and control flow by combining Stateflow blocks with the standard Simul
119. Stateflow Coder generates the target Stateflow and Stateflow Coder are required Using Stateflow Coder you can create multiple targets using specific compilers for prototyping or production use on particular hardware platforms See Adding and Specifying a Stand Alone Target on page 9 16 Customizing the Target on page 9 20 and Compiling Building Stand Alone Targets on page 9 28 for more information Typical Tasks to Generate Code These are some typical code generation tasks you might want to accomplish e Create a Stateflow diagram using the notation efficiently knowing the semantics for code generation e Parse the machine e Add and specify a stand alone target e Customize the target e Compile code and build a target O verview Typical Code Generation Sequence This diagram shows a typical progression from model creation to generated executable assuming you are generating code for a stand alone target Parser Stateflow Explorer Stateflow Coder target code Compiler Parse the model invoke via Tools menu or Target dialog box Add a target and customize the commands that generate target code in the Target Configuration dialog box invoke via Tools or any shortcut menu Generate code invoke explicitly via the Target Configuration dialog box or implicitly via Start menu item on the Simulation menu Generate executable explicitly invoke the compiler via the Target Configuration dialog bo
120. _one is processed from the 7 21 7 Semantics 7 22 root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_one There is valid transition from state A to superstateB State A exit actions execute and complete exi t A State A is marked inactive State B is marked active State B entry actions execute and complete ent B StateB detects and uses the history junction to determine which substate is the destination of the transition into the superstate The history junction indicates substate B B4 was the last active substate and thus the destina tion of the transition State B B4 is marked active State B B4 entry actions execute and complete ent B4 The Stateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one Default Transitions Example Labeled Default Transitions This example shows the use of a default transition with a label State is active entry enta E_onelE_two B entry entB during durB exit exitB E_one B1 entry entB1 during durB1 during durA exit exitA E _two B2 entry entB2 during durB2 exit exitB2 exit exitB1 Initially the Stateflow diagram is asleep Stated is active Even
121. a Parent Types 0 cece es 3 25 Data Hierarchy and Scope 0 0c eee eee 3 26 Data SCOPE iinet eid alae k w wt eatin ata eA ar a ale 3 27 Table of Data Scope and Parent Combinations 3 32 PALA POPES i ig iin eh esar om hal eacetw E oan Taam aa 3 32 Data Attributes 0 ee eee 3 33 Overview 2 60 e tenet e en ees 4 2 Interfaces to Stateflow 1 0 cee eens 4 2 Typical Tasks to Define Stateflow Interfaces 4 2 Where to Find More Information on Events and Data 4 3 Defining the Stateflow Block Update Method 4 4 Stateflow Block U pdate Methods 000 0 eee 4 4 Defining a Triggered Stateflow Block 0 0c eee 4 5 Example Triggered Stateflow Block 00 00 cee eee 4 5 Defining a Sampled Stateflow Block 00 000 eee eee 4 5 Example Sampled Stateflow Block 000 e eee eee 4 6 Defining an Inherited Stateflow Block 00 00a 4 6 Example Inherited Stateflow Block 0 00000 cee eee 4 7 Defining a Continuous Stateflow Block 000 4 7 Considerations in Choosing Continuous Update 4 7 Example Continuous Stateflow Block 00 eae 4 8 Defining Output to Simulink Event Triggers 4 10 OVE VIEW s ira me ae Ledeen Ee SY ee es 4 10 Defining Function Call Output Events 0 4 10 Example Using Function Call Output Events 4 11 Example Func
122. a input from Simulink e Add a data object choosing a chart as the parent of the data e Choose Input from Simulink as the Scope e Specify data attributes e Apply and save the changes Add a Data Object Choosing a Chart as the Parent These steps describe how to add a data object 1 Choose Explore from the graphics editor Tools menu to invoke the Explorer 2 Select a chart object in the hierarchy that you want to be the data object s parent You must explicitly choose a parent to create a data object Choosing the Chart to be the parent determines that the data resides within the chart 3 Choose Data from the Explorer Add menu The Data properties dialog box is displayed 4 Enter anamein the Name field Choose Input from Simulink as the Scope Once you have chosen the chart as the parent the choice of valid scopes includes Local Input from Simulink Output to Simulink Temporary or Workspace Choose Input from Simulink as the Scope to enable access rights to Simulink and any offspring of the chart Data Inputs from Simulink When you add a data input each data input is represented on the Stateflow block by a Simulink input port Multiple data inputs to the Stateflow block must be scalar they cannot be vectorized Specify Data Attributes If you want to change the defaults you can specify data Units Type Initial Minimum and Maximum values Apply and Save the Changes Click on the Apply button to save th
123. ack to itself Transitions from a common source to muliple destinations Transitions from multiple sources to a common destination Transitions from a source to a destination based on common events See the section titled Event Actions on page 7 43 for asummary of the semantics of connective junctions What Is Flow Diagram Notation Flow diagram notation is essentially logic represented without the use of states In some cases using flow diagram notation is a closer representation of the system s logic and avoids the use of unnecessary states Flow diagram notation is an effective way to represent common code structures likef or loops andi f then else constructs The use of flow diagram notation in a Stateflow diagram can produce more efficient code optimized for memory use Reducing the number of states optimizes memory use Flow diagram notation is represented through combinations of self loops to connective junctions transitions to and from connective junctions and inner transitions to connective junctions The key to representing flow diagram notation is in the labeling of the transitions specifically the use of action language Flow diagram notation and state to state transition notation seamlessly coexist in the same Stateflow diagram Connective Junctions Example Connective J unction with All Conditions Specified When event e occurs state A transfers toD E or F depending on which of the conditions c1 c2 or
124. action that specifies the broadcast of event 1 event1 is defined in Stateflow to be an Output to Simulink with a Function Call trigger type The Stateflow block output port for event 1 is connected to the trigger port of theband pass filter1 Simulink block Theband pass filter1 block has its Trigger type field set to function call eventi w Bf entry x x y Defining O utput to Simulink Event Triggers This sequence is followed when stated is active and the transition from state A to state B is valid and is taken 1 Stated exit actions execute and complete 2 Stated is marked inactive 3 Thetransition action is executed and completed In this case the transition action is a broadcast of event 1 Becauseevent 1 iS an event Output to Simulink with a function call trigger theband pass filter1 block executes and completes and then returns to the next statement in the execution sequence The value of y is fed back to the Stateflow diagram 4 StateB is marked active 5 StateB entry actions execute and complete x x y Thevalueofy isthe updated value fromtheband pass filter1 block 6 TheStateflow diagram goes back tosleep waiting to be awakened by another event Defining Edge Triggered Output Events These are essential conditions that define the use of triggered output events e Thechart has an Output to Simulink event with one of these edge triggered types defined Either Edge Rising Edge Falling Edge Ev
125. actions for the active state are executed and completed and then a check for the existence of a valid explicit or implicit transition among the children of the state is conducted The examples in this chapter demonstrate the top down processing of events Semantics of Active and Inactive States This example shows the semantics of active and inactive states S Al entry entA during durA Q exit exitA Bi entry entBQ during durB exit exitBQ 7 Semantics 7 6 Initially the Stateflow diagram is asleep and both states areinactive An event occurs and the Stateflow diagram is awakened This is the semantic sequence 1 The Stateflow diagram root checks to see if there is a valid transition as a result of the event A valid default transition to state A is detected 2 Stated is marked active 3 Stated entry actions execute and complete ent A 4 TheStateflow diagram goes back tosleep waiting to beawakened by another event Event E_one occurs and the Stateflow diagram is awakened State A is active This is the semantic sequence 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_ one A valid transition is detected from state A to state B N State A exit actions execute and complete exi t A 3 Stated is marked inactive 4 StateB is marked active 5 StateB entry actions execute and complete ent B 6 TheStateflow diagram goes back to sleep t
126. age 6 42 for more information on the action language If no condition is specified the implied condition is always evaluated as true In this example if the condition of f_count 0 is true the condition action of f_count is immediately executed Transition Action The transition action is executed after the transition destination has been determined to be valid provided the condition if specified is true If the transition consists of multiple segments the transition action is only executed when the entiretransition path tothe final destination is determined as valid Precede the transition action with a backslash See the section titled Action Language on page 6 42 for more information on the action language In this example if the condition of f _count 0 is true and the destination state Of f is valid the transition action Li ght _off is executed What Is a Valid Transition In most cases a transition is valid when the source state of the transition is active and thetransition label is valid Default transitions areslightly different because there is no source state Validity of a default transition to a substateis evaluated when thereis a transition toits superstate assuming the superstate 6 19 6 Notations is active This labeling criteria applies to both default transitions and general case transitions These are possible combinations of valid transition labels Transition Label Is Valid If
127. al Events 0 0c cece eee eee eee eens 5 18 What Is the Data 0 ccc eens 5 18 Adding Local Data 0 cece ees 5 19 Stateflow Finder User Interface 5 20 Finder Dialog BOX 0 cece eee 5 20 Finder Display Area 0 0 cece eee 5 23 Searching for a Wildcard String 5 26 6 EXAMpPIG eeren dena bee y pa e eed oa ead enew eg ts 5 26 Searching for an Exact String Match 5 28 EX MPIG i ui ci cae hie im edie bw ek een Sod nee ie 5 28 Searching for All Objects of a Specified Object Type 5 30 Ex mipl vo er atia a eti i er ee 5 30 Searching Based on Multiple Conditions 5 32 EXAMpPle papp are dite He hae Bhs Baten n 4a wes e 5 32 Searching for an Object to Edit Properties 5 34 Example soris veered eee doe SERRE eee eERe Va Bee wee 5 34 Notations Overview 0 00 6 ct ttn ene ene 6 2 What Is Meant by Notation 0 00200 eee eee aes 6 2 Motivation Behind the Notation 200 eae 62 How Is the Notation Checked 0 2 0 e eee eee 6 3 What Are the Graphical Objects asasan 63 What Are the Nongraphical Objects 0055 6 4 What Is the Data Dictionary 0000 2c eee 6 4 KeywordS 2 0 c eee eee 65 How Is Hierarchy Represented 000c eee eaee 66 Example Representing State Hierarchy 6 7 E
128. ample Transitions from Multiple Sources toa Common Destination on page 7 40 Example Transitions from a Source to a Destination Based on a Common Event on page 7 41 Contents of section Event Actions on page 7 43 e Example Event Actions and Superstates on page 7 43 Contents of section Parallel AN D States on page 7 45 e Example Event Broadcast State Action on page 7 45 e Example Event Broadcast Transition Action Nested Event Broadcast on page 7 50 e Example Event Broadcast Condition Action on page 7 54 Contents of section Directed Event Broadcasting on page 7 58 e Example Directed Event Broadcast Using send on page 7 58 e Example Directed Event Broadcasting Using Qualified Event Names on page 7 60 7 4 Event Driven Effects on Semantics Event Driven Effects on Semantics What Does Event Driven Mean The Stateflow diagram executes only when an event occurs an event occurs and the Stateflow diagram is awakened to respond to the event Exactly what executes depends on the circumstances when the event occurs Actions that are to take place based on an event are atomic to that event Once an action is initiated it is completed Top Down Processing of Events When an event occurs it is processed from the top or root of the Stateflow diagram down through the hierarchy of the Stateflow diagram At each level in the hierarchy any during andon event _name
129. ample Using Condition Actions to Broadcast Events to Parallel AND States on page 7 16 Example Cyclic Behavior to Avoid When Using Condition Actions on page 7 17 Contents of section Default Transitions on page 7 18 Example Default Transition in an Exclusive OR Decomposition on page 7 18 Example Default Transition toa J unction on page 7 20 Example Default Transition and a History J unction on page 7 21 Example Labeled Default Transitions on page 7 23 Contents of section Inner Transitions on page 7 25 Example Processing One Event Within an Exclusive OR State on page 7 25 Example Processing a Second Event Within an Exclusive OR State on page 7 26 Example Processing a Third Event Within an Exclusive OR State on page 7 27 Example Processing One Event with an Inner Transition to a Connective J unction on page 7 28 Example Processing a Second Event with an Inner Transition toa Connective J unction on page 7 29 Example Inner Transition to a History J unction on page 7 31 7 Semantics Contents of section Connective Junctions on page 7 33 Example If Then Else Decision Construct on page 7 33 Example Self Loop on page 7 34 Example For Loop Construct on page 7 35 Example Flow Diagram Notation on page 7 37 Example Transitions from a Common Source to Multiple Destinations on page 7 39 Ex
130. ange 2 Placethe cursor over a selected junction click the right mouse button to dis play the shortcut menu Place the cursor over Arrowhead Size The shortcut menu disappears and a numeric size is displayed 3 Click and drag horizontally to the left to decrease the arrowhead size or to the right to increase the arrowhead size The numeric display adjusts to show the currently selected arrowhead size Moving a Junction To move a junction select drag and release it in a new position Editing J unction Properties Select a junction click the right mouse button on that junction to display the J unction shortcut menu Choose Properties to display the Connective J unction properties dialog box Ed Connective Junction iof x Parent char untitled Untitled Description me Document Link eye hs Apply Fever Help Close W orking with Junctions This is the history junction properties dialog box k History Junction iof x Parent chart untitled Untitled Description Document Link DAG Apply zea Help Close This table describes the junction object fields Field Description Parent Parent of this state read only click on the hypertext link to bring the parent to the foreground Description Textual descripti on comment Document Link Enter a web URL address or a general MATLAB command Examples are www mat hwor ks com mailto email_ address edit spec data speed txt
131. ansitions In the component summary Stateflow diagram the history junction in St at eAl indicates that when a transition to St ateAl occurs the substate that becomes active St ateAla StateAlb or St at eAlc is based on which of those substates was most recently active In the automatic transmission system history indicates that when clutch engaged causes a transition fromneutral totheengaged superstate 1 17 1 Introduction 1 18 the substate that becomes active either first or second is based on which of those substates was most recently active neutral Clutch_engaged engaged speed gt threshold second Actions Actions take place as part of Stateflow diagram execution The action can be executed either as part of a transition from one state to another or based on the activity status of a state In the Graphical Components figure the transition segment from St at eAlb to the connective junction is labeled with a condition action f unc1 anda transition action f unc 2 The semantics of how and why actions take place are discussed throughout the examples in Chapter 7 Semantics Transitions can have condition actions and transition actions as shown in this example Condition Transition action action switch_off c1 elec_off light_off Anatomy of a Model and Machine States can haveentry during exit andon event _name actions For example Power_on entry ent_action
132. ar to this sample Power_on Power_off gt Label the transitions Click on the transition from Power _on toPower_off toselect it Click onthe alongside the transition and enter the label Swi t ch Press the Escape key to deselect the transition label and exit the edit Label the transition from Power_off toPower_on with the same text Switch Your Stateflow diagram should look similar to this sample Power_off 6 Add a default transition Click and release the mouse on the Default Transition button in the toolbar Drag the mouse toa straight portion on the border of thePower _off state Click and release the mouse when the arrowhead snaps to the border Using Stateflow of thePower_off state Your Stateflow diagram should look similar to this sample Power_off 7 Parse the Stateflow diagram Parsing the Stateflow diagram ensures that the notations you have specified are valid and correct Choose Parse Diagram from the Tools menu of the graphics editor to parse the Stateflow diagram Informational messages are displayed in the MATLAB command window Any error messages are displayed in red If no red error messages appear the parse operation is successful and the text Done is displayed See Parsing on page 9 11 for more information on parsing For More Information For moreinformation on creating Stateflow diagrams using the graphics editor see Using the Graphics Editor 1 29 1 Int
133. archy a target s parent must be a machine this menu item is disabled if a chart or state parent type is selected displays an untitled Target Configura tion properties dialog box Help Menu The Help menu provides these options Menu Choice Description Topics HTML Help Desk HTML About Stateflow Displays Stateflow online help in an HTML browser An online version of the Stateflow User s Guideis one of the options available from the online help Displays the MATLAB Help Desk in an HTML browser Displays a pop up window with software version information 5 7 5 Exploring and Searching Moving Objects Changing Parent Tocreate desired behavior you may need to changethe parent of an event data or target object Objects in the Contents of pane can be moved in the hierarchy to change an object s parent Click and drag an object from the Contents of pane to a new location in the Object Hierarchy pane to change its parent If the object is the current parent an X with a circle around it is displayed indicating this is an invalid operation If you move an object to a level in the hierarchy that does not support that object s current Scope property the Scope is changed to Local Moving Objects Changing Index and Port Order To ensure proper ordering of event and or data Input from or Output to Simulink you may need to move some of these objects in the E xplorer Click and drag a data o
134. are the rules for processing transitions e State transitions are achieved through taking valid transition paths e A valid transition path is found through the process of considering all candidate paths segment by segment in precise deterministic order e For a path to be valid all transition segments along the path must be valid e With thefirst invalid segment a candidate path is rejected and not processed further e While processing for a valid path condition actions of valid transition segments are executed e Transitions are processed at a decision point in this order a Transitions with higher level parents b Event triggered guarding condition c Event triggered only d Guarding condition only e Unconditional f Clockwise twelve o clock rule for junctions g Clockwise from top left corner rule for states 7 69 7 Semantics 7 70 Rules When Taking Transition Paths In summary these are the rules when taking transition paths The parent of a valid transition path is the innermost state that contains all the points along the transition path All of the active states up to the parent of the transition path are exited in a bottom up hierarchical manner When exiting a superstate with exclusive OR decomposition first exit the active child and then exit the superstate When exiting a superstate with parallel AND decomposition first exit all active children in a deterministic order geometrically from r
135. ated was valid Parallel AND States Parallel AND states are evaluated and executed first from top to bottom and then from left to right in the case of a tie In this example assuming that A and 7 65 7 Semantics B andC andD are exactly equivalent from top down the parallel AND states are executed in this order A B D C 7 66 Semantic Rules Summary Semantic Rules Summary Event Broadcasting Rules In summary these are the rules for event broadcasting e A Stateflow diagram is event driven the Stateflow diagram awakens when an event is broadcast e An event broadcast occurs in a top down manner starting from the parent of the event or the intended directed state Imported and Output to Simulink events can be broadcast but cannot be received cannot trigger transitions 7 67 7 Semantics 7 68 Rules for Processing States In summary these are the rules for processing states The sole purpose of an active state is to become inactive through a valid state transition Active states are processed from the top down in a depth first manner Active exclusive OR states are processed a Outer transitions are processed in the search for a valid path from the state Any stateduri ng actions includingon event _name actions are executed Inner transitions are processed in the search for a valid path within the state If the state is a superstate with no valid transition paths and if the sup
136. ateflow diagram name You can also change the Stateflow block name in the Simulink model Once you have saved the Stateflow diagram the new name appears The Graphics Editor M ain W indow Modified Flag An asterisk following the Stateflow diagram Stateflow block name indicates that an unsaved change has been made to the Stateflow diagram Menu Bar The menu choices provide the ability to operate on the graphical Stateflow diagram objects and perform operations on the Stateflow diagram itself The menu bar consists of these menus e File e Edit e Simulation e Style e Tools Add e Help 2 Using the Graphics Editor Toolbar You can select from these object buttons on the toolbar Name Button Icon Description State Use a State to depict a mode of the system Use a history junction to indicate when entering this level in the hierarchy that the last state that was active becomes the next state to History junction be active Use a default transition to indicate when entering this level in the hierarchy which state becomes active by default in the absence of a history junction Default transition e junction to handle situations where transitions out of one state into two or more states are taken based on the same event but guarded by different conditions Connective Fae One use of a connective junction is YA 2 6 The Graphics Editor M ain W indow Productivi
137. ateflow is invoked The file can be re executed on demand from the MATLAB command line interface by enteringsfsave defaults Machine Defaults The machine defaults are Parameter Default chart name NULL chart creator Unknown chart version none Defaults File Defining Color Colors are defined using the three element matrix red green blue RGB notation The matrix notation maps to the following colors This table lists some representative RGB color definitions Color Red Green Blue Black 0 0 0 White 1 1 1 Red 1 0 0 Green 0 1 0 Blue 0 0 1 Yellow 1 1 0 Magenta 1 0 1 Cyan 0 1 1 Chart Defaults The chart defaults are Parameter Default chart name Untitled chart stateFont Name Helvetica chart transitionFont Name Helvetica chart stateCol or chart stateLabel Color chart transitionColor 011 Cyan 1 11 White 1 1 0 Yellow 2 51 2 Using the Graphics Editor 2 52 Parameter Default chart transitionLabel Color 110 Yellow chart groupedCol or 0 752941 0 752941 0 752941 chart junctionCol or 101 Magenta chart selectionColor 0 1 0 Green chart animationColor 1 0 0 Red chart chartCol or 0 0 0 Black Target Defaults The target defaults are Parameter Default target name Untitled target description NULL target customCode NULL target codeCommand sfc target codeFlags sfun debug consistency range conflict target makeComman
138. ates 0 cee eee ee 2 24 What Can You Do with States 00 0000 00 2 24 Specifying Decomposition 0 cece eee eee 2 24 Creating Deleting States 2 0 eee 2 25 Labeling States ata wiide a isoye iA aR ara e eee 2 26 Grouping and Ungrouping States a sasae 2 26 Showing and Hiding States 0 0 2 eee eee 2 27 Resizing States 20 0 cece ee 2 27 Changing Font Size 0 0 ee ee 2 27 Changing Arrowhead Size 1 1 0 ce cee 2 28 Moving States 0 0 cee ee 2 28 Editing State Properties 2 0 c eee eee 2 29 Working with Transitions 2 31 What Can You Do with Transitions 2 31 Creating Deleting Transitions 2 000 e eee 2 31 What Is a Default Transition 00002 e eee 2 32 Creating Default Transitions 0 0c eee eee 2 32 Editing Transition Attach Points 055 2 32 Labeling Transitions 000 ee 2 33 Valid babs eviey ideas eee ye ee duds gt fede hedge eos 2 34 Changing Font Size a wus waeaie a ere nase a own Weed aed 2 34 Changing Arrowhead Size 0 cee eee ee 2 34 Moving Transition Labels 2 000 eee eee eee 2 35 Editing Transition Properties 20 0a ee eee 2 36 Working with J unctions 00055 2 38 What Can You Do with J unctions 0 0000 2 38 Creating Del
139. ates the appropriate export and import event code for both machines See Exported Events on page 4 25 for an example showing theimported event format required if an external codesource is used Imported Consider a real world example to clarify when to define an Imported event Someone buys a communications pager and indicates you may want to use the pager number to page them in the future They tell you the pager number and you take note of the number by writing it down You can then use the number to page that person You cannot receive the page because you do not own the pager Similarly you may want to broadcast an event that is externally outside the Stateflow diagram the machine and the Simulink model defined By defining an event s scope to be Imported the event can be broadcast anywhere within the hierarchy of that machine including any offspring of the machine An Imported event s parent is external However the event needs an adoptive parent to resolve symbols for code generation An Imported event s adoptive parent must be the machine because the machine is the highest level in the Stateflow hierarchy that can interface to external sources Importing the event does not imply anything about what the external source does with the information It is the responsibility of the external source to make the Imported event available in the manner appropriate to the source to make use of the right to broadcast the event
140. ault 2 32 definition 1 13 description property 2 37 destination property 2 37 document link property 2 37 editing attach points 2 32 editing properties 2 36 glossary definition A 11 label format 2 33 label property 2 37 labeling 2 33 notation label example 6 18 labeling 6 18 types 6 20 valid label 6 19 notation definition 6 17 operations 2 31 parent property 2 37 properties 2 37 representing hierarchy 6 8 source property 2 37 toand from exclusive OR states 1 semantics example 7 8 toand from exclusive OR states 2 semantics example 7 9 toand from exclusive OR states 3 semantics example 7 10 to and from junctions notation example 6 21 to and from OR states notation example 6 21 to and from OR superstates notation example 6 22 to and from substates notation example 6 23 valid labels 2 34 transition label changing font size 2 34 condition 2 33 condition action 2 33 event 2 33 moving 2 35 notation condition 6 18 condition action 6 19 event 6 18 transition action 6 19 transition action 2 33 trigger type function call 3 18 Index tutorial carousel add and define data task 8 20 add and define events task 8 18 basic operation 8 2 create a Simulink model task 8 9 create and label AND states task 8 14 create and label OR states task 8 10 create and label superstates task 8 13 create default transitions task 8 17 create the transitions task 8 15 design questions 8 4 determining data 8 7 determining default t
141. bject to be Imported Stateflow generates the appropriate export and import data code for both machines This example shows the format required in the external code source custom code to import an Exported data object sf_ev_d_inout_ex File Edit Simulation Format Tools Sine Wave Sine Wave ext _data is defined as imported in the external code source fo ext _data added and external code source defined as an Exported data extern int ext _data void func_exampl e void ext _ data 123 Stateflow generates this code int ext data Imported Data Similarly you may want to access a data object that is externally outside the Stateflow diagram the machine and the Simulink model defined By defining 4 29 4 Defining Stateflow Interfaces 4 30 a data s scope to be Imported the data can be accessed anywhere within the hierarchy of that machine including any offspring of the machine An Imported data object s parent is external However the data object needs an adoptive parent to resolve symbols for code generation An Imported data object s adoptive parent must be the machine because the machine is the highest level in the Stateflow hierarchy that can interface to external sources Importing the data object does not imply anything about what the external source does with the data object It is the responsibility of the external source to make the Imported data objec
142. bject with Input from or Output to Simulink Scope to a new position in the Contents of pane Data list to change its port number Click and drag an event Input from or Output to Simulink Scope to a new position in the Contents of pane Event list to change its index number Deleting Objects Select the object in the Contents of pane and press the Delete key or select Cut Ctrl X from the Edit menu to delete an object Stateflow Explorer User Interface Event Properties Dialog Box This is a new Event properties dialog box Eq Event event O x Name event Parent machine untitled Debugger breakpoints I Start of broadcast I End of broadcast Description Oe Document Link Bias Apply ZAA Help Close Name Enter the name of the event object in this field Parent The event s parent is listed as a hyptertext link in a read only field The object type is in parenthesis followed by the name of the object Clicking on the parent in blue displays and changes focus to either the Simulink model parent is the machine or the graphics editor parent is either the chart or a state depending on the parent See these sections for more information Event Parent Types on page 3 7 Events Hierarchy and Scope on page 3 9 Scope An event s Scope defines to what extent the object is known relative to the Stateflow block the Simulink model and sources external to the Simulink model By default
143. cast situation occurs Neither transition can complete Debugging Cyclic Behavior Example Flow Cyclic Behavior Not Detected This Stateflow diagram shows an example of cyclic behavior in a flow diagram that is not detected by the Debugger The data object i is set to zeroin the condition action of the default transition i is incremented in the next transition segment condition action The transition to the third connective junction is valid only when the condition i lt 0 istrue This condition will never betruein this flow diagram and there is a cycle This cycle is not detected by the Debugger because it does not involve event broadcast recursion Detecting cycles that are involved with data values is not currently supported 10 23 10 Debugging Example Noncyclic Behavior Flagged as a Cycle This Stateflow diagram shows an example of noncyclic behavior that the Debugger flags as being cyclic i lt 5 i E State A becomes active andi is initialized to zero When the transition is tested the condition i lt 5 is true The condition actions incrementi and broadcast event E are executed The broadcast of E when state A is active causes a repetitive testing and incrementing of i until the condition is no longer true The Debugger flags this as a cycle when in reality the apparent cycle is broken when i becomes greater than 5 10 24 Reference 11 Reference This chapter contains detailed
144. ccc ccc cee Example Event Broadcast StateAction 05 Example Event Broadcast Transition Action Nested Event Broadcast 00 cece eee eee Example Event Broadcast Condition Action Directed Event Broadcasting 005 Example Directed Event Broadcast Usingsend Example Directed Event Broadcasting Using Qualified Event Names 0000 c eee tee Execution Order 0 00 0 ccc ccc ccc eens OVERVIGW oaeee ee eee SAR sat Vila aed es Re ae ds aa Bd Execution Order Guidelines 0 ees Parallel AND States ccc ce ee eee eee Semantic Rules Summary 0202005 Event Broadcasting Rules 0 00 ce eee ees Rules for Processing States 2 0 c eee Rules for Processing Transitions 0 00e eee Rules When Taking Transition Paths Tutorial Entering a Stateflow Diagram 8 Overview ob one Pic hr ee id eked Sens a ecberdi Weeentrbletond 6 8 2 ODjECtIVES 2 tent eee 8 2 Provided Models for This Chapter 20000 ee 8 2 Carousel Tutorial Example a na a 8 2 Basi Op ratioN spresnenie a iay EE a KA 8 2 Designing the Carousel Stateflow Diagram 8 4 OVENVICW acccadcchiw sidan EENEN ETE NS A ee ae ee 8 4 The Design Questions 0 0 c eects 8 4 What Are the States ce ee eee 8 4 What Is a State Decomposition 000 ee
145. choices Appropriate selection of an event s parent allows you 3 Events and Data 3 10 to be specific about who can trigger on an event within the hierarchy This directed event broadcasting eliminates unnecessary event processing Event Scope An event s scope defines to what extent the object is known relative to the Stateflow block the Simulink model and sources external to the Simulink model These are the options for the Scope property e Local e Input from Simulink e Output to Simulink e Exported e Imported Local A Local event is broadcast and only received within the hierarchy of the parent Valid parent types for a local event are machine chart and state Input from Simulink An event that originates from the Simulink model and is an input to the Stateflow block is an Input event Input events must be parented by the chart Input events are broadcast to the chart and its offspring Events that are defined to be inputs are also interfaces to the Simulink model of which the Stateflow block is a part When you define an event as an Input from Simulink the appropriate notation is automatically added to the Stateflow block in the Simulink model Event inputs are represented by the addition of a Simulink trigger port on the Stateflow block Events When you add an event Input from Simulink a single Simulink trigger port is added to the Stateflow block Single Input from Simulink event sf_ev_d_inout_ex
146. cribed and designed does not have junctions See the sections titled Connective J unctions on page 6 32 and History on page 6 40 for information on the use and notation for Connective and History junctions What Are the Transitions In the carousel system these are the transitions between OR states Power_off gt Power_on triggered by event Switch_on Power_on Power_off triggered by event Swi tch_off Power_on Ride On gt Power_on Ride Stopped triggered by any event when the condition Speed gt Max_speed istrue Power_on Ride On gt Power_on Ride Stopped triggered by event Emergency stop Power _on Ride On Power_on Ride Stopped triggered by event Ride done Power_on Ride Stopped Power_on Ride On triggered by event Start button Power_on Timer Stopped gt Power_on Ti mer Counting triggered by event Start_button Power_on Timer Counting Power_on Timer Stopped triggered by any event when the condition Ti me gt Duration istrue The event Ri de_done is broadcast as a transition action See the section titled Transitions on page 6 17 for more information Designing the Carousel Stateflow Diagram Are There Default Transitions These are the default transitions in the example e ThePower off substate is the default state to become active upon a transi tion to the carousel Stateflow diagram e ThePower_on Ride St opped substate is the default state to become active upo
147. cts and are thus not represented directly in the Graphical Components figure Data objects are used to store numerical values for reference in the Stateflow diagram Data objects are created and modified using the Stateflow E xplorer Data objects can be created at any level in the hierarchy Data objects have properties such as ascope Thescope defines whether the data object is e Local to the Stateflow diagram e An input to the Stateflow diagram from its Simulink model e An output from the Stateflow diagram to its Simulink model e Non persistent temporary data e Defined in the MATLAB workspace e A constant e Exported to a code destination external to the Stateflow diagram and Simulink model e mported from a code source external tothe Stateflow diagram and Simulink model Hierarchy Hierarchy enables you to organize complex systems by defining a parent and offspring object structure A hierarchical design usually reduces the number of transitions and produces neat manageable diagrams Stateflow supports a hierarchical organization of states such that states can exist within other states Stateflow represents state hierarchy with superstates and 1 15 1 Introduction substates For example this Stateflow diagram has a superstate that contains two substates neutral Clutch_engaged f engaged first second Theengaged superstatecontainsthefirst andsecond substates Theengaged superstate is the parent in
148. d This solution is much simpler than the previous one See the section titled Example Processing One Event with an I nner Transition to a Connective unction on page 7 28 for more information on the semantics of this notation 6 28 Transitions Example Two Before Using an Inner Transition This is an example of a Stateflow diagram that could be simplified by using an inner transition Any event occurs and awakens the Stateflow diagram The default transition to the connective junction is valid The destination of the transition is determined by the conditions C_one and C_two If C_one is true the transition toAl is true If C_two is true the transition toA2 is valid The transitions between Al and A2 are also determined by C_one and C_two Example Two Inner Transition to a Connective Junction This example shows a solution to the same problem Example Two using an inner transition to a connective junction A2 amp C_two StateAl is initially active 6 29 6 Notations Any event occurs and awakens the Stateflow diagram The default transition to the connective junction is valid The destination of the transitions is determined by C_one and C_t wo When the default transition path is followed neither state Al nor A2 is active thus the truth of condition is based exclusively on C_one and C_two The Stateflow diagram is simplified by using an inner transition in place of the transit
149. d mex v target simulationTarget 0 Defaults File State Defaults The state defaults are Parameter Default state fontSize 9 0 state arrowSi ze 8 0 State visible 1 Transition Defaults The transition defaults are Parameter Default transition fontSize 9 0 transition arrowSize 8 0 transition visible 1 Junction Defaults These junction defaults are defined in the defaults file Parameter Default junction arrowSize 8 0 junction visible 1 2 53 2 Using the Graphics Editor Data Defaults These data object defaults are defined in the defaults file Parameter Default data name data data range I nf inf Event Defaults These event object defaults are defined in the defaults file Parameter Default event name NULL Events and Data Overview 2 ee a a 3 2 Events 2 6 8 G08 Ho wok Yee a A ke we 3 5 Implicit Local Events 3 20 3 Events and Data Overview Events and Data Events drive the Stateflow diagram execution The occurrence of an event causes the status of the states in the Stateflow diagram to be evaluated Data objects are used to store numerical values for reference in the Stateflow diagram Events and data are nongraphical objects that are created using either the Stateflow E xplorer see Stateflow E xplorer User Interface on page 5 5 or the graphics editor Add menu see Add M enu on page 2 48
150. de is for stand alone nonsimulation targets You uniquely name this target within Stateflow O verview In summary the primary design approach options are e Use Stateflow together with Simulink for simulation e Use Stateflow Stateflow Coder Simulink and RTW to generate target code for the complete model e Use Stateflow and Stateflow Coder to generate target code for a machine 1 Introduction Finite State Machine Concepts 1 6 What Is a Finite State Machine A finite state machine FSM is a representation of an event driven reactive system In an event driven system the system transitions from one state mode to another prescribed state provided that the condition defining the change is true For example you can represent an automatic transmission in a car by a finite state machine The transmission has a number of different modes of operation The system transitions from being in neutral to being engaged in a gear when the driver shifts the stick from the neutral to engaged position FSM Representations Traditionally the relationships between the inputs outputs and states of an FSM arerepresented in a truth table The resulting table describes the logic necessary to control the behavior of the system under study Another approach to designing event driven systems is to model the behavior of the system by describing it in terms of states and transitions The state that is activeis determined based on t
151. del The Stateflow block interface includes e Physical connections between Simulink blocks and the Stateflow block e Event and data information exchanged between the Stateflow block and either its Simulink model or external sources e MATLAB workspace e Definitions in external code sources Typical Tasks to Define Stateflow Interfaces Defining the interface for a Stateflow block can involve some or all of these tasks e Defining the Stateflow block update method e Defining Output to Simulink events e Adding and defining nonlocal events and nonlocal data within the Stateflow diagram e Defining relationships with any external sources The tasks are presented in this section in the order of appearance in this list This could be a typical sequence You may find a particular sequence complements your model development process better than another O verview Where to Find More Information on Events and Data See these sections for conceptual information on data and events Events on page 3 5 and Data on page 3 22 These references in particular are relevant to defining the interface Event Parent Types on page 3 7 Events Hierarchy and Scope on page 3 9 Event Scope on page 3 10 Table of Event Parent and Scope Combinations on page 3 15 Event Ports on page 3 16 Event Triggers on page 3 17 Data Parent Types on page 3 25 Data Hierarchy and Scope on page 3 26
152. descriptions of Stateflow functions These functions operate on the machine Functions Sf new Creates and displays a new Simulink model containing an empty Stateflow block Sees f new sfexit Closes all Stateflow diagrams Simulink models containing Stateflow diagrams and exits the Stateflow environment Seesfexit sfsave Saves the current machine and Simulink model See sfsave stateflow Opens the Stateflow model window Seest at ef ow This function operates on a Stateflow diagram Functions sfprint Prints the visible portion of a Stateflow diagram See sfprint This function is independent of models and Stateflow diagrams Functions sf hel p Displays Stateflow online help in an HTML browser See sfhelp The Stateflow model window contains an empty Stateflow block an Examples block and a manual switch A Stateflow block is equivalent to a Stateflow diagram 11 2 sfnew Purpose Syntax Description Example Create a new Simulink model containing an empty Stateflow block sfnew sfnew model name sf new creates and displays a new untitled Simulink model containing an empty Stateflow block sf new model name creates and displays a new Simulink model with the title specified Create and display a new titled Simulink model which contains an empty Stateflow block gt gt sfnew example A new Simulink model titled example which contains an empty Stateflow block
153. diagram Each data object has a parent Data is often manipulated in the actions that can be associated with states and or transitions For example if state Of f is active and the event s witch_on is broadcast the transition from Of f toOn is triggered The dataon_count is incremented once the destination state 0n has been determined If state0On is active and the events witch_off is broadcast the transition from On to Off is triggered The data off count is incremented once state 0f f has been determined as the destination a switch_on on_count Off switch_offfoff_count The value of data is determined either from within the Stateflow diagram through actions or from outside of the Stateflow diagram either through Simulink or from an external source Data All data objects have these properties e Name see Data Name on page 3 24 Description see Data Description on page 3 24 Parent see Data Parent Types on page 3 25 Data Hierarchy and Scope on page 3 26 Scope see Data Scope on page 3 27 Table of Data Scope and Parent Com binations on page 3 32 Port if Scope is Input from Simulink or Output to Simulink see Data Ports on page 3 32 Data Attributes Units See Units on page 3 33 Type See Type on page 3 34 Initial Minimum and Maximum See Initial Value on page 3 34 Min imum Value on page 3 34 and Maximum Value on pa
154. dialog box Ed Data data Bil x Name data Units Parent machine untitled Scope Port Type Peal double E Inital Value fo Minimum J inf Maximum inf Description Document Link IDAZ Apply zE Help Close Name Enter the name of the data object in this field Units Units is a user entered string to describe the units of the data type Parent The data object s parent is listed in a read only field The parent is the object in the Object Hierarchy display that was selected when the data object was created The object type is in parenthesis followed by the name of the object Clicking on the parent in blue displays and changes focus to either the Simulink model parent is the machine or the graphics editor parent is either the chart or a state depending on the parent See these sections for more information Data Parent Types on page 3 25 and Data Hierarchy and Scope on page 3 26 Scope A data object s scope defines to what extent the object is known relative to the Stateflow block the Simulink model and sources external to the Simulink model Stateflow Explorer User Interface By default the Scope is Local The Scope options are displayed in a pull down menu The options displayed depend on the parent If the Scope you desire is not an available option for that parent type you may need to move the event so that it is parented by an object that supports that Scope
155. down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_one Thereis a valid transition segment from state B tothe connective junction and from the junction to state C 2 StateB executes and completes exit actions exit B 3 StateB is marked inactive 4 Statec is marked active 5 Statec executes and completesentry actions ent C 6 TheStateflow diagram goes back tosleep waiting to be awakened by another event 7 41 7 Semantics This sequence completes the execution of this Stateflow diagram associated with event E_one 7 42 Event Actions Event Actions Example Event Actions and Superstates This example shows the semantics of event actions within superstates State Al is active Al entry entA during durAQ exit exitAQ on E_three A_one E_four entry entAl B during durA1 Com no exit exitA1 iad entry entB during durB exit exitBQ A2 entry entA2 during durA2 exit exitA2 Initially the Stateflow diagram is asleep State A A1 is active Event E_three occurs and awakens the Stateflow diagram Event E_three is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_t hree Thereis no valid transition State A e
156. e Semantics of State Actions on page 7 7 for information on how and when entry actions are executed During Action Intheexample stateOn hastwoduring actions ight _on andon_count These actions are executed whenever state 0n s during action is executed See Semantics of State Actions on page 7 7 for information on how and when during actions are executed Exit Action In theexample stateOf f hasexit action i ght _off This action is executed whenever state 0f f sexi t action is executed See Semantics of State Actions on page 7 7 for information on how and when exit actions are taken On Event_name Action In the example state Off hastheonevent_name power_ outage When the event power outage occurs theaction handle outage is executed See Semantics of State Actions on page 7 7 for information on how and when on event _name actions are taken Example Unique State Names This example shows how hierarchy supports unique naming of states Each of these states has a unique name because of the hierarchy of the Stateflow diagram Although the name portion of the label on the state itself is not unique when the hierarchy is prepended to the name in the data 6 15 6 N otations dictionary the result is unique The full names for the states as seen in the data dictionary are e Ridel On e Ri del Off e Ri de2 On e Ri de2 Off Although the names 0n and Of f are duplicated
157. e Stopped substate Click the border when the cursor changes to a cross hair Without releasing the mouse button drag the mouse to a straight portion on the side border of thePower_on Ri de On substate When the transition snaps to the border release the mouse button Transitions cannot be attached on corners since corners are used for resizing Y ou create one transition in this step 2 Create the rest of the transitions within the Ri de superstate You create three transitions in this step 3 Create the transitions within theTi mer superstate You create two transitions in this step 4 Create the transitions to and from thePower _off state You create two transitions in this step 8 15 8 Tutorial Entering a Stateflow Diagram Sample Snapshot Your Stateflow diagram should now look similar to this Stateflow diagram Power_on e s Ride ci Power_off een ee 2 i KA Stopped Pus a ias T Label the Transitions The general format of a transition label is event condition condition_action transition_action In this example there are eight transitions to label Use the transition labels in the solution Stateflow diagram as a guide These steps show how tolabel the transitions 1 Start with the transition from the substate Power on Ride Stopped tothe substate Power _on Ri de 0n Select the transition Click on the alongside the transition and enter the label St art _but ton Deselect the transition label
158. e as modes of control strategy Example Continuous Stateflow Block Simulink will awaken sample the Stateflow block at each step in the simulation as well as at intermediate time points that may be requested by the Simulink solver This method is consistent with the continuous method in Simulink Defining the Stateflow Block Update M ethod In this example provided in the E xamples Stick Slip Friction Demonstration block the chart Update method set in the Chart Properties dialog box is set to Continuous iS sf_stickslip a ox File Edit Simulation Format Tools l sf_stickslip mdl force and position The input fore linearly compresses vs time the spring but friction resists this movement The magnitude of friction depends on the state of motion Oo With the default parameters the natural edit frequency is much higher than that of the excitation force For contrast change Parameters the parameter values to M 0 1 kg and Fsliding 0 1 N Stick slip Friction Simulation To run choose Start from the Simulation menu 4 9 4 Defining Stateflow Interfaces 4 10 Defining Output to Simulink Event Triggers Overview Stateflow block output events connect to other Simulink blocks or Stateflow blocks There are two main options for trigger type e Edgetriggered e Function call Simulink controls the execution of edge triggered subsystems The function call mechanism is a means by
159. e place only if a certain condition is true Conditions are placed within These are some guidelines for defining conditions e The expression must be a Boolean expression of some kind The condition must evaluate to either true 1 or false 0 e The expression can consist of Boolean operators which make comparisons between data and numeric values Any function that returns a Boolean value Theln state_name condition function that is evaluated as true when the state specified as the argument is active The full state name including any ancestor states must be specified to avoid ambiguity e Thecondition expression should not call a function that causes the Stateflow diagram to change state or modify any variables e Boolean expressions can be grouped using amp for expressions with AND rela tionships and for expressions with OR relationships e Assignment statements are not valid condition expressions e Unary increment and decrement actions are not valid condition expressions Time Symbol You can use the letter t to represent absolute time in simulation targets This simulation time is inherited from Simulink For example the condition t On_time gt Duration specifies that the condition is true if the value of On_ti me subtracted fromthe simulation timet is greater than the value of Duration The meaning of t for nonsimulation targets is undefined since it is dependent upon the specific application and ta
160. e chart in the Object Hierarchy that you want to be the data object s parent Choose New and then Data from the Explorer File menu The Data properties dialog box is displayed Replace the contents of the name field with the name count Set the Minimum field to 0 and the Maximum field to 10 Click on the Close button to save the changes and close the Data properties dialog box 5 19 5 Exploring and Searching 5 20 Stateflow Finder User Interface Finder Dialog Box The Finder operates on a machine This is the Finder dialog box Stateflow Machine name zz Stateflow Finder sf_exp_srch Mii x String Criteria Search Method Look for Normal Wildcard regular expression EER Fa Ar a C Exact Word match Look in ny ER ject T Object Type Refine FM States W Transitions I Junctions W Events V Data M Targets Gear Matches Search History a 4 ote String Criteria You specify the string by entering the text to search for in the Look for text box The search is case sensitive All text fields are included in the search by default Alternatively you can search in specific text fields by using the drop down Look in list box to choose one of these options e Any Search the state and transition labels object names and descriptions of the specified object types for the string specified in the Look for field Label Search the state and transition labels of the specified object types
161. e eee 1 4 Finite State Machine Concepts 1 6 What Is a Finite State Machine 0 000 1 6 FSM Representations 0 0 e eee eee 1 6 Stateflow Representations 0 0 c cece eee eee 1 6 NIQEGH ONS sito As es ob wk oo eae one be a a Oe ee 1 7 Semantis sd Sn Saw raano re YR Gi eee we ee Oa we CaS 1 7 REfErENGES jcc eas sidead en fen hoe ena a ee te woe ee 1 7 Contents Anatomy of a Model and Machine 1 8 The Simulink Model and Stateflow Machine 1 8 Defining Stateflow Interfaces 0 0 0 e eee ees 1 10 Stateflow Diagram Objects 0 ccc eee ee 1 11 Using Stateflow 0 eens 1 22 Stateflow Typical Tasks 0 000 cece ee eee 1 22 Sample Solution 0 0 c eee eee 1 22 Creating a Simulink Model 0 00 cee eee 1 23 Creating a Stateflow Diagram 00 e eee eee 1 26 Defining the Stateflow Interface 0 0 cece eee 1 30 Running a Simulation 0 0 2 0 e eee eee 1 32 DeDUGGING ias ios aai tae eRe aon bee eee Wi eee ne Ee 1 33 Generating Code ae iasad am aan iia eee ens 1 35 Using the Graphics Editor 2 The Graphics Editor Main Window 2 2 OVEFVIEW oai eia eee ene n teens 2 2 Main Window Components 000 cece eee ees 2 2 Drawing Area 0 cee eee 2 3 Message ATCA uaiu aao a di ae ee ea ea AE min REO E 2 3 Zooming OPtionS
162. e properties Click on the Close button to save the properties and close the dialog box 4 19 4 Defining Stateflow Interfaces 4 20 Event Outputs to Simulink Tasks to Define an Event Output to Simulink These tasks describe how to add and define the necessary fields for an event output to Simulink e Add an event choosing a Chart as the parent of the data e Choose Output to Simulink as the Scope e Specify the Trigger type e Apply and save the changes Add an Event Choosing a Chart as the Parent These steps describe how to add an event 1 Choose Explore from the graphics editor Tools menu to invoke the Explorer 2 Select a chart object in the hierarchy that you want to be the event s parent You must explicitly choose a parent to create an event Choosing the Chart to be the parent of the event enables receive rights to Simulink and tothe chart and all its offspring 3 Choose Event from the Explorer Add menu The Event properties dialog box is displayed 4 Enter anamein the Name field Choose Output to Simulink as the Scope Once you have chosen the chart as the parent the choice of valid scopes includes Local Input from Simulink or Output to Simulink Choose Output to Simulink as the Scope to enable send rights to Simulink and any offspring of the chart and to enable receive rights to the Simulink model Event O utputs to Simulink When you define an event to be an Output to Simulink a Simulink outp
163. e the design information conveyed by a Stateflow diagram Stateflow notation consists of e A set of graphical objects e A set of nongraphical text based objects e Defined relationships between those objects See Chapter 6 Notations for detailed information on Stateflow notations Semantics Semantics describe how the notation is interpreted and implemented A completed Stateflow diagram illustrates how the system will behave A Stateflow diagram contains actions associated with transitions and states The semantics describe in what sequence these actions take place during Stateflow diagram execution Knowledge of the semantics is important to make sound Stateflow diagram design decisions for code generation Different use of notations results in different ordering of simulation and generated code execution The default semantics provided with the product are described in Chapter 7 Semantics References For more information on finite state machine theory consult these sources 1 Harel David Statecharts A Visual F ormalism for Complex Systems Science of Computer Programming 8 1987 pages 231 274 2 Hatley Derek J and Imtiaz A Pirbhai Strategies for Real Time System Specification Dorset House Publishing Co Inc NY 1988 1 Introduction Anatomy of a Model and Machine The Simulink Model and Stateflow Machine The Stateflow machine is the collection of Stateflow blocks in a Simulink mode
164. ect buttons that correspond to The Graphics Editor M ain W indow drawing objects Using these object buttons you create your Stateflow diagrams Stateflow diagram Stateflow block name Drawing area Modified flag Menu bar Ed stateflow Untitled 5 x File Edit Simulation Style Tools Add Help Toolbar n ie Zoom in a z Cut Copy Zoom A Paste factor selector Font Size Junction Size Arrowhead Size Zoom out Exclusive OR Parallel AND Fit To View SelectAll Explore Debug Find mi Bsa Message area General Scroll shortcut menu bars Drawing Area The drawing area is the region of the main window where graphical objects can be placed The size of the drawing area is increased by resizing the main window Message Area Informational messages about what object or operation is active in the editor graphics editor focus messages are displayed in the message area in the lower left hand side of the main window 2 Using the Graphics Editor 2 4 Zooming Options These are the zoom control options Click on the Zoom In button to make a quick zoom in to the closest discrete zoom factor Click on the Zoom Out button to make a quick zoom out to the closest dis crete zoom factor Use the Zoom Factor Selector to choose a discrete zoom factor percentage from a menu Click on the percentage value to display the discrete per centage value pulldown menu Click on the down arrow
165. ected Stateflow diagram with the condition added to the transition from Power_on toPower off Power_on a Switch t gt 10 0 Shift 1 10 15 10 Debugging Debugging State Inconsistencies 10 16 What is a State Inconsistency Stateflow notations specify that states are consistent if e An active state consisting of at least one substate with XOR decomposition has exactly one active substate e All substates of an active state with AND decomposition are active e All substates of an inactive state with either XOR or AND decomposition are inactive A stateinconsistency error has occured if at any step in the Stateflow diagram simulation these notation rules are violated Causes of State Inconsistency State inconsistency errors are most commonly caused by the omission of a default transition to a substate in superstates with XOR decomposition Design errors in complex Stateflow diagrams can also result in state inconsistency errors These errors may only be detectable using the Debugger at runtime Detecting State Inconsistency To detect the state inconsistency during a simulation e Enable Debugging Animation and the State Inconsistency check in the Target Configuration sfun property dialog box e Build the target with the debugging options e Invoke the Debugger and enable State Inconsistency checking e Start the simulation Debugging State Inconsistencies Example State Inconsistency
166. ed on the Stateflow block The chart will be the parent for all the data in the carousel example Choose Data from the Explorer Add menu The Data properties dialog box is displayed Enter Ti me in the Name field Select Local in the Scope field Click on the Close button to save the changes and close the dialog box Add and Define Input from Simulink Data TheSpeed data object is Input from Simulink 1 2 Choose Explore from the Tools menu of the graphics editor Select the parent for the new data object Double click on the machine name the name you specified when you saved the Simulink model in the Object Hierarchy list Double click on the chart name the name you specified on the Stateflow block The chart will be the parent for all the data in the carousel example Choose Data from the Explorer Add menu The Data properties dialog box is displayed Enter Speed in the Name field Select Input from Simulink in the Scope field Since the Scope is Input from Simulink a port number is displayed You do not need to change the port number Click on the Close button to save the changes and close the dialog box 8 21 8 Tutorial Entering a Stateflow Diagram 8 22 Add and Define Data Output to Simulink Ride_on isthe only data Output to Simulink 1 Choose Explore from the Tools menu of the graphics editor 2 Select the parent for the new data object Double click on the machine name the name you specifi
167. ed when you saved the Simulink model in the Object Hierarchy list Double click on the chart name the name you specified on the Stateflow block The chart will be the parent for all the data in the carousel example 3 Choose New and then Data from the Explorer File menu The Data object properties dialog box is displayed 4 Enter Ri de_on in the Name field 5 Select Output to Simulink in the Scope field 6 Since the Scope is Output to Simulink a port number is displayed You do not need to change the port number 7 Click on the Close button to save the changes and close the dialog box Add and Define Workspace Data Duration is the only Workspace data object 1 Choose Explore from the Tools menu of the graphics editor 2 Select the parent for the new data object Double click on the machine name the name you specified when you saved the Simulink model in the Object Hierarchy list Double click on the chart Procedure 5 6 name the name you specified on the Stateflow block The chart will be the parent for all the data in the carousel example Choose New and then Data from the Explorer File menu The Data object properties dialog box is displayed Enter Duration in the Name field Select Workspace in the Scope field Click on the Close button to save the changes and close the dialog box Add and Define Constant Data Max_speed is the only Constant data object 1 2 Choose Explore from the Tools menu
168. elated Products and Documentation Requirements Stateflow is a multiplatform product running on Windows95 Windows NT and UNIX systems Stateflow requires e MATLAB 5 2 e Simulink 2 2 e AC or C compiler for creating MATLAB MEX files on your platform F or a list of all the compilers supported by MATLAB see the MathWorks Tech nical Support Department s Technical Notes at http www mathworks com support tech notes mex See the MATLAB Application Program Interface Guidefor information on how to ensure proper installation for integration into the MATLAB environment In addition you can optionally use the Real Time Workshop to generate floating point code for Simulink portions of the model Pas MATLAB Related Products and Documentation W hat Is MATLAB MATLAB is a high performance language for technical computing It integrates computation visualization and programming in an easy to use environment where problems and solutions are expressed in familiar mathematical notation Typical uses include e Math and computation e Algorithm development e Modeling simulation and prototyping e Data analysis exploration and visualization e Scientific and engineering graphics e Application development including graphical user interface building MATLAB is an interactive system whose basic data element is an array that does not require dimensioning This allows you to solve many technical computing probl
169. ems Digital Signal Processing DSP Control MMI Stateflow Components Stateflow consists of these primary components e Stateflow graphics editor see Chapter 2 Using the Graphics Editor e Stateflow Explorer see Chapter 5 Exploring and Searching e Stateflow Finder see Chapter 5 Exploring and Searching e Stateflow simulation code generator see Chapter 9 Generating Code e Stateflow Debugger see Chapter 10 Debugging Stateflow Coder is a separately available product and generates code for nonsimulation targets See Chapter 9 Generating Code for information relevant to Stateflow Coder Stateflow Dynamic Checker supports runtime checking for conditions such as cyclic behavior and data range violations The Dynamic Checker is currently available if you have a Stateflow license 1 Introduction 1 4 Design Approaches Stateflow is used together with Simulink and optionally with the Real Time Workshop RTW all running on top of MATLAB MATLAB provides access to data high level programming and visualization tools The control behavior that Stateflow models complements the algorithmic behavior modeled in Simulink Simulink supports development of continuous time and discrete time dynamic systems in a graphical block diagram environment Stateflow diagrams are incorporated into Simulink models to enhance the new event driven capabilities in Simulink such as conditionally executed
170. ems especially those with matrix and vector formulations in a fraction of thetimeit would taketowritea program ina scalar noninteractive language such as C or Fortran The name MATLAB stands for matrix laboratory MATLAB was originally written to provide easy access to matrix software developed by the LINPACK and EISPACK projects which together represent the state of the art in software for matrix computation MATLAB has evolved over a period of years with input from many users In university environments it is the standard instructional tool for introductory and advanced courses in mathematics engineering and science In industry MATLAB is the tool of choice for high productivity research development and analysis MATLAB features a family of application specific solutions called tool boxes Very important to most users of MATLAB toolboxes allow you to learn and apply specialized technology Toolboxes are comprehensive collections of MATLAB functions M files that extend the MATLAB environment to solve particular classes of problems Areas in which toolboxes are available include signal processing control systems neural networks fuzzy logic wavelets simulation and many others See the MATLAB documentation set for more information xxiii Before You Begin xxiv W hat Is Simulink Simulink is a software package for modeling simulating and analyzing dynamic systems It supports linear and nonlinear systems modeled i
171. en but an action is generated You can represent this situation by using a connective junction or a self loop transition from state to itself In stateA event e occurs If condition c1 is met transition AB is taken generating action a1 The transition A A is valid if evente occurs and c1 is not true In this self loop the system exits and re enters state A and executes action a2 An alternative representation using a connective junction is shown Connective Junctions The two representations are equivalent in the one that uses a connective junction it is not necessary to specify condition c 1 explicitly as it is implied A n 5 eflc1 a1 el c1 a2 f c1 ia1 P See the section titled Example Self Loop on page 7 34 for information on the semantics of this notation Example Connective J unction and For Loops This example shows a combination of flow diagram notation and state transition notation Self loops to connective junctions can be used to represent for loop constructs In stateA 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 The condition action 0 is executed The condition on the self loop is evaluated as true and the condition actions i f unc1 execute The condition actions execute until the condition i lt 10
172. en dropping it to attach to a destination object The default transition object isa transition with a destination but no source object Name Button Icon Description Default Use a Default transition to indicate transition when entering this level in the hier archy which state becomes active by default A 5 G lossary A 6 See the section titled What is a Default Transition on page 6 24 for more information Events Events drive the Stateflow diagram execution All events that affect the Stateflow diagram must be defined The occurrence of an event causes the status of the states in the Stateflow diagram to be evaluated The broadcast of an event can trigger a transition to occur and or can trigger an action to be executed E vents are broadcast in a top down manner starting from the event s parent in the hierarchy Events are added removed and edited through the Stateflow E xplorer Seethe section titled Events on page 3 5 for more information Explorer See Stateflow Explorer Finder See Stateflow Finder Finite State Machine A finite state machine FSM is a representation of an event driven system F SMs arealso used to describe reactive systems In an event driven or reactive system the system transitions from one mode or state to another prescribed mode or state provided that the condition defining the change is true Hierarchy Hierarchy enables you to organize complex sy
173. ent broadcast Use the default chart Update method that is Triggered or Inherited set in the Chart properties dialog box to achieve this behavior Example G etting Started Adding Events and Data This Simulink model and Stateflow diagram are used in this section sf_explore_ex2 File Edit Simulation Format Tools ephe s2 Heat_on Fan_on Heat_on a On count gt 10 Fan_off What Are the Events There are four Local events Fan_on Fan_off Heat_on andHeat off in the Stateflow diagram TheTi mer parallel AND superstate broadcasts the Local event Fan_on Thetransition from Fan Of f toFan On that is triggered by the broadcast of Local event Fan_on broadcasts the transition actionHeat _on The 5 17 5 Exploring and Searching 5 18 transition fromHeat Of f toHeat On is triggered by the broadcast of the Local event Heat _on Add Local Events When you create the graphical objects in the Stateflow diagram you use the event names as part of the transition labels Adding them as labels does not define them as events in the data dictionary Use either the graphics editor Add menu or the Explorer to add and define events 1 Select Event from the graphics editor Add menu Select Local from the Event submenu Input from Simulink Target Output to Simulink Replace the contents of the name field with the namefan_on Click on the Close button to save the changes and close the Event
174. ent status of the Stateflow diagram e Step through the execution of the Stateflow diagram e Specify display of one of these options at atime the call stack code coverage data values or active states The breakpoints can be changed during runtime and areimmediately enforced When you save the Stateflow diagram all of the debugger settings including breakpoints are saved so that the next time you open the model the breakpoints remain as you left them Runtime Debugging Oncethetarget is built with the debugging code you can then optionally enable or disable the associated runtime options in the Debugger Enabling or disabling the options in the Debugger window affects the Debugger output display results Enabling disabling the options in the Debugger window does not affect the target code and does not require the target to be rebuilt There are also some runtime debugging options that do not require supporting code in the target These options can be dynamically set e Enable disable cycle detection in the Debugger window e Set global breakpoints at Any chart entry Any event broadcast Any state entry e Enable disable local Debugger breakpoints at specific chart or state action execution points in these appropriate property dialog boxes Chart see Editing Chart Stateflow Diagram Properties on page 2 19 State see Editing State Properties on page 2 29 e Enable disable local Debugger breakpoints at a spec
175. ents are added and defined using either the graphics editor Add menu or the Explorer See Add Menu on page 2 48 or Stateflow Explorer User Interface on page 5 5 for more information e The Simulink block connected to the edge triggered event Output to Sim ulink has the Trigger type field set to the equivalent edge triggering type Example Edge Triggered Semantics In this example thetransition from stated tostateB in the Stateflow diagram has a transition action that specifies the broadcast of event1 event1 is defined in Stateflow to be an Output to Simulink with a Rising edgetrigger type The Stateflow block output port for event 1 is connected to the trigger port of the 4 13 4 Defining Stateflow Interfaces band pass filter1 Simulink block Theband pass filteri1 block has its Trigger type field set to rising sf_func3 event v B entry X gt 4 14 Defining O utput to Simulink Event Triggers This sequence is followed when stated is active and the transition from state A to state B is valid and is taken 1 Stated exit actions execute and complete 2 Stated is marked inactive 3 Thetransition action an edge triggered Output to Simulink event is registered but not executed Simulink is controlling the execution and execution control does not shift until the Stateflow block completes 4 StateB is marked active 5 States entry actions execute and com
176. ents drive Stateflow diagram execution an essential question is how are the events broadcast Events are broadcast e Within the Stateflow diagram Local through event broadcast actions e As input events from Simulink e As Imported events from an external code source e Bythesend event_name state_name action language function Events are broadcast in a top down manner starting from the event s parent in the hierarchy Thesend action language function allows refinement of the receive rights associated with the specified event The send action language function sends theevent _name specified tothest at e_name specified the specified event is directed to be received by the state specified See Directed Event Broadcasting on page 6 58 for more information on send Getting Started with Events The flexibility and power provided by parenting and scoping events can be overwhelming and complex to begin with The simplest case to consider is e Create a Simulink model containing a single Stateflow diagram e Use the Simulink implicit event broadcast to awaken the Stateflow diagram e Define events parented by the chart e Define events scope defined as Local e Specify Local event broadcasts within the Stateflow diagram See Example Getting Started Adding Events and Data on page 5 16 for an example of this simplest case Event Name An event name can consist of any alphanumeric and special character combination with the exception of
177. er state remains active then the processing continues in is passed down to active substate s Active parallel AND states are processed Any during actions includingon event_name actions of the state are executed Inner transitions are processed in the search for a valid path within the state If the state is a superstate with no valid transition paths and if the super state remains active then the processing continues in is passed down to active substate s Note that in each of the above steps when a successful transition path is found it is taken The prerequisite for each step is that the exclusive OR state is still active If for any reason the exclusive OR state becomes Semantic Rules Summary inactive its processing is regarded as complete and no further steps are taken e When the execution of a Stateflow diagram is completed it must be in a con sistent state An active state consisting of at least one substate with XOR decomposi tion has exactly one active substate All substates of an active state with AND decomposition are active All substates of an inactive state with either XOR or AND decomposition are inactive e Theorder of execution of parallel AND states in a superstate with parallel AND decomposition is determined by the geometrical sorting of states from top to bottom and then from left to right in the case of a tie Rules for Processing Transitions In summary these
178. erarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if thereis a valid transition as a result of E_ one The transition from state A to state B is now valid because C_one is true 2 Stated exit actions execute and complete exit A 3 Stated is marked inactive 4 Thetransition action A_one is executed and completed 5 States is marked active 6 StateB entry actions execute and complete ent B 7 TheStateflow diagram goes back tosleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one Inner Transitions Example Processing a Third Event Within an Exclu sive OR State Using the same example what happens when a third event E_t wo occurs JA amp _four Al E_one C_one A_one entry entA A_two during durAQ i ie a By StateB is ey entry entB marked active during durB exit exitB E_two C_two A_three Initially the Stateflow diagram is asleep State B is now active Event E_two occurs and awakens the Stateflow diagram Condition C_t wo is false Event E_t wo is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_t wo A potentially valid transition from stateB to state A is detected The transition is not valid because C_two i
179. es Glossary G lossary A 2 Actions Actions take place as part of Stateflow diagram execution The action can be executed as part of a transition from one state to another or depending on the activity status of a state Transitions can have condition actions and transition actions F or example Condition Transition action action switch_off c1 elec_off light_off States can haveentry during exit and on event _name actions For example Power_on entry action1 0 during action20 exittaction30 on switch_off action4 If you enter the name and backslash followed directly by an action or actions without theent ry keyword the action s are interpreted as entry action s This shorthand is useful if you are only specifying ent ry actions The action language defines the categories of actions you can specify and their associated notations An action can bea function call an event to be broadcast a variable to be assigned a value etc For more information see the section titled Action Language on page 6 42 Condition A condition is a Boolean expression to specify that a transition occurs given that the specified expression is true For example neutral clutch_engaged engaged G speed threshold speed gt threshold isa condition second The action language defines the notation to define conditions associated with transitions See the section titled Action Language
180. ese options Menu Choice Description Cut Ctrl X Moves selected object s from the drawing area to the Stateflow clipboard Copy Ctrl C Copies selected object s to the Stateflow clipboard Paste Ctrl V Pastes object s from the Stateflow clipboard to the drawing at the current mouse location Select All Ctrl A Selects all object s in the Stateflow diagram Simulation Menu The Simulation menu provides these options Menu Choice Description Start Ctrl T Start the simulation Pause Pause the simulation Parameters Ctrl E Displays the simulation parameters dialog box See the Using Simulink document for more information on simulation parameters 2 Using the Graphics Editor 2 46 Style Menu Using the Style menu you can change the color of these objects States State labels Transitions Transition labels J unctions Chart All objects of that type are redisplayed in the color you choose You can also change the object selection color from this menu The color submenus of the Style menu provide these color options Black Blue Green Cyan Red Magenta Yellow White Using the Style menu you can also change the font size of any selected text M ain Editor M enus Tools Menu The Tools menu provides these options Menu Choice Description Explore Ctri R Debug Ctrl D Find Ctrl F Parse Parse Diagram Open Simulation Target Open RTW Targ
181. ess block parameters and connect blocks to build models It also provides reference descriptions of each block in the standard Simulink libraries W hat Is Real Time Workshop Real Time Workshop RTW is an automatic C language code generator for Simulink It produces C code directly from Simulink block diagram models and automatically builds programs that can be run in real time in a variety of environments Stateflow works in conjunction with Real Time Workshop in these ways e Stateflow generates high quality integer based code runs on a fixed point processor a floating point processor is not required e RTW generates floating point based code a floating point processor is required e Stateflow blocks are fully integrated for real time code generation and com patible with RTW Note If you want to target Stateflow and RTW generated code for the same processor you need a floating point processor XXV Before You Begin How to Use This Guide xxvi Chapter Quick Reference If you are new tothe Stateflow environment goto Chapter 1 Introduction to get an overview and a quick start If you want to get started right away go to Chapter 8 Tutorial Entering a Stateflow Diagram for step by step instruction on creating a Stateflow diagram For information on using the graphics editor refer to Chapter 2 Using the Graphics Editor Chapter 3 Events and Data describes the nongraphical ob
182. et Displays the Stateflow Explorer Displays the Stateflow Debugger Displays the Stateflow Finder Parse all Stateflow diagrams in the current machine Results of the parse operation are displayed in a pop up window and in the MATLAB command window Parse the current Stateflow diagram Results of the parse operation are displayed in a pop up window and in the MATLAB command window Displays the Target Configuration sfun properties dialog box Displays the Target Configuration rtw properties dialog box 2 47 2 Using the Graphics Editor Add Menu The Add menu provides these options Menu Choice Description Event Data Target Choose a scope from the submenu creates a new untitled event at the machine level in the object hierarchy use the Explorer to modify the parent displays an untitled Event properties dialog box Choose a scope from the submenu creates a new untitled data object at the machine level in the object hierarchy use the E xplorer to modify the parent displays an untitled Data properties dialog box Creates a new untitled target at the machine level in the object hierarchy a target s parent must bea machine displays an untitled Target Configuration properties dialog box In all cases the machine is the object s parent by default Use the Explorer to modify the parent of event or data objects Use the Explorer to delete any of these objects See these sections
183. eting unctions 0 0 20 2 38 Changing Size eshte Pe a A a 2 39 Changing Arrowhead Size 000 c eee eee 2 39 Moving aJ unction 0 0 ccc eee 2 40 Editing unction Properties 000 c cea eee 2 40 Main Editor Menus 000 e eee eee ees 2 42 OVEN VIEW ned ee See PEE we Shee ead ww Yee a ede Eee ees 2 42 File Menu vied Pete Cer eee ee web ee Tee a 2 43 Print AS Submenu 0 00 cee ee 2 44 Edit M nU 2i24 4007 pa ar aneo see es peee dace are es 2 45 Simulation Menu 00 0 ee 2 45 Style Menun das see ee Oe Ga el eek 2 46 T ll Men e iae t RA saan hls AOR te Ae be 2 47 Add MENU Tesia ia Peed neat teks aed Cow tee boot 2 48 Help Menu reru ibeo viste epe mma eee 2 49 iv Contents Defaults File 00 0 000000 cee 2 50 What Is the Defaults File ce eet 2 50 What Do You Need to Know about the Defaults File 2 50 Machine Defaults 0 0 0 eee ee ees 2 50 Defining Color 0 cece ae 2 51 Chart Defaults nuunuu aaaeeeaa 2 51 Target Defaults 0 eee ees 2 52 State Defalis d csa cigiesei dar dite aa otek ered Bw terete a mia ar aei 2 53 Transition Defaults 0 cc ee eee eee 2 53 Junction Defaults 0 0 cc ee eens 2 53 Data Defaults 0 0 eee eens 2 54 Event Defaults 2 0 0 ccc eee eens 2 54 3 Overview 0 0 ccc teen e tetas 3 2 Events and Data 2 cece tee 3 2 Where to Find More In
184. exclusive When a state has exclusive OR decomposition only one substate can be active at a time The children of exclusive OR decomposition parents are OR states Active and Inactive States States have the Boolean characteristic of being active or inactive The occurrence of events drives the execution of the Stateflow diagram At any point in the execution of a Stateflow diagram there will be some combination of active and inactive states These are some possible combinations e Multiple active states with parallel AND decomposition In this example when state A is active Al and A2 are active 6 11 6 Notations e An active state with parallel AND decomposition and an active state with exclusive OR decomposition In this example stateB andC c2 or stateB andC C1 areactiveat the sametime e One active state with exclusive OR decomposition In this example stateB or state A A1 or stateA A2 is active at any onetime MS a P When a given state is active all of its ancestor states are also active See the section titled Semantics of Active and Inactive States on page 7 5 for more information What Are Combination States When a Stateflow diagram has states with parallel AND decomposition multiple states can be active simultaneously A combination state is a notational representation of those multiple states For example a Stateflow diagram could have two active states with parallel
185. external code source 3 14 index property 3 16 input from Simulink 3 10 local 3 10 name property 3 6 output to Simulink 3 12 parent and scope combinations 3 15 parent property 3 7 port property 3 16 properties 3 5 properties dialog box 5 9 apply button 5 11 close button 5 11 debugger breakpoint fields 5 11 description field 5 11 document link field 5 11 index field 5 10 name field 5 9 parent field 5 9 port field 5 10 revert button 5 11 scope field 5 9 trigger field 5 10 representing hierarchy 6 9 trigger property 3 17 what is 3 5 event actions and superstates semantics example 7 43 event broadcast state action notation example 6 57 transition action notation example 6 57 event input from Simulink add and choose parent task 4 16 apply the changes task 4 17 choose scope task 4 16 select the trigger task 4 17 tasks 4 16 trigger type determining 3 18 event output to Simulink add and choose a parent task 4 20 apply and save task 4 21 choose scope task 4 20 task overview 4 10 tasks 4 20 event triggers defining edge triggered 4 13 defining function call 4 10 defining output to Simulink 4 8 edge triggered semantics example 4 13 function call example 4 11 function call semantics 4 12 events getting started 3 6 getting started example 5 16 glossary definition A 6 how are they broadcast 3 6 input from Simulink function call and edge triggers 3 19 scope property 3 10 Index events and data getting started add local eve
186. f the block Defining a Continuous Stateflow Block To define a continuous Stateflow block the chart Update method set in the Chart Properties dialog box is set to Continuous See Editing Chart Stateflow Diagram Properties on page 2 19 Considerations in Choosing Continuous Update The availability of intermediate data makes it possible for the solver to back up in time to precisely locate a zero crossing Refer to Using Simulink for further information on zero crossings Use of the intermediate time point information can provide increased simulation accuracy To support the Continuous update method Stateflow keeps an extra copy of all its data In most cases including continuous time simulations the Inherited method provides consistent results The timing of state and output changes of the Stateflow block is entirely consistent with that of the continuous plant model 4 7 4 Defining Stateflow Interfaces There are situations when changes within the Stateflow block must be felt immediately by the plant and a Continuous update is needed e Data Output to Simulink that is a direct function of data Input from Simulink and the data is updated by the Stateflow diagram stateduring actions in particular e Models in which Stateflow states correspond to intrinsic physical states such as the onset of static friction or the polarity of a magnetic domain This is in contrast to states that are assigned for exampl
187. flag to the code generation command in the Coder Command field See Make Command Customization on page 9 23 and Compiling Code Building Targets on page 9 26 for more information on the Coder Command field If you have bi tops enabled some of the logical binary operators and unary operators are interpreted as bitwise operators See Binary Operations on page 6 45 and Unary Operations on page 6 47 for specific interpretations Action Language Binary Operations Binary operations fall into these categories e Numerical Example Description a b Addition of two operands a b Subtraction of one operand from the other a b Multiplication of two operands aj b Division of one operand by the other a b Modulus e Logical the default setting bit operations not enabled Example Description a b Comparison of equality of two operands a amp b Logical AND of two operands a amp amp b 6 45 6 N otations Example Description a b Logical OR of two operands a b a b Comparison of inequality of two operands a b a gt b Comparison of the first operand greater than the second operand a lt b Comparison of the first operand less than the second operand a gt b Comparison of the first operand greater than or equal to the second operand a lt b Comparison of the first operand less than or equal to the second operand Logical bit operations enabled
188. flow diagram Power_on Switch_on Z p lt Ride l y Speed gt Max_speed 1i Power_off nOn ooo Start_button i ie Stopped vat Switch_off SY p Fide done gt i Emergency_stop Add and Define Event Objects Events are added removed and edited using the Explorer These events must be defined Ride_done Switch_on Switch off Start _button Emergency stop Add and Define a Local Event Ri de_done is the only local event in the carousel example 1 Choose Explore from the Tools menu of the graphics editor window to dis play the Explorer 2 Select the parent for the new event Double click on the machine name the name you specified when you saved the Simulink model in the Object Hierarchy list Double click on the chart 8 18 Procedure name the name you specified on the Stateflow block The chart will be the parent for all the events in the carousel example 3 Choose Event from the Explorer Add menu The Event properties dialog box is displayed 4 Enter Ri de_done in the name field 5 Select Local in the Scope field 6 Click on the Close button to save the changes and close the dialog box Add and Define Input from Simulink Events There are four Input from Simulink events to add and define Swit ch_on Switch _off Start button andEmergency_ stop 1 Choose Explore from the Tools menu of the graphics editor window to dis play the Explorer 2 Select the parent f
189. font size The font size of all labels on any selected states is adjusted 2 27 2 Using the Graphics Editor 2 28 Changing Arrowhead Size The arrowhead sizeis a property of the destination object Changing one of the incoming arrowheads of a state causes all incoming arrowheads tothat state to be adjusted to the same size The arrowhead size of any selected states is adjusted To adjust arrowhead size from the State shortcut menu 1 Select the state s whose incoming arrowhead size you want to change 2 Placethecursor over a selected state click the right mouse button to display the shortcut menu Place the cursor over Arrowhead Size The shortcut menu disappears and a numeric size is displayed 3 Click and drag horizontally to the left to decrease the arrowhead size or to the right to increase the arrowhead size The numeric display adjusts to show the currently selected arrowhead size Moving States To move a state select drag and release it in a new position If you move a grouped superstate the superstate and its contents are moved W orking with States Editing State Properties Select the state click the right mouse button to display the State shortcut menus and choose Properties This is the State properties dialog box 2 29 2 Using the Graphics Editor This table lists and describes the state object fields Field Description Name Stateflow diagram name read only click on this hyper
190. for more information Example Getting Started Adding Events and Data on page 5 16 and Stateflow Explorer User Interface on page 5 5 For more information on the Event Data and Target Configuration property dialog boxes see these sections e Event Properties Dialog Box on page 5 9 e Data Properties Dialog Box on page 5 12 e Adding and Specifying a Stand Alone Target on page 9 16 2 48 M ain Editor M enus Help Menu The Help menu provides these options Menu Choice Description Topics HTML Displays Stateflow online helpin an HTML browser An online version of the Stateflow User s Guideis one of the options available from the online help Help Desk HTML Displays the MATLAB Help Desk in an HTML browser About Stateflow Displays a pop up window with software version information 2 49 2 Using the Graphics Editor Defaults File What Is the Defaults File The defaults file contains default settings for e Machines e Charts e Targets e States e Transitions e J unctions e Data e Events What Do You Need to Know about the Defaults File The fileis calleddefaults no file extension and is located in the directory listed bysf Root that is created as part of the installation process You can edit this file to modify and customize the default values Y ou can add defaults for any user writeable property The file is executed at initialization time when St
191. for the string specified in the Look for field e Name Search the name fields of the specified object types for the string specified in the Look for field Description Search the description fields of the specified object types for the string specified in the Look for field Stateflow Finder User Interface Search Method By default the Search Method is Normal Wildcard regular expression Alternatively you can click on the Exact Word match option if you are searching for a particular sequence of one or more words A regular expression is a string composed of letters numbers and special symbols that defines one or more strings Some characters have special meaning when used in a regular expression while other characters are interpreted as themselves Any other character appearing in a regular expression is ordinary unless a precedes it These are the special characters supported by Stateflow Character Description nw Start of string End of string Any character Quote the next character Match zero or more Match one or more Set of characters Object Type Specify the object type s to search by toggling the radio boxes A check mark indicates that the object is included in the search criteria By default all object types are included in the search criteria Object Types include e States e Transitions e J unctions e Events e Data e Targets 5 21 5 Exploring and Searching
192. formation on Creating Modifying and Deleting Events and Data 0c eee eee 3 4 EVentS ooo hatin 88 80 E ed Oe ee ee 3 5 What Is an Event 00000 oreren 3 5 Event Properties ssussua uaaa a 3 5 How Are Events Broadcast sasa sanaaa 3 6 Getting Started with Events ssssa sasae 3 6 Ev nt NamM iaae sureres esik paaa oa a A a A E 3 6 Event Description ssasaas asana ea 3 7 Event Parent Types 0 0 eee es 3 7 Events Hierarchy and Scope 0 cece eee ees 3 9 Event SCOpe srrrrieriroris t tmine das Geeta Wek od qnaoicd woe doe a 3 10 Table of Event Parent and Scope Combinations 3 15 Event POPES s omiaa aaae ogni hon catback int Beeson gee aed ok aao verte ano 3 16 Event MAICES 6 iii iiss a sonnin ao cea ore a mace a oo PEI a dose raat ECE 3 16 Event Triggers 0 cece eee 3 17 Determining Overall Input Trigger Type 3 18 Combining Function Call and Edge Triggers 3 19 vi Contents Implicit Local Events 00 cee eee eee 3 20 OVENVIEW i aa uina ean kee fae RG Yd Kiet ee ee Oe De eee es 3 20 Types of Implicit Events 2 0 c eee 3 20 Example Implicit Local Event 000 eee eae 3 21 Data sf ech dg rerep ei re peace EE EEEE ANE 3 22 What Is a Data Object 2 eee 3 22 Getting Started with Data 0 0 0 0 a eee 3 23 Bata Nane eae 3 24 Data Description 2 cece 3 24 Dat
193. g Event Inputs from Simulink When you add an event input a single Simulink trigger port is added to the top of the Stateflow block Select the Trigger The trigger defines how the Stateflow block s input events are handled in the context of their Simulink model The Trigger type indicates what kind of signal has meaning for the input event The Trigger can have these values Keyword Description Either Edge Either rising or falling edge trigger where the control signal changes either from 0 toa nonzero value from a negative value to a pos itive value or from a positive value to a nega tive value Rising Edge Rising edge trigger where the control signal changes from either from 0 to a positive value or from a negative value to a positive value Falling Edge Falling edge trigger where the control signal changes from either 0 to a negative value or from a positive value to a negative value Function Call Function call triggered Each Stateflow block can only have one overall trigger type See Determining Overall Input Trigger Type on page 3 18 for more information Apply the Changes Click on the Apply button to save the properties Click on the Close button to save the properties and close the dialog box 4 17 4 Defining Stateflow Interfaces 4 18 Data Inputs from Simulink Tasks to Define a Data Input from Simulink These tasks describe how to add and define the necessary fields for a dat
194. ge 3 34 See the section titled Action Language on page 6 42 for more information on the action language Getting Started with Data The flexibility and power provided by parenting and scoping data can be overwhelming and complex to begin with The simplest case to consider to start with is e Create a Simulink model containing a single Stateflow diagram e Usethe Simulink implicit event broadcast to awaken the Stateflow diagram e Define data parented by the chart e Define the data scope to be Local e Specify Local events broadcast in the Stateflow diagram See Example Getting Started Adding Events and Data on page 5 16 for an example of this simplest case 3 23 3 Events and Data Data Name A data name can consist of any alphanumeric and special character combination with the exception of embedded spaces The name cannot begin with a numeric character The length of a name is not restricted Data Description The description can consist of any ASCII text you want to enter to describe the object 3 24 Data Data Parent Types You must choose a parent when defining a data object Y ou explicitly choose the parent through theE xplorer The chart is implicitly chosen as the parent if you use the graphics editor Add menu Data objects can have parents with these object types e Machine The machine is the collection of all Stateflow blocks in the Simulink model In this example the machine is the collectio
195. generate stand alone code suitable to target for a particular processor Stateflow generates simulation code sf un target for the On_off Stateflow block Theon_off Stateflow block and its Simulink model is not designed or intended to generate stand alone code for a specific target processor For More Information See Generating Code for more information on code generation 1 35 1 Introduction 1 36 Using the Graphics Editor The Graphics Editor Main Window Shortcut Menus Using the Graphics Editor Working with Charts Stateflow Diagrams Working with States Working with Transitions Working with J unctions Main Editor Menus Defaults File 2 2 2 10 2 15 2 18 2 24 2 31 2 38 2 42 2 50 2 Using the Graphics Editor The Graphics Editor Main Window Overview Using the graphics editor you can visually model complex reactive systems based on finite state machinetheory and statechart formalisms The graphics editor is designed with productivity in mind The user interface features a number of productivity boosts see Productivity Boosts on page 2 7 See Using Stateflow on page 1 22 for a quick tutorial on using the graphics editor Main Window Components The main window consists of a toolbar pull down menus and a drawing area The window is titled with the name of the current Stateflow diagram The toolbar on the left hand side contains obj
196. gets Informational messages and any error messages are displayed in a popup window and also in the MATLAB command window Stateflow Coder must be present to build stand alone targets 9 29 9 Generating Code Typical Code Generation Related Error Messages Overview Code generation related error messages can originate from the parser the simulation code generator Stateflow Coder or from the external C compiler If you are explicitly parsing generating code or building a target it is apparent which operation generated the error It is less clear which operation generated the error if you are implicitly performing these operations through one of these methods e Choosing Start from the graphics editor Simulation menu e Choosing Start from the Simulink model Simulation menu e Choosing Debug from the graphics editor Tools menu choosing debugging options and clicking on the Go button A common error message when a simulation is started via one of those options is Error using gt toolbox stateflow stateflow private intfcn method Stateflow S Function build failed If you receive this message you may have parser code generation or target generation errors Errors are displayed in red in an informational dialog box and alsoin the MATLAB command window Note that whenever you see a linein the error message dialog box you can double click on that line to zoom in in the Stateflow diagram on the object
197. gment from a default transition to a connective junction The transition segments beginning from a twelve o clock position and progressing clockwise on the connective junction are evaluated for validity The first transition segment 7 20 Default Transitions evaluated labeled with C_t wo is valid The complete transition from the default transition to state B B2 is valid 4 StateB B1 executes and completes exi t actions exit B1 5 States B1 is marked inactive 6 StateB B2 is marked active 7 StateB B2 executes and completes entry actions ent B2 8 TheStateflow diagram goes back tosleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with the occurrence of any event Example Default Transition and a History J unction This example shows the semantics of a superstate and a history junction Stated is active entry entAt E_one during durAf exit exitAG Bi E entB 9 during durB exit exitB Bi entry entB1 B2 during durBi entry entB2 exit exitB1 during durB2 exit exitB2 B3 B4 entry emtB3 entry entB4 during durB3 during durB4 exit exitB3 exit exitB4 Initially the Stateflow diagram is asleep State A is active There is a history junction and stateB4 was the last active substate of superstateB Event E_one occurs and awakens the Stateflow diagram EventE
198. guage function sends theevent_name specified tothestate_name specified the specified event is directed to be received by the state specified See Directed Event Broadcasting on page 6 58 for more information on send 3 15 3 Events and Data 3 16 Event Ports Ports are used to connect the Stateflow block to other Simulink blocks Each event output in a Stateflow diagram corresponds to a port on the Stateflow block Ports have numbers that indicate the relative position of that port on the Stateflow block Each event output is represented by the addition of a Simulink port on the right side of the Stateflow block E vent ports appear below any data ports on the right side of the Stateflow block Each port on the Stateflow block must be connected to a port on an appropriate block in the Simulink model sf_ev_d_ports_ex File Edit Simulation Format Tools Output to Simulink events port 3 port 4 Event Indices Event indices are used to correlate the order of the event defined as an input from Simulink within the Stateflow diagram with the vector of inputs from Simulink Event inputs are represented by the addition of a Simulink trigger port on the top of the Stateflow block If there are multiple event inputs they are vectored into that single trigger port using a Simulink MUX block You Events must make sure that the order of the input elements in the vector corresponds properly to the index numbers defined in
199. hat is representative of the carousel system What are the states What is the decomposition of the states What should the state labels be Are there junctions What are the transitions Are there default transitions Are there events Is there data What Are the States Begin by listing possible states in the carousel system A good place to begin is by considering the physical components of the carousel There are likely to be states associated in some way with some of the physical components Audio The audio components are a subset of the carousel system as a whole If the audio system is enabled on the operator s console music plays when the rideis in progress In this tutorial the substates of the audio component are not discussed in any detail Designing the Carousel Stateflow Diagram Video The video components are a subset of the carousel system as a whole If the video system is enabled on the operator s console an image of a rotating platform is displayed on the operator s console In this tutorial the substates of the video component are not discussed in any detail Ride The platform movement is the ride There is a state associated with the ride as a whole In the simplest sense the ride is either in progress or not Thereis one state Ride that consists of two substates 0n and Stopped Timer A state for a timer is somewhat less obvious than the others The duration of the ride is set by the
200. he Simulink chart Output to chart Simulink and any offspring of the Simulink chart Temporary chart state Parent only none of its offspring Workspace machine chart Parent and any of its offspring Constant machine chart Parent and any of its offspring state Exported machine Any offspring of the machine and external sources Imported machine Any offspring of the machine Data Ports Ports are used to connect the Stateflow block to other Simulink blocks Each input or output in a Stateflow diagram corresponds to a port on the Stateflow block Ports have numbers that indicate the relative position of that port on the Stateflow block Each data input is represented by the addition of a Simulink port on the left side of the Stateflow block Each data output is represented by the addition of a Simulink port on the right side of the Stateflow block Each 3 32 Data port on the Stateflow block must be connected toa port on an appropriate block in the Simulink model sf_ev_d_ports_ex iol x Eile Edit Simulation Format Tools Output to Input from Simulink Simulink data data potl port 1 _ port2 port 2 Data Attributes Data objects have these data type attributes that define how data objects are represented in the generated code e Units e Type e Initial Minimum and Maximum Units Units is a user entered string that describes the units of the data type 3 33 3 Events and Data
201. he Trigger type indicates what kind of signal has meaning for the input or output event Trigger types fall into two general categories edge or function call triggered Stateflow Explorer User Interface The Trigger property can have these values e Either Edge e Rising Edge Falling Edge e Function Call For more information see these sections Event Triggers on page 3 17 and Determining Overall Input Trigger Type on page 3 18 Debugger Breakpoints Click in the checkbox display a checkmark to set a breakpoint either at the start of the event broadcast Start of Broadcast or at the end of the event broadcast End of Broadcast Description Click in the text field area labeled Description and enter any textual comments or descriptions for the object Document Link Enter a web URL address or a general MATLAB command in the Document Link field Examples of links are www mat hworks com mailto email_address edit spec data speed txt Apply Revert and Close Buttons Click on the Apply button to save the current values Click on the Revert button to go back to the original values after changes have been applied but before the dialog box has been closed The Revert button is grayed out until a change has been applied Click on the Close button to save the current values and close the dialog box 5 11 5 Exploring and Searching 5 12 Data Properties Dialog Box This is an untitled data object properties
202. he data dictionary by using the Explorer The parser evaluates entries and relationships between entries in the data dictionary to verify the notation is correct O verview Keywords These Stateflow keywords have special meaning in the notation Keyword Shorthand Meaning change data_name during entry entry state name exit chg data_name du en en state_ name ex A condition function that is evaluated as true when the value of dat a_name specified as the argument changes Actions that follow are exe cuted as part of a state s during action Actions that follow are exe cuted as part of a state s entry action Generates a local event when the specified st ate_name is entered Actions that follow are exe cuted as part of a state s exit action 6 5 6 Notations Keyword Shorthand Meaning exit state_name ex state_name Generates a local event when the specified st ate_name is exited in state_name none A condition function that is evaluated as true when the state name specified asthe argument is active on event_name none Actions that follow are exe cuted when theevent_name specified as an argument to theon keyword is broadcast send event name state name none Send theevent name speci fied tothestate_name speci fied directed event broadcasting matlab eval String argl arg2 ml Action specifies a call using MATLAB function notation
203. he occurrence of events under certain conditions State transition diagrams STDs and bubble diagrams are graphical representations based on this approach Stateflow Representations Stateflow uses a variant of the finite state machine notation established by Harel 1 Using Stateflow you create Stateflow diagrams A Stateflow diagram is a graphical representation of a finite state machine where states and transitions form the basic building blocks of the system Y ou can also represent flow stateless diagrams using Stateflow Stateflow provides a block that you include in a Simulink model The collection of Stateflow blocks in a Simulink model is the Stateflow machine Additionally Stateflow enables the representation of hierarchy parallelism and history Hierarchy enables you to organize complex systems by defining a parent offspring object structure For example you can organize states within other higher level states A system with parallelism can have two or more orthogonal states active at the same time History provides the means to specify the destination state of a transition based on historical information Finite State M achine Concepts These characteristics enhance the usefulness of this approach and go beyond what STDs and bubble diagrams provide Notations A notation defines a set of objects and the rules that govern the relationships between those objects Stateflow notation provides a common language to communicat
204. hecks to see if there is a valid transition as a result of E_one Thereis a valid implicit transition from state A A1 to state B B1 Condition C_one is true State A executes and completes during actions durA State A A1 executes and completes exi t actions exitA1 State A A1 is marked inactive State A executes and completes exit actions exit A State A is marked inactive The transition action A is executed and completed State B is marked active State B executes and completes entry actions ent B 10 State B B1 is marked active 11 State B B1 executes and completesent ry actions ent B1 12 The Stateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one Condition Actions Condition Actions Example Actions Specified as Condition Actions This example shows the semantics of a simple condition action in a multiple segment transition Stated is Al active entry entA during durAg exit exitAQ E_one A_one C entry entC during durC exit exitCG C_one Bi entry entB during durB exit exitB Initially the Stateflow diagram is asleep Stated is active Event _one occurs and awakens the Stateflow diagram Conditions C_one andC_two are false Event _one is processed from the root of the Stateflow diagram down through the hierarchy of the
205. his S function is the agent Simulink interacts with for simulation and analysis The control behavior that Stateflow models complements the algorithmic behavior modeled in Simulink block diagrams By incorporating Stateflow blocks into Simulink models you can add event driven behavior to Simulink simulations You create models that represent both data and control flow by combining Stateflow blocks with the standard Simulink and toolbox blocksets These combined models are simulated using Simulink stateflow Example This example shows how to open the Stateflow model window and use a Stateflow block to create a Simulink model 1 Invoke Stateflow gt gt stateflow The Stateflow model window and an untitled Simulink model containing a Stateflow block are displayed eS sflib ojx File Edit Simulation Format Tools ee a AA Untitled Double click to open the This i a manual Statetlow Examples Library switch convenient for generting events EA untitled Bl x Eile Edit Simulation Format Tools Untitled 11 7 stateflow 2 Doubleclick on the untitled Stateflow block in the untitled Simulink model to invoke a Stateflow editor window Eq Stateflow Untitled File Edit Simulation Style Tools Add Help 3 You areready to create the underlying Stateflow diagram 11 8 sfprint Purpose Syntax Description Print the visible portion of the Stateflow diagram Sf pri Sf pri Sf pri Sf pri
206. i Ed Exploring sf_exp_srch explore_ex iof x machine M Mae Edt Add Help Hypertext link to Object Hierarchy Contents of chart sf_exp_srch explore_ex parent M st exp srch chart C cE Event On local te oft event input 1 label search ex state knr RA eventi output 2 Data data local datal input 1 label dataZ output 1 data4 workspace data3 temporary data5 constant M essage area O bject Hierarchy The Object Hierarchy machines M charts C and states is displayed in the left hand pane A character indicates that the hierarchy machine M chart C or state can be expanded by double clicking on that entry or by clicking on the character A character indicates thereis nothing to expand As you move the cursor over an Object Hierarchy entry it is shown in blue and indicates the cursor focus The focus tells you which object would be selected if you clicked the mouse at that moment Clicking on an entry in the Object Hierarchy selects that entry Selection is indicated by a blue background and bold text 5 5 5 Exploring and Searching Contents of Events data and target objects parented by the currently selected object in the Object Hierarchy are displayed in the Contents of pane Each type of object has a heading label that also indicates the number of objects of that type defined These are the possible parent and object combinations Machine M Chart C State Event yes
207. ialog box Choosing Explore from the graphics editor Tools menu to display the Explorer Double click on a stand alone target to display its Target Configuration properties dialog box Click on the Generate Code Only or Build Stateflow Target buttons in the Target Configuration dialog box Choosing Parameters from a Simulation menu either the Simulink model or the graphics editor menu Click on the RTW tab Click on the Build button in the RTW tab of the Simulation parameters dialog box In all cases a popup information window is displayed when the parsing is com plete If the parsing is unsuccessful one error at a time is displayed in red in the informational window The Stateflow diagram automatically selects and pans to the object containing the parse error Double click on the error in the information window to bring the Stateflow diagram to the forefront zoom fit to view and select the object containing the parse error Press the space bar to zoom back out Fix the error and reparse the Stateflow diagram Informa tional messages are also displayed in the MATLAB command window 9 11 9 Generating Code These steps describe parsing assuming this Stateflow diagram 1 Parse the Stateflow diagram Choose Parse Diagram from the graphics editor Tools menu to parse the Stateflow diagram Stated in the upper left hand corner is selected and this 9 12 Parsing message is displayed in the popup window and the MATLA
208. icate the design information conveyed by a Stateflow diagram Stateflow notation consists of e A set of graphical objects e A set of nongraphical text based objects e Defined relationships between those objects e Keywords e Action language Motivation Behind the Notation Chapter 2 Using the Graphics Editor and Chapter 5 Exploring and Searching discuss how to use the product to create the various objects K nowing how to create the objects is the first step to designing and implementing a Stateflow diagram The next step is understanding and using the notation to create a well designed and efficient Stateflow diagram This chapter focuses on the notation the supported relationships amongst the graphical objects and the action language that dictates the actions that can be associated with states and transitions The Stateflow notation supports many different ways of representing desired system behavior The representation you choose directly affects the efficiency of the generated code You can use the notation to optimize for these code attributes e Speed e Code size e Memory use See Using the Notation Efficiently on page 9 7 for more information O verview How Is the Notation Checked The parser evaluates the graphical and nongraphical objects in each Stateflow machine against the supported Stateflow notation and the action language syntax Errors are displayed in informational popup windows See
209. ific transition either when thetransition is tested or when it is determined to be valid in the O verview Transition property dialog box see E diting Transition Properties on page 2 36 e Enable disable local Debugger breakpoints based on a specific event broad cast see Event Properties Dialog Box on page 5 9 10 5 10 Debugging Stateflow Debugger User Interface Debugger Main Window This is the Debugger main window as it appears when first invoked a Stateflow Debugger Debugging untitled 10 6 Stateflow Debugger User Interface This is the Debugger main window as it appears when a debug session is active a Stateflow Debugger Debugging sf_intro_example 10 7 10 Debugging 10 8 Status Display Area Once a debugging session is in progress these status items are displayed in the upper portion of the Debugger window The currently executing model is displayed in the Executing field The execution point that the Debugger is halted at is displayed in the Stopped field Consecutive displays of this field show each semantic step being executed The event being processed is displayed in the Current Event field The current simulation time is displayed in the Simulation field The percentage of code that has been covered thus far in the simulation is displayed in the Code Coverage field Break On Controls Use the Break On controls to specify global breakp
210. iggers Since Function Call triggers take precedence over Edge trigger types any Edge triggered events defined in the input vector will be ignored This example illustrates an alternative method to combine Function Call triggered events and Edge triggered events sf_ev_d_func_ex Eile Edit Simulation Format Tools Rising Edge iy Input fromm Simulink event All four Output to Simulink events are Falling Edge M t Function Input from Call Simulink event triggered Generator aa ar oh inputeventst Input from imulink Simulink event a aan is conto F u ncti on Call triggered 3 19 3 Events and Data Implicit Local Events 3 20 Overview There is a set of implicit local events that can be used within the Stateflow diagram These events are very useful to define conditional activity based on when a specified state has been entered or exited or when a data value has changed Only implicit events that are referenced in the Stateflow diagram are broadcast Implicit local events are parented by the chart Any offspring of the chart can trigger on the event receive rights The state name and data_object_name must be unique within the chart The names can be qualified with ancestor names in the hierarchy if necessary Types of Implicit Events You can specify these events in any Stateflow diagram without performing any explicit definition The set includes e entry state_name Generates a local event when
211. ight to left and from the bottom of to the top of the Stateflow diagram and then exit the superstate This is the reverse of entry into such superstates J ust before exiting each state the state s exi t action is executed Note that when executing theexi t action the state is still marked active A state exit is complete when it is marked inactive After exiting all activestates along thetransition path thetransition actions of the path are executed in the order they appear along the path At this point the transition into new states is executed in a top down hierarchical manner When entering an exclusive OR state its superstate with exclusive OR decomposition is entered first When entering a parallel AND state its superstate with parallel AND decomposition is also entered Note that all siblings of this parallel AND state must also be entered These children are entered in a deterministic order geometrically from left to right and from the top to the bottom of the Stateflow diagram This is the reverse of exit from such superstates J ust after entering each state its entry action is executed Note when executing theentry action the state is already marked active When the transition path terminates on the edges of a superstate the entry into its substate s is determined by processing the default transition paths of the superstate When thetransition path crosses the edges of a superstate to terminate on a
212. imulink at the defined regular sample times sf_discrete_ex Sl x File Edit Simulation Format Tools The outputs of a sampled Stateflow block are held after the execution of the block Defining an Inherited Stateflow Block These are essential conditions that define an inherited trigger Stateflow block e The chart Update method set in the Chart Properties dialog box is set to Triggered or Inherited See Editing Chart Stateflow Diagram Properties on page 2 19 e The chart has an Input from Simulink data object defined added and defined using either the graphics editor Add menu or the Explorer See Add Menu on page 2 48 or Tasks to Define a Data Input from Simulink on page 4 18 The chart sample time is determined by Simulink to be consis tent with the rate of the incoming data signal Defining the Stateflow Block Update M ethod Example Inherited Stateflow Block A Stateflow block that is not explicitly triggered via the trigger port nor is a discrete sample time specified can be triggered by Simulink The Stateflow block is called by Simulink at a sample time determined by Simulink In this example morethan one Input from Simulink data object is defined The sample times are determined by Simulink to be consistent with the rates of both incoming signals sf_inherit_ex File Edit Simulation Format Tools The outputs of an inherited trigger Stateflow block are held after the execution o
213. ine Once a parent is chosen that object is known in the hierarchy from the parent downwards including the parent s offspring F or example a data object parented by the machine is accessible by that machine by any charts within that machine and by any states within that machine The hierarchy of the graphical objects is easily and automatically handled for you by the graphics editor You manage the hierarchy of nongraphical objects through the Explorer or the graphics editor Add menu Defining Stateflow Interfaces Each Stateflow block corresponds toa single Stateflow diagram The Stateflow block interfaces to its Simulink model The Stateflow block may interface to code sources external to the Simulink model data events custom code Stateflow diagrams are event driven Events can be local to the Stateflow block or can be propagated to and from Simulink and code sources external to Simulink Data can be local to the Stateflow block or can be shared with and passed to the Simulink model and to code sources external to the Simulink model You must define the interface to each Stateflow block Defining the interface for a Stateflow block can involve some or all of these tasks e Defining the Stateflow block update method e Defining Output to Simulink events e Adding and defining nonlocal events and nonlocal data within the Stateflow diagram e Defining relationships with any external sources Anatomy of a Model and Machine In
214. information on how the hierarchy representations are interpreted see Chapter 7 Semantics Example Representing State Hierarchy This is an example of how state hierarchy is represented Car_done Car_made Parts_assembled Car_shipped The Stateflow diagram is the parent of Car_done Car_done isthe parent state of theCar_made andCar_shipped states Car_made is also a parent tothe Parts_assembl ed andCar painted states Parts_ assembled andCar_painted are children of theCar_made state The machine is the root of the Stateflow hierarchy The Stateflow diagram is represented by the character Each level in the hierarchy of states is 6 7 6 N otations separated by the character The full hierarchy representation of the state names in this example is e Car_done e Car_done Car_made e Car_done Car_ shi pped e Car_done Car_made Parts_ assembled e Car_done Car_made Painted Example Representing Transition Hierarchy This is an example of how transition hierarchy is represented Power_on switch_high swtich_cold Cald A transition s hierarchy is described in terms of the transition s parent source and destination The parent is the lowest level that the transition Source and destination is contained within The machine is the root of the hierarchy The Stateflow diagram is represented by the character Each level in the hierarchy of states is separated by the characte
215. ing options in preliminary simulation target builds to ensure that the model is behaving as you expect to evaluate code coverage and to perform dynamic checking When you save the Stateflow diagram all of the debugger settings including breakpoints are saved Generally speaking debugging options should be disabled for RTW and standalone targets The Debugger does not interact with RTW or standalone targets and the overhead incurred from the added instrumented code is undesirable Stateflow Dynamic Checker Stateflow Dynamic Checker is currently available if you have a Stateflow license Stateflow Dynamic Checker is useful for debugging During a simulation the Dynamic Checker evaluates the coverage of the simulation i e the percentage of unprocessed transitions states that are visited In addition you can choose to detect these conditions state inconsistencies data range violations transition conflicts and cyclic behavior Generally speaking the Dynamic Checker is used for simulation and options should be disabled for RTW and standalone targets The overhead incurred from the added instrumented code is undesirable in these targets Enabling most of the dynamic checking options adds instrumentation code to the target See Enable Dynamic Checker Options on page 9 24 and Dynamic Checker Options on page 10 10 for more information O verview Typical Debugging Tasks These are some typical debugging tasks
216. ing the right mouse button in an area outside the borders of all states The W orking with States Stateflow diagram decomposition reverts to exclusive OR decomposition if all states are deleted Cut Copy Paste Font Size Arrowhead Size Parallel AND Show Hide Group UnGroup Fit To View Select All Explore Find Properties Creating Deleting States Tocreate one state at a time click on the State button in the toolbar and then click on a location in the drawing area Tocreate multiple states double click on the State button in the toolbar The button is now in multiple object mode Click anywhere in the drawing area to place a state in the drawing area Additional clicks in the drawing area create additional states Click on the State button or press the Escape key to cancel the operation Exclusive OR state Parallel AND state To delete a state select it and choose Cut CtrI X from the Edit or any shortcut menu or press the Delete key 2 25 2 Using the Graphics Editor 2 26 Labeling States The character is the default empty label for states Click on the to edit the label Press the Return key to continue the label on the next line Deselect the object to exit the edit State labels have this general format name entry during exit on event _name The keywords entry Shorthand en during Shorthand du exit shorthand ex andon identify actions associated w
217. ink on page 4 16 Data Inputs from Simulink on page 4 18 Event Outputs to Simulink on page 4 20 Data Outputs to Simulink on page 4 22 Defining the Interface to External Sources on page 4 25 Typical Searching Tasks Using the Finder you can e Search the data dictionary for objects Searches are performed across all of the Stateflow diagrams within a Simulink model Stateflow machine Search for all objects that contain a specified string or subset of a string in the label name description or any combination thereof of the object wildcards regular expressions are supported See Searching for an Exact String Match on page 5 28 Search for all objects that have an exact word match in the label name description or any combination thereof of the object See Searching for an Exact String Match on page 5 28 Search for all objects of a specified object type See Searching for All Objects of a Specified Object Type on page 5 30 e Perform certain actions on objects listed in the search results display area Edit object properties See Searching for an Object to Edit Properties on page 5 34 Automatically select objects in their Stateflow diagrams Stateflow Explorer User Interface Stateflow Explorer User Interface Explorer Main Window This is the Explorer main window showing the object hierarchy of an example chart explore ex h
218. ink blocksets These combined models are simulated using Simulink The Using Simulink document describes how to work with Simulink It explains how to manipulate Simulink blocks access block parameters and connect blocks to build models It also provides reference descriptions of each block in the standard Simulink libraries State A state describes a mode of a reactive system A reactive system has many possible states States in a Stateflow diagram represent these modes The activity or inactivity of the states dynamically changes based on events and conditions Every state has hierarchy In a Stateflow diagram consisting of a single state that state s parent is the Stateflow diagram itself A state also has history that applies to its level of hierarchy in the Stateflow diagram States can have G lossary A 10 actions that are executed in a sequence based upon action type The action types are entry during exit oron event _name actions Name Button Icon Description State fe Use a state to depict a mode of the system Stateflow Block The Statefl ow block is a masked Simulink model and is equivalent toan empty untitled Stateflow diagram Use the Stateflow block to include a Stateflow diagram in a Simulink model The control behavior that Stateflow models complements the algorithmic behavior modeled in Simulink block diagrams By incorporating Stateflow blocks into Simulink models you can add complex even
219. ion toaJ unction 7 20 Example Default Transition and a History J unction 7 21 Example Labeled Default Transitions 04 7 23 Inner Transitions 0 0 unauna ccc cece eens 7 25 Example Processing One Event Within an Exclusive OR State ccc ees 7 25 Example Processing a Second Event Within an Exclusive OR State 1 cee 7 26 Example Processing a Third Event Within an Exclusive OR State oroen iert E Ene ee 7 27 Example Processing One Event with an Inner Transition toa Connective UNCION 0 ce ees 7 28 Example Processing a Second Event with an Inner Transition toa Connective UNCLION 0 ce ees 7 29 Example Inner Transition toa History J unction 7 31 xiii xiv Contents Connective unctions anaua Example If Then Else Decision Construct Example Self Loop 002 c cece eee Example For Loop Construct 200 eee eas Example Flow Diagram Notation 20000 Example Transitions from a Common Source to Multiple Destinations 0 0 00 c aa Example Transitions from Multiple Sources toa Common Destination 0 00 ee Example Transitions from a Source to a Destination Based ona Common Event 2 0 cece eee eee Event Actions oeo ena ncn Wiemann Bere Example Event Actions and Superstates Parallel AND States 0 0 00
220. ions available on all shortcut menus 2 10 state 2 13 transition 2 14 simulation menu 2 45 simulation target compiling building tasks 9 27 configuation dialog box 9 21 Simulink glossary definition A 9 overview xxiv requirements for xxii Simulink model and Stateflow machine relationship between 1 8 stand alone target add target task 9 17 adding and specifying tasks 9 16 compiling building 9 28 configuration dialog box 9 23 state active and inactive notation 6 11 active notation 6 11 changing incoming transition arrowhead size 2 28 combination notation 6 12 creating and deleting 2 25 debugger breakpoint property 2 30 decomposition notation 6 10 definition 1 12 description property 2 30 document link property 2 30 editing properties 2 29 exclusive OR decomposition notation 6 11 glossary definition A 9 grouping and ungrouping 2 26 inactive notation 6 11 label property 2 30 labeling 2 26 labeling notation 6 13 moving 2 28 name property 2 30 notation decomposition 6 10 during action 6 15 entry action 6 14 exit action 6 15 labeling example 6 14 name 6 14 on action 6 15 notation overview 6 10 operations 2 24 parallel AND decomposition notation 6 11 parent property 2 30 properties 2 30 representing hierarchy 6 7 resizing 2 27 showing and hiding 2 27 specifying decomposition 2 24 unique name notation example 6 15 state inconsistencies 10 16 state label changing font size 2 27 during keyword 2 26 entry keyword 2 26 exit
221. ions between A A1 and A A2 in the original example If stated is already active theinner transition is used tore evaluate which of the substates of state A is to be active If stateA1 is not active and C_one is true the transition to Al is valid If stateA2 is not active and C_two is true the transition to A2 is valid This solution is much simpler than the previous one See the section titled Example Processing One Event with an I nner Transition to a Connective unction on page 7 28 for more information on the semantics of this notation Example Inner Transition to a History J unction This example shows an inner transition to a history junction switch_off Power_on switch_high Low High switch_low StatePower_on High is initially active When event Reset occurs the inner transition tothe history junction is valid Because the inner transition is valid the currently active state Power on High will be exited When the inner transition to the history junction is processed the last active state Power on Hi gh becomes active is re entered If Power_on Low was active under the same circumstances Power _on Low would be exited and re entered as a result The inner transition in this example is equivalent to drawing an outer self loop transition on both Power _on Low and Power_on High See the section titled Example Use of History J unctions on page 6 40 for another example using a history junction
222. iper subsystems You represent parallelism in Stateflow by specifying parallel AND state decomposition Parallel AND states are displayed as dashed rectangles Default Transitions Default transitions specify which exclusive OR state is to be active when thereis ambiguity between two or more exclusive OR states at the same level in the hierarchy In the Graphical Components figure when St at eA is active by default StateA1 is also active Without the default transition toSt ateAl there is ambiguity in whether St at eAl or St at eA2 should be active 1 20 Anatomy of a Model and Machine IntheLi ghts subsystem the default transition totheLi ghts 0f f substate indicates when the Li ghts superstate becomes active the Of f substate becomes active by default o Switch_off iti na E Default transition Vv i Switch_on lt Default transitions specify which exclusive OR substate in a superstate the system enters by default in the absence of any information History junctions override default transition paths in superstates with exclusive OR decomposition Connective J unctions Connective junctions are decision points in the system A connective junction is a graphical object that simplifies Stateflow diagram representations and facilitates generation of efficient code They provide alternative ways to represent desired system behavior In the Graphical Components figure the connective junction is used as a decisio
223. is displayed eS example iof x File Edit Simulation Format Tools Untitled 11 3 sfex it Purpose Close all Stateflow diagrams Simulink models containing Stateflow diagrams and exit the Stateflow environment Syntax sfexit Description sfexit closes all Stateflow diagrams all Simulink models containing Stateflow diagrams and exits the Stateflow environment sfexit unlocks the Stateflow ME X file and clears it from the workspace 11 4 sfsave Purpose Syntax Description Save the current machine and Simulink model sfsave sfsave machinename sfsave machine saveasname sfsave defaults sfsave saves the current machine and Simulink model sfsave machinename Saves the specified machine and its Simulink model sfsave machine saveasname Saves the specified machine and its Simulink model with the specified name sfsave defaults Saves the current environement default settings in the defaults file 11 5 stateflow Purpose Syntax Description 11 6 Open the Stateflow model window statefl ow stateflow opens the Stateflow model window The model contains an untitled Stateflow block an Examples block and a manual switch The Stateflow block is a masked Simulink model and is equivalent to an empty untitled Stateflow diagram Use the Stateflow block toincludea Stateflow diagram in a Simulink model Every Stateflow block has a corresponding S function T
224. is the highest level in the Stateflow hierarchy The object hierarchy beneath the Stateflow machine consists of combinations of the graphical and nongraphical objects The data dictionary is therepository for all Stateflow objects You can use the Stateflow Finder and Stateflow Explorer together to browse and make changes to data dictionary objects Stateflow data dictionary machine The Explorer displays any defined events data and targets within an object hierarchy where machines charts and states are potential parents You can create modify and delete events data and target objects using the Explorer You can also add events data and targets using the graphics editor Add menu See Add Menu on page 2 48 for more information If you add 5 2 O verview data or events via the Add menu the chart is automatically defined as the parent If you add a target the machine is defined as the parent Targets can only be parented by the machine If you want to change the parent of a data or event object you must use the Explorer to do so Similarly you must use the Explorer if you want to delete an event data or target object See Customizing the Target on page 9 20 for information on customizing the simulation target See Adding and Specifying a Stand Alone Target on page 9 16 for information on creating targets to generate code using the Stateflow Coder product The Finder displays a list of objects based o
225. isplay Call Stack Click on the Call Stack button to display a sequential list of the Stopped and Current Event status items that occur when single stepping through the simulation Coverage Click on the Coverage button to display a listing of code coverage Code coverage displays the current percentage of unprocessed transitions states etc at that point in the simulation Browse Data Click on the Browse button to display the current value of any defined data objects Active States Click on the Active States button to bring the graphics editor in focus displaying any active states Clear Output Click on the Clear Output button to remove any previously displayed information from the display area Breakpoints Click on the Breakpoints button to display a list of the set breakpoints Once you have selected an output display button that type of output is displayed until you choose a different display type MATLAB Command Field Direct access to the MATLAB command window is not possible while the Debugger is stopped at a breakpoint If you need to enter any MATLAB commands during a debugging session enter them into the MATLAB Command field and press the Return key 10 11 10 Debugging Debugging Runtime Errors Example Stateflow Diagram This example Simulink model and Stateflow diagram is used to show how to debug some typical runtime errors sf_debug_ex File Edit Simulation Format Tools Power_on 1
226. itA1b exit exitA2b i 5 StateA Al Ala executes and completes exi t actions exi tAla 6 StateA Al Ala is marked inactive Parallel AN D States 7 StateA A1 A1b executes and completes entry actions ent A1b 8 StateA Al Alb is marked active 9 Parallel stateA A2 is evaluated next StateA A2 during actions execute and complete dur A2 There are no valid transitions as a result of E_one 10 Stated A2 A2b now activeas a result of the processing of the condition action event broadcast of E_t wo executes and completes during actions dur A2b 11 The Stateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one and the condition action event broadcast toa parallel state of event E_t wo The final Stateflow diagram activity now looks like this At entry entA during durA exit exitAG entry entA1 11 entry entA2 1 during durA1 11 during durA2 exit exitA1 11 exit exitA2 i A2al Ala a entry entAta i entry entAZa ee i A during durA2a Aring CRATER exit exitA2a exit exitAla i E_one E_two State Alb Li R2 State A2b i ive entry entA 1b ii entry entA2b i i i Saale i during durA1b 11 during durA2b i is active i exit exitA 1b exit exitA2b 7 57 7 Semantics Directed Event Broadcasting
227. ith the state Each keyword is optional and positionally independent Y ou can specify none all or some of them The colon after each keyword is required The slash following the state name is optional as long as it is followed by a carriage return If you enter the name and slash followed directly by an action or actions without theent ry keyword the action s are interpreted as entry action s This shorthand is useful if you are only specifying ent ry actions See the section titled Labeling a State on page 6 13 for more information Grouping and Ungrouping States States that contain other states are called superstates All of the states contained in a superstate can be grouped together for ease of movement copying and uniform scaling when resizing Once selected you can move and resize a group as though it was a single object When you move a grouped superstate the contents are automatically hidden for efficiency in the moving operation Double click on or within the superstate border to group all of the states contained in a superstate A grouped superstate is represented graphically by a thicker border The appearance varies slightly depending on the type of decomposition exclusive OR or parallel AND and the platform The contents of a grouped superstate are always highlighted in a light shade of gray W orking with States To ungroup a grouped superstate double click on or within the grouped superstate borde
228. ition 1 notation ex ample 6 27 before using an inner transition 2 notation ex ample 6 29 glossary definition A 7 notation overview 6 27 processing a second event with an inner transi tion toa connectivejunction semantics example 7 29 processing a second event within an exclusive OR state semantics example 7 26 processing a third event within an exclusive OR state semantics example 7 27 processing one event with an inner transition to a connective junction semantics example 7 28 processing one event within an exclusive OR state semantics example 7 25 to a connective junction 1 notation example 6 28 to a connective junction 2 notation example 6 29 to a history junction notation example 6 30 to a history junction semantics example 7 31 installation xxviii junction changing incoming arrowhead size 2 39 changing size 2 39 creating and deleting 2 38 description property 2 41 document link property 2 41 editing properties 2 40 moving 2 40 operations 2 38 parent property 2 41 properties 2 41 keywords change data_name 6 5 during 6 5 entry 6 5 entry state_ name 6 5 exit 6 5 exit state name 6 6 in state_ name 6 6 matlab 6 6 matlab 6 6 on event name 6 6 send event_ name state name 6 6 summary list 6 5 literals 6 62 Index M machine glossary definition A 7 what is 3 8 make command customization 9 23 MATLAB overview xxiii requirements for xxii ml functions 6 50 ml Name space
229. itions and states The semantics describe in what sequence these actions take place during Statefl ow diagram execution Knowledge of the semantics is important to make sound Stateflow diagram design decisions for code generation Different use of notations results in different ordering of simulation and generated code execution Stateflow semantics consist of rules for e Event broadcasting e Processing states e Processing transitions e Taking transition paths The details of Stateflow semantics are described largely by examples in this chapter The examples cover a range of various notations and combinations of state and transition actions See Semantic Rules Summary on page 7 67 for a summary of the semantics List of Semantic Examples This is a list of the semantic examples provided in this chapter Contents of section Transitions to and from Exclusive OR States on page 7 8 e Example Processing of One Event on page 7 8 e Example Processing of a Second Event on page 7 9 e Example Processing of a Third Event on page 7 10 Example Transition from a Substate to a Substate on page 7 11 O verview Contents of section Condition Actions on page 7 13 Example Actions Specified as Condition Actions on page 7 13 Example Actions Specified as Condition and Transition Actions on page 7 14 Example Using Condition Actions in For Loop Construct on page 7 15 Ex
230. j x File Edit Simulation Format Tools triggerex If more than one Input from Simulink event is defined the sample times are determined by Simulink to be consistent with various rates of all the incoming signals The outputs of a Triggered Stateflow block are held after the execution of the block Defining a Sampled Stateflow Block There are two ways you can define a sampled Stateflow block Setting the chart Update method set in the Chart Properties dialog box to Sampled and entering a Sample Time value defines a sampled Stateflow block See Editing Chart Stateflow Diagram Properties on page 2 19 4 5 4 Defining Stateflow Interfaces Alternatively you can add and define an Input from Simulink data object Data is added and defined using either the graphics editor Add menu or the Explorer See Add M enu on page 2 48 or Tasks to Definea Data Input from Simulink on page 4 18 The chart sample time is determined by Simulink to be consistent with the rate of the incoming data signal The Sample Time set in the Chart Properties dialog box takes precedence over the sample time of any Input from Simulink data Example Sampled Stateflow Block A Stateflow block that is not explicitly triggered via the trigger port can be triggered by Simulink by specifying a discrete sample rate You can specify a Sample Time in the Stateflow diagram s Chart properties dialog box The Stateflow block is then called by S
231. ject either adds that object to the selection list if it was deselected or deselects the object if it is on the selection list This is useful to select objects within a state without selecting the state itself 2 15 2 Using the Graphics Editor 2 16 To select all objects in the Stateflow diagram choose Select All from the Edit menu or the right mouse button shortcut menu Simultaneously pressing the Shift key and doing a rubberband selection selects objects touched by the rubberband if they are deselected and deselects objects touched by the rubberband if they are selected Pressing the E scape key deselects all selected objects Pressing the Escape key again brings the Simulink model the parent of the Stateflow diagram forward Cutting and Pasting Objects You can cut oneor more objects from the drawing area or cut and then paste the object s as many times as you like You can cut and paste objects from one Stateflow diagram to another The Stateflow clipboard contains the most recently cut selection list of objects The object s are pasted in the drawing area location closest to the current mouse location Tocut an object select the object and choose Cut from either e The Edit menu on the main window e The right mouse button shortcut menu Pressing the Ctrl and X keys simultaneously is the keyboard equivalent to the Cut menu item The Stateflow clipboard contains the most recent deleted selection list of objects T
232. jects that are essential to completing and defining interfaces to the Stateflow diagram Chapter 4 Defining Stateflow I nterfaces describes the types of interfaces and how to define them For information on using the Stateflow Explorer and the Stateflow Finder see Chapter 5 Exploring and Searching Use Chapter 6 Notations Chapter 7 Semantics and Chapter 9 Generating Code together to understand the language used to communicate Stateflow diagram design information how that notation is interpreted and implemented behind the scenes and how to generate code See Chapter 10 Debugging for information on debugging your simulation See Chapter 11 Reference for information on specific functions and their syntax See the Glossary for definitions of key terms and concepts How to Use This G uide Typographical Conventions To Indicate This Guide Uses Example New terms Italics An array is an ordered collec tion of information Keys menu Boldface with an Choose the File menu names items and initial capital GUI controls letter Function names Monospace type Thesf open command opens variables example code user entered text a model xxvii Before You Begin Installation Your platform specific MATLAB Installation Guide provides essentially all of the information you need to install Stateflow Prior to installing Stateflow you must obtain a
233. ked to enable Stateflow 1 32 Using Stateflow diagram animation Click on the Close button to apply the change and close the window 4 Choose Start from the graphics editor Simulation menu to start a simulation of the model By default the S function is the simulation target for any Stateflow blocks Informational and error messages related to the S function code generation for Stateflow blocks are displayed in the MATLAB command window Once the simulation is started and the target is built the graphics editor becomes read only frozen The input from the Sine block is defined as the Input from Simulink event Swi tch When the simulation starts the Stateflow diagram is animated reflecting the state changes triggered by the input sine wave Each input event of Swi t ch toggles the model between the Power_off andPower_on state 5 Choose Stop from the graphics editor Simulation menu to stop a simula tion Once the simulation is stopped the graphics editor becomes writeable unfrozen Debugging The Stateflow Debugger supports functions like single stepping animating and running up to a designated breakpoint and then stopping These steps show how to step through the simulation using the Debugger 1 Display the Debugger by choosing Debug from the Tools menu of the graphics editor 2 Click on the Break on Chart Entry checkbox to specify you want the Debugger to stop the simulation execution when the chart is entered 3 C
234. l The Simulink model and Stateflow machine work seamlessly together Running a simulation automatically executes both the Simulink and Stateflow portions of the model A Simulink model can consist of combinations of Simulink blocks toolbox blocks and Stateflow blocks Stateflow diagrams In Stateflow the chart Stateflow diagram consists of a set of graphical states transitions connective junctions and history junctions and nongraphical event data and target objects There is a one to one correspondence between the Simulink model and the Stateflow machine Each Stateflow block in the Simulink model is represented in Stateflow by a single chart Stateflow diagram Each Stateflow machine has its own object hierarchy The Stateflow machine is the highest level in the Stateflow hierarchy The object hierarchy beneath the Stateflow machine consists of combinations of the graphical and nongraphical objects The data dictionary is the repository for all Stateflow objects 1 8 Anatomy of a Model and Machine Simulink model block block Stateflow i Stateflow data dictionary machine lt gt One to one mapping chart Stateflow diagram Stateflow scoping rules dictate where the types of nongraphical objects can exist in the hierarchy For example data and events can be parented by the 1 9 1 Introduction 1 10 machine the chart Stateflow diagram or by a state Targets can only be parented by the mach
235. l in the hierarchy A2a is the relative hierarchy notation for the source of the transition The full path is A A2 A2a The relative hierarchy notation for the destination of the transition is A2b The full path is A A2 A2b 5 25 5 Exploring and Searching Searching for a Wildcard String Example This example Stateflow diagram is used to show how to find all object labels containing a specified wildcard string A a C_one C A2 x N E_one C_one A2b E_two C_one 1 Select Find from the Tools menu of the Stateflow graphics editor window to invoke the Finder 2 Click in the Look for text field and enter A2 3 Click on and enable the Normal Wildcard radio box 5 26 Searching fora W ildcard String 4 Click on the Search button These are the results of the search Eq statetlow Finder sf_exp_srch _ jo x State O AZc There are four matches The Search History shows that the current search criterionisAll objects with A2 Thedisplay shows the matches are all exclusive OR O states 5 27 5 Exploring and Searching Searching for an Exact String Match Example This example Stateflow diagram is used to show how to find all objects with an exact string match in the label Pe T C m gt E_one C_one A2b E_two C_one 1 Select Find from the Tools menu of the Stateflow graphics editor window to invoke the Finder 2 Click in the Lo
236. l sources for broadcast purposes Exported events must be parented by the machine because the machine is the highest level in the Stateflow hierarchy that can interface to external sources The machine also retains the ability to broadcast the Exported event Exporting the event does not imply anything about what the external source does with the information It is the responsibility of the external source to include the Exported event in the manner appropriate to the source to make use of the right to broadcast the event If the external source is another machine then one machine defines an Exported event and the other machine defines the same event to be mported 4 25 4 Defining Stateflow Interfaces 4 26 Stateflow generates the appropriate export and import event code for both machines This example shows the format required in the external code source custom code to take advantage of an Exported event sf_ev_d_inout_ex File Edit Simulation Format Tools Sine Wave Sine Wave e is imported in the external code source e is added and external code source defined as an Exported event func_exampl e void extern void external broadcast_e void external broadcast _e Stateflow generates this code void external _broadcast_e void code based on the event definition Defining the Interface to External Sources Imported Events Consider the same pager examp
237. ld contents including the truncated portion is used for resorting Each field label is also a button Click on the button to have the list sorted based on that field If the same button is pressed twice in a row the sort ordering is reversed The Finder can be resized vertically to display more output rows but cannot be expanded horizontally Click on a graphical entry to highlight that object in the graphical editor window Double click on an entry to invoke the Property dialog box for that object Representing Hierarchy The Finder displays Parent Source and Destination fields to represent the hierarchy The Stateflow diagram is the root of the hierarchy and is represented by the character Each level in the hierarchy is delimited bya character The Source and Destination fields usethe combination of the and the characters to denote that the state listed is relative to the Parent hierarchy Stateflow Finder User Interface Using this Stateflow diagram as an example E_three C_one A2 S E_one C_one A2b E_two C_one what are the values for the Parent Source and Destination fields for the transition from A2a toA2b The transition is within state A2 State A2 s parent is state A and stateA s parent is the Stateflow diagram itself A A2 is the notation for stateA2a s parent StateA2a is the transition source and state A2b is the destination These states are at the same leve
238. le discussed for Exported events to clarify the use of Imported events Someone buys a pager and indicates you may want to use this number to page them in the future They tell you the pager number and you take note of the number by writing it down You can then use the number to page that person You cannot receive the page because you do not own the pager Similarly you may want to broadcast an event that is externally outside the Stateflow diagram the machine and the Simulink model defined By defining an event s scope to be Imported the event can be broadcast anywhere within the hierarchy of that machine including any offspring of the machine An Imported event s parent is external However the event needs an adoptive parent to resolve symbols for code generation An Imported event s adoptive parent must be the machine because the machine is the highest level in the Stateflow hierarchy that can interface to external sources mporting the event does not imply anything about what the external source does with the information It is the responsibility of the external source to make the Imported event available in the manner appropriate to the source to make use of the right to broadcast the event If the external source is another machine then one machine defines an Imported event and the other machine defines the same event to be Exported Stateflow generates the appropriate import and export event code for both machines 4
239. le of this notation See the section titled Example Inner Transition to a History J unction on page 7 31 for more information on the semantics of this notation 6 41 6 Notations Action Language What Is an Action Language You sometimes want actions to take place as part of Stateflow diagram execution The action can be executed as part of a transition from one state to another or it can depend on the activity status of a state Transitions can have condition actions and transition actions States can haveentry during exit and on event _name actions An action can bea function call an event to be broadcast a variable to be assigned a value etc The action language defines the categories of actions you can specify and their associated notations Violations of the action language notation are flagged as errors by the parser This section describes the action language notation rules Objects with Actions This Stateflow diagram shows examples of the possible transition and state actions Transition action 7 State exit event2idata1 5 B __ action Stateentry exit Time_out and on rv event name entyid x y action on event3 func1 Stateduring action Gi during Switch_on event1 temp gt 50 func 10y ondition action Action Language Transition Action Notation Actions can be associated with transitions via the transition s label The general format of a transition label is event
240. lick on the Go button to start the simulation Informational and error messages related to the S function code generation for Stateflow blocks are displayed in the MATLAB command window When the target is built the 1 33 1 Introduction graphics editor becomes read only frozen and the Debugger window will be updated and look similar to this Fe Stateflow Debugger Debugging sf_intro_example 4 Click on the Step button to proceed one step at a time through the simulation Take note of the top portion of the Debugger window where this information is displayed e Where the simulation is stopped e What is executing e The current event e Thesimulation time e The current code coverage percentage Using Stateflow Watch the graphics editor window as you click on the Step button to see each transition and state animated when it is executing After both Power _ off and Power _on have become active by stepping through the simulation the code coverage indicates 100 5 Choose Stop from the graphics editor Simulation menu to stop a simulation Once the simulation is stopped the graphics editor becomes writeable unfrozen 6 Click on the Close button in the Debugger window 7 Choose Close from the File menu in the Simulink model window For More Information See Debugging for more information beyond the debugging topics in this section Generating Code If you have the Stateflow Coder product you can
241. llipsis to continue on the next line Changing Font Size Font size is adjusted through the shortcut menus using a virtual scrollbar To adjust font size with the virtual scrollbar 1 2 Select the transition s whose label font size you want to change Right click on a selected transition whose font you want to change to display the shortcut menu Place the cursor over the Font Size menu item Click and drag horizontally on the Font Size menu item Theshortcut menu disappears and a numeric size is displayed Drag the mouse tothe left to decrease the font size or to the right to increase the font size The font size of all labels on any selected transitions is adjusted Changing Arrowhead Size The arrowhead sizeis a property of the destination object Changing one of the incoming arrowheads of an object causes all incoming arrowheads tothat object to be adjusted to the same size The arrowhead size of any selected transitions and any other transitions ending at the same object is adjusted W orking with Transitions To adjust arrowhead size from the Transition shortcut menu 1 Select the transition s whose arrowhead size you want to change 2 Place the cursor over a selected transition click the right mouse button to display the shortcut menu Place the cursor over Arrowhead Size The shortcut menu disappears and a numeric size is displayed 3 Click and drag horizontally to the left to decrease the arrowhead
242. ly the Changes 0 00 e eee tees 4 23 MATLAB Workspace 000 eee eee eens 4 24 What Is the MATLAB Workspace 00020 eae 4 24 Using the MATLAB Workspace 0200 e enna 4 24 vii viii Contents Defining the Interface to External Sources 4 25 What Are External Sources 0 0000 c eee ee 4 25 Exported Events 0 0000 cece eee ete 4 25 Imported Events 0 0 00 cece ete 4 27 Exported Data 2 icacaicee eens eadded KEE e E RRE eW eee 4 28 Imported Data 0 0 00 cee ee 4 29 5 OVOERVICW e ocd ririn a Bi ee ee EAA EARSTE A 5 2 Exploring and Searching 02 0c e eee eee 5 2 Where to Find More Information on Events and Data 5 3 Typical Exploring Tasks 0 20 cece ee 5 3 Typical Searching Tasks 0 e cee ee 5 4 Stateflow Explorer User Interface 5 5 Explorer Main Window 00 cece teens 5 5 Moving Objects Changing Parent 0 2 eee aee 5 8 Moving Objects Changing Index and Port Order 5 8 Deleting Objects 0 cece 5 8 Event Properties Dialog Box 0 000 e eee eee 5 9 Data Properties Dialog Box 0 0c cece eee 5 12 Example Getting Started Adding Events and Data 5 16 Task Overview 2 cent e ee e eee eenes 5 16 Solution Model and Stateflow Diagram 5 16 What Are the Events ccc eee eee 5 17 Add Loc
243. m a Simulation menu either the Simulink model or the graphics editor menu Click on the RTW tab Specify any RTW specific options in the RTW tab See the Real Time Work shop User s Guide for detailed information on RTW Click on the Build button in the RTW tab of the Simulation parameters dialog box Stateflow Coder must be present to build a target with RTW Calls to MATLAB functions in the action language should be avoided if you plan to build an RTW target that includes code from Stateflow Coder Compiling Building Stand Alone Targets These steps show how to build a stand alone Stateflow target assuming you have already specified any customizations see Customizing the Target on page 9 20 1 Choose Explore from the graphics editor Tools menu to invoke the Explorer Click on the machine of interest in the Object Hierarchy list left hand side of the Explorer Double click on the target name in the E xplorer window to display the Target Configuration property dialog box Click on the Generate Code button in the Target Configuration dialog box to generate the code This operation implicitly parses the machine and gen erates the code Click on the Build Stateflow Target button in the Target Configuration dialog box to build the stand alone target This operation implicitly parses the machine generates code and generates an executable image You can build one target at a time Compiling Code Building Tar
244. mation on the action language 6 13 6 Notations Example Labeling a State This example shows the state labeling formats and explains the components of the label Oni entry on_count 0 during light_on on_count on power_outage handle_outage Off exitlight_off Name The nameof the state forms the first part of the state label Valid state names consist of alphanumeric characters and can include the _ character e g Transmission orGreen_on The use of hierarchy provides some flexibility in the naming of states The name that you enter as part of the label must be unique when preceded by the hierarchy of its ancestor states The name as stored in the data dictionary consists of the text you entered as the label on the state preceded by the hierarchy of its ancestor states separated by periods States can have the same name appear on the graphical representation of the state as long as the full names within the data dictionary are unique The parser indicates an error if a state does not have a unique name entry in the data dictionary for that Stateflow diagram See the section titled Example Unique State Names on page 6 15 for an example of uniquely named states In this example the state names are 0n and Of f Entry Action In the example state 0n hasentry actionon_count 0 The value of on_count is reset to 0 whenever state 0n s entry action is executed 6 14 States Se
245. meter across a range of values Using scopes and other display blocks you can see the simulation results while the simulation is run ning In addition you can change parameters and immediately see what hap pens for what if exploration The simulation results can be put in the MATLAB workspace for postprocessing and visualization Model analysis tools include linearization and trimming tools which can be accessed from the MATLAB command line plus the many tools in MATLAB and its application toolboxes And because MATLAB and Simulink are inte grated you can simulate analyze and revise your models in either environ ment at any point Stateflow is part of this environment The Stateflow block is a masked Simulink model Stateflow builds an S function that corresponds to each Stateflow machine This S function is the agent Simulink interacts with for simulation and analysis Related Products and Documentation The control behavior that Stateflow models complements the algorithmic behavior modeled in Simulink block diagrams By incorporating Stateflow diagrams into Simulink models you can add event driven behavior to Simulink simulations You create models that represent both data and control flow by combining Stateflow blocks with the standard Simulink blocksets These combined models are simulated using Simulink The Using Simulink document describes how to work with Simulink It explains how to manipulate Simulink blocks acc
246. mulink parameters a Doubleclick on the Sine Wave block and edit the parameters as shown in this example dialog box Sine Wave Click on the Close button to apply the changes and close the dialog box 1 31 1 Introduction b Choose Parameters from the Simulation menu of the Simulink model window and edit the values to match the values in this dialog box Ed Simulation parameters sf_intro_example of x Solver Workspace vo Diagnostics RTw RTW Exteral Simulation time Start time 0 0 Stop time 100 Solver options Type Fixed step discrete no continuous states Fi Fixed step size 0 001 Output options Refine output Refine tector 1 For More Information For more information on Stateflow interfaces beyond what is discussed here see Defining Stateflow Interfaces Running a Simulation These steps show how to run a simulation 1 Ensure the Stateflow diagram and any display blocks such as the Scope block are open Double click on the0n_ of f Stateflow block to display the Stateflow diagram Double click on the Scope block to display the output of the Sine wave 2 Select Open Simulation Target from the graphics editor Tools menu Ensure that the checkbox to Enable Debugging Animation is checked Click on the Close button to apply the change and close the window 3 Select Debug from the graphics editor Tools menu Ensure that the Enabled radio button under Animation is chec
247. n on page 9 23 for more information Click on the Generate Code Only button to parse the machine implicitly and generate target code Informational messages and any error messages are displayed in a pop up window and also in the MATLAB command window Specify the Make Command TheMake Command field defines how the executable is to be generated and varies depending on your environment See Coder Command Customiza tion on page 9 23 for more information Click on the Build Stateflow Target button to generate an executable file This operation implicitly parses the machine generates code and generates an executable image You can build one target at a time Informational and any error messages are displayed in a pop up window and alsoin the MATLAB command window Disable debugging animation Generally speaking debugging animation should be disabled for stand alone targets The debugger does not interact with stand alone Adding and Specifying a Stand Alone Target targets and the overhead incurred from the added instrumented code is undesirable in stand alone targets Ensure that the Enable Debugging Animation checkbox is disabled See Enable Debugging Animation on page 9 24 and Chapter 10 Debugging for more information Enable Dynamic Checker options Generally speaking the Dynamic Checker options should be disabled for stand alone targets The overhead incurred from the added instrumented code is undesi
248. n a transition to the Ri de superstate e ThePower_on Ti mer Stopped Substate is the default state to become active upon a transition to theTi mer superstate See the section titled What is a Default Transition on page 6 24 for more information Are There Events These events aredefined Ride _done Switch_on Switch_off Start_button andEmergency stop See the sections titled Events on page 3 5 for more information on events Is There Data The carousel system has these data objects Ti me Speed Duration and Max_speed See the section titled Data on page 3 22 for more information on data 8 7 8 Tutorial Entering a Stateflow Diagram Procedure Overview A carousel is a familiar reactive system that you can model with a Stateflow diagram The system reacts based upon actions the ride operator takes to use it For the purposes of this tutorial some aspects of the operation are simplified Use the sample solution in this section as a guide while following these steps In this section you learn how to Create a simple Simulink model with a Stateflow block Save an untitled model and Stateflow diagram Create and label the OR states Create and label the AND states Create and label the superstates Create the transitions Label the transitions Create default transitions Add and define event objects Add and define data objects Save the Stateflow diagram and exit Procedure
249. n call tof unction_name1 with the specified arguments is executed and completed If 2 is active and an event occurs theduri ng action a function call tof unction_name3 with the specified arguments executes and completes ml Functions You can specify calls to MATLAB functions that return scalars of type double in the action language ml Function Format The format of the ml function is ml eval String argl arg2 arg3 where the return value is scalar of type double If the result returned is e A vector then the first element is returned e A void then an appropriate format must be used an assignment statement cannot be used e A string a structure or a cell array then the behavior is undefined 6 50 Action Language eval String is a string that is evaluated in the MATLAB workspace with formatted substitutions ofar gl arg2 arg3 etc Example One ml Function Call This is an example of an ml function call as part of a condition action If 1 is active an event occurs and if c_one istrue the expression si n x is evaluated in the MATLAB workspace and the return value assigned to a x must be a variable in the MATLAB workspace and a is a data object in the Stateflow diagram The result of the evaluation must be a scalar If x is not defined in the MATLAB workspace a runtime error is generated Example Two ml Function Call This is an example of a ml functi
250. n contin uous time sampled time or a hybrid of the two Systems can also be multirate i e have different parts that are sampled or updated at different rates For modeling Simulink provides a graphical user interface GUI for building models as block diagrams using click and drag mouse operations With this interface you can draw the models just as you would with pencil and paper or as most textbooks depict them This is a far cry from previous simulation pack ages that require you to formulate differential equations and difference equa tions in a language or program Simulink includes a comprehensive block library of sinks sources linear and nonlinear components and connectors Y ou can also customize and create your own blocks Models are hierarchical so you can build models using both top down and bottom up approaches You can view the system at a high level then double click on blocks to go down through the levels to see increasing levels of model detail This approach provides insight into how a model is organized and how its parts interact After you define a model you can simulate it using a choice of integration methods either from the Simulink menus or by entering commands in MATLAB s command window The menus are particularly convenient for interactive work while the command line approach is very useful for running a batch of simulations for example if you are doing Monte Carlo simulations or want to sweep a para
251. n event awakens this Stateflow diagram and stated is active a is incremented The value of a quickly becomes a data range violation 10 20 Debugging Cyclic Behavior Debugging Cyclic Behavior What is Cyclic Behavior When a step or sequence of steps is indefinitely repeated recursive this is called cyclic behavior The Debugger cycle detection algorithms detect a class of infinite recursions caused by event broadcasts Detecting Cyclic Behavior To detect cyclic behavior during a simulation e Enable Debugging Animation in the Target Configuration sfun property dialog box e Build the target with debugging options e Invoke the Debugger and enable Detect Cycles e Start the simulation 10 21 10 Debugging 10 22 Example Cyclic Behavior This Stateflow diagram shows a typical example of a cycle created by infinite recursions caused by an event broadcast an i P ra B P Cf 3 i TON N 1 F o during E1 i H I E n When statec duri ng action executes event E1 is broadcast The transition from stateA A1 tostateA A2 becomes valid when event E1 is broadcast Event E2 is broadcast as a condition action of that transition The transition from state B B1 tostateB B2 becomes valid when event E2 is broadcast Event E1 is broadcast as a condition action of the transition from state B B1 tostateB B2 Because these event broadcasts of E1 and E2 arein condition actions a recursive event broad
252. n of syst eml andsystem2 State flow blocks Parent_exnew of x File Edit Simulation Format Tools system e Chart The chart Stateflow diagram refers to the specific Stateflow block The Stateflow blocks titled system1 andsystem2 each represent an underlying chart that can parent objects within the Stateflow diagram 3 25 3 Events and Data 3 26 e State The state refers to a specific state within the hierarchy In the example this issysteml s Stateflow diagram Either of these states sys1_on and sysl_off can be parents sysi_on entry sysl_on 1 sysl_off entry sys1_on 0 Switch Data Hierarchy and Scope Data objects have hierarchy a parent and scope Hierarchy and scope together define a range of access to data objects A data object is accessible only within its parent including siblings Access to data is defined in terms of these two questions e Where does the data reside The data object s parent determines where the data resides e Who accesses the data The data object s parent and scope determine who can access the data By default the data s Scope value is Local Local data can be accessed from anywherein the hierarchy of its parent Changing the Scope of the data from the default value of Local to one of the other values changes this default behavior See Data Scope on page 3 27 for the behavior associated with the Scope value choices Data Data Scope
253. n of the border of the source state Click the border when the cursor changes toa cross hair Drag and release on a straight portion of the border of the destination state when the transition changes from a dotted linetoa solid line The solid line indicates the transition is in position to be attached The cross hair will not appear if you place the cursor on a corner since corners are used for resizing Use the same procedure to create transitions to and from junctions The only difference is that transitions can be connected to any point on the junction J unctions are resized through the J unction shortcut menu To delete a transition select it and choose Cut Ctrl X from the Edit menu or any shortcut menu or press the Delete key 2 31 2 Using the Graphics Editor 2 32 What Is a Default Transition The default transition object is a transition with a destination but no source object Default transitions specify which exclusive OR state is to be active when thereis ambiguity between two or more exclusive OR states at the same level in the hierarchy Default transitions also specify that a junction should be entered by default IntheLi ghts subsystem the default transition to the Li ghts Of f substate indicates when the Li ght s superstate becomes active the Of f substate becomes active by default 0 Switch_off ve a FS Default transition Switch_on 4 Default transitions specify which exclusive OR subs
254. n point for twotransition segments that complete at St at eAlc This example shows how connective junctions displayed as small circles are used to represent the flow of ani f code structure if cl Ten a if c2 a2 telse if c3 a3 c2 a2 c3 a3 1 21 1 Introduction Using Stateflow Stateflow Typical Tasks Using Stateflow typically involves e Creating or starting with a Simulink model e Creating a Stateflow diagram e Defining a Stateflow block interface e Running a simulation e Debugging e Generating code Depending upon your design approach the details of the tasks and or the sequence you do them in will vary Sample Solution Here is a sample of the completed Stateflow diagram Power_off Switch 1 22 Using Stateflow Hereis a sample of the completed Simulink model sf_intro_example File Edit Simulation Format Tools When you simulate this model the generation of the input event from Simulink Switch will toggle the activity of the states between Power _on and Power off Creating a Simulink Model Opening the Stateflow model window is the first step towards creating a Simulink model with a Stateflow block By default an untitled Simulink model with an untitled empty Stateflow block is created for you when you open the Stateflow model window You can either start with the default empty model or copy the untitled Stateflow block into any Simulink model to includea
255. n search criterion you specify Y ou can directly access the properties dialog box of any object in the search output display by double clicking on that object The Finder the Explorer and the Add menu on the graphics editor provide access to the event data and target properties dialog boxes Where to Find More Information on Events and Data See these sections for conceptual information on data and events Events on page 3 5 and Data on page 3 22 For information on data and events relevant to defining Stateflow interfaces see Chapter 4 Defining Stateflow Interfaces See Adding and Specifying a Stand Alone Target on page 9 16 for information on defining standalone targets For information on customizing targets including the simulation target see Customizing the Target on page 9 20 Typical Exploring Tasks Exploring Stateflow diagrams can involve some or all of these tasks e Adding defining modifying and deleting non graphical objects events data and targets e Exploring browsing events data and target objects e Navigating through the hierarchy of open machines charts and states See Example Getting Started Adding Events and Data on page 5 16 for an example of adding and defining Local events and data parented by the chart 5 3 5 Exploring and Searching See these sections for information on adding events and data in more complex contexts Event Inputs from Simul
256. n through the hierarchy of the Stateflow diagram 1 7 8 The Stateflow diagram root checks to see if there is a valid transition as a result of the event There is no valid transition State A s children are parallel AND states They are evaluated and exe cuted from left to right and top to bottom State A A1 is evaluated first StateA A1 checks for any valid transitions as a result of the event Since the condition dat a1l 1 is true there is a valid transition from state A A1 to stateA A2 State A Al exit actions execute and complete exit A1 State A Al is marked inactive The transition action a qualified event broadcast of event E_one to state B represented by the notation B E_one is executed and completed a The broadcast of event E_one awakens state B This is a nested event broadcast Since state B is active the directed broadcast is received and stateB checks to see if there is a valid transition There is a valid transi tion fromB B1 toB B2 b StateB B1 executes and completes exit actions exit B1 c States B1 is marked inactive d States B2 is marked active State A A2 is marked active Stated A2 entry actions execute and complete ent A2 This sequence completes the execution of this Stateflow diagram associated with an event broadcast using a qualified event name to a parallel state 7 61 7 Semantics Execution Order 7 62 Overview In a single processor envir
257. nctions You can choose from these types of junctions Name Button Description Icon Connectivejunction One use of a connective junction is to handlesituations wheretransitions out of one state into two or more states are taken based on the same event but guarded by different conditions when entering this level in the hierarchy that the last state that was active becomes the next state to be active History junction Usea history junction to indicate Changing Size To adjust the junction size from the J unction shortcut menu 1 Select thejunction s whose size you want to change The size of any selected junctions is adjusted 2 Placethe cursor over a selected junction click the right mouse button to dis play the shortcut menu and place the cursor over J unction Size 3 Click and drag horizontally to the left to decrease the junction size or tothe right to increase the junction size The numeric display adjusts to show the currently selected junction size Changing Arrow head Size The arrowhead size is a property of the destination object Changing one of the incoming arrowheads of a junction causes all incoming arrowheads to that junction to be adjusted to the same size The arrowhead size of any selected junctions is adjusted 2 39 2 Using the Graphics Editor 2 40 To adjust arrowhead size from theJ unction shortcut menu 1 Select the junction s whose incoming arrowhead size you want to ch
258. nd from Exclusive OR Superstates This example shows transitions to and from an exclusive OR superstate and the use of a default transition RO Switch_on j select 1 m Waiting Selection_made l Switch_oft Q Rootbeer Lemon select 2 select 3 select 4 This is an expansion of the soda machine Stateflow diagram that includes the initial example of the0n and Of f exclusive OR states On is now a superstate containing the Wai ti ng and soda choices states The transition Of f gt 0n is valid when state Of f is active and event Swi tch_on occurs Now that 0n isa superstate this is an explicit transition to the 0n superstate Transitions To be a valid transition to a superstate the destination substate must be implicitly defined By defining that the Wai ting substate has a default transition the destination substate is implicitly defined This notation defines that the resultant transition is Of f gt On Waiting The transition 0n gt 0f f is valid when state On is active and event Swit ch_off occurs When theSwi t ch_off event occurs no matter which of the substates of On is active we want to transition to the Of f state This top down approach supports the ability to simplify the Stateflow diagram by looking at the transitions out of the superstate without considering all the details of states and transitions within the superstate See the section titled Default Transitions on page
259. nd verify the system s behavior at any stage of your design Automatically generate integer or floating point code directly from your design Take advantage of the integration with the MATLAB and Simulink environments to model simulate and analyze your system Flow diagram notation is essentially logic represented without the use of states In some cases using flow diagram notation is a closer representation of the system s logic and avoids the use of unnecessary states Flow diagram notation is an effective way to represent common code structures likef or loops andi f t hen el se constructs Stateflow also provides clear concise descriptions of complex system behavior using finite state machine theory flow diagram notations and state transition diagrams Stateflow brings system specification and design closer together It is easy to create designs consider various scenarios and iterate until the Stateflow diagram models the desired behavior O verview Examples of Stateflow Applications A few of the types of applications that benefit from using the capabilities of Stateflow are e Embedded systems Avionics planes Automotive cars Telecommunications e g routing algorithms Commercial computer peripherals appliances etc Programmable logic controllers PLCs process control Industrial machinery e Man machine interface MMI Graphical user interface GUI e Hybrid systems Air traffic control syst
260. nective junction have two modes of operation to place objects in the drawing area In either mode the cursor changes toa character when the editor is in an object button mode Single object mode Click on the object button and drag to place one object of that type in the drawing area Alternatively click on the object button release and click in the drawing area to choose the location for that object Pressing the Escape key cancels any operation Multiple object mode Double click on the object button Additional clicks in the drawing area create and place multiple objects of that type Click on the object button to release the button Pressing the Escape key cancels any operation Canceling Operations Pressing the Escape key cancels the current operation and deselects any objects on the selection list Selecting and Deselecting Objects Oncean object isin thedrawing area you need to select it to make any changes or additions to that object To select an object click on it When an object is selected it is highlighted in the color set as the selection color To select multiple objects click the left mouse button and drag the selection rubberband so that the grayed frame encompasses or touches the objects you want to select Once all objects are within the rubberband release the left mouse button All objects or portions of objects within the rubberband are selected Simultaneously pressing the Shift key and clicking on an ob
261. non RTW targets You need a Stateflow Coder license to be able to generate RTW and Stateflow stand alone target code Using Stateflow you can generate simulation target code only Stateflow Coder has these additional features Generated code is immediately very readable including fully commented sections Object names in the Stateflow diagram are preserved in the generated code In addition the first 24 characters of all symbols are guaranteed to be unique ensuring portability to many embedded system s target cross compilers All data objects are typed which ensures more efficient generated code Implementation of flow diagram notation especially those including transition actions is highly optimized Function inlining is used for optimizing event broadcasts Stateflow Coder takes advantage of any directed event broadcasting and thus ensures minimal overhead during that event broadcast O verview Stateflow Dynamic Checker Stateflow Dynamic Checker is currently available if you have a Stateflow license Stateflow Dynamic Checker is useful for debugging During a simulation the Dynamic Checker evaluates the coverage of the simulation i e the percentage of unprocessed transitions states that are visited In addition you can choose to detect these conditions state inconsistencies data range violations transition conflicts and cyclic behavior Generally speaking the Dynamic Checker is used for simulation and options
262. nsition segment condition action fensorValue read_adc puts the new value read from the ADC in the data object sensor Val ue The final transition segment is determined by the value of sensor Val ue If sensorValue lt 100 istrue the stateSensor Low is the destination If 6 36 Connective Junctions sensorValue gt 200 is true thestateSensor High is the destination Otherwise stateSensor Normal is the destination state Sensor sensorValue lt 100 adc_busy See the section titled Example Flow Diagram Notation on page 7 37 for information on the semantics of this notation Example Connective J unction from a Common Source to Multiple Destinations Transitions AB and A C share a common source state A An alternative representation uses one arrow from A toa connective junction and multiple arrows labeled by events from the junction to the destination states B and C See the section titled Example Transitions from a Common Source to Multiple Destinations on page 7 39 for information on the semantics of this notation 6 37 6 Notations Example Connective J unction Common Destination Transitions AC and B8 C share a common destination statec An alternative representation uses one transition from A toa connective junction one transition from B to the same connective junction and one transition from the connective junction to the destination state C See the section
263. ntA2b during durA 2b exit exitA2b Initially the Stateflow diagram is asleep Parallel substates A A1 Al1a and A A2 A2a are active Event E_one occurs and awakens the Stateflow diagram Parallel AN D States Start of event E_one processing Start of event E_t wo processing E_one processing is preempted Event E_ one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_ one Thereis no valid transition State A executes and completes during actions durA State A s children are parallel AND states They are evaluated and exe cuted from left to right and top to bottom Stated A1 is evaluated first State A A1l executes and completes during actions dur A1 State A A1 checks for any valid transitions as a result of event E_ one There is a valid transition from stateA Al Ala tostateA Al Alb State A Al Ala executes and completes exit actions exit Ala State A Al Ala is marked inactive 7 Transition action generating event E_t wo is executed and completed a Thetransition from stateAla tostateAlb as a result of eventE_one is now preempted by the broadcast of event E_t wo b The broadcast of event E_t wo awakens the Stateflow diagram a second time The Stateflow diagram root checks to see if there is a valid transi tion as aresult of E_t wo The
264. ntinues until C_one is false Assume that after five loops C_one is false The next possible transition segment to the next connective junction is evaluated It is an unconditional transition segment with a condition action Thetransition segment is taken and the condition action d my_func is executed and completed The returned value of d is 84 The next possible transition segment is evaluated There are three possible outgoing transition segments to consider Two are conditional one is uncon ditional The segment labeled with the condition d lt 100 is evaluated first based on the geometry of the two outgoing conditional transition segments Since the return value of d is 84 the condition d lt 100 istrueand this tran sition to the destination state A Al is valid State A Al exit actions execute and complete exit A1 State A A1 is marked inactive State A Al is marked active 10 State A Al entry actions execute and complete ent A1 11 The Stateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one Connective Junctions Example Transitions from a Common Source to Multiple Destinations This example shows the semantics of transitions from a common source to multiple destinations Bi i entry entB State A is during durBQ active entry entA exit exitB during durAQ
265. nts task 5 18 adding local data task 5 19 what are the events task 5 17 what is the data task 5 18 getting started example 5 16 getting started solution 5 16 getting started task overview 5 16 events hierarchy and scope 3 9 exclusive OR state notation 6 11 exit keyword 2 26 E xplorer add menu 5 7 contents of list 5 6 deleting objects from 5 8 edit menu 5 6 file menu 5 6 help menu 5 7 main window 5 5 moving objects to change index and port order 5 8 moving objects to change parents 5 8 object hierarchy list 5 5 overview 5 2 typical tasks 5 3 user interface 5 5 exploring and searching overview 5 2 exported data 4 28 event 4 25 external code sources defining interface for 4 25 definition 4 25 F falling edge triggered 3 18 Finder dialog box 5 20 clear button 5 22 close button 5 22 display area 5 23 help button 5 22 matches field 5 22 object type 5 21 refine button 5 22 representing hierarchy 5 24 search button 5 22 search history list 5 22 search method 5 21 string criteria field 5 20 glossary definition A 11 overview 5 2 typical tasks 5 4 user interface 5 20 finite state machine glossary definition A 6 references 1 7 representations 1 6 what is 1 6 flow diagram f or loop notation example 6 35 notation example 6 36 notation optimization 9 9 notation overview 6 32 overview example 6 36 for loop notation example 6 35 semantics example 7 35 1 7 Index function call combining with edge triggers 3 19
266. o specify the directory and filename for the Simulink model Closes the current Stateflow diagram Closes all open and or iconified Stateflow diagrams in the Simulink model Prints the graphical portion of the current Stateflow diagram Displays a submenu of file format choices Displays the platform specific printer setup dialog box PC only Closes all open Stateflow diagrams and models Exits Stateflow Simulink and MATLAB environments 2 Using the Graphics Editor Print As Submenu The Print As submenu of the File menu provides these printing options Menu Choice Description PostScript Saves the Stateflow diagram as a PostScript file Color PostScript Saves the Stateflow diagram as a color PostScript file Encapsulated Saves the Stateflow diagram as an encapsulated PostScript PostScript file Tiff Saves the Stateflow diagram as at iff file J peg Saves the Stateflow diagram as aj peg file Bitmap to Copies the Stateflow diagram to the clipboard PC Clipboard platform only Selection of one of these choices generates a file of the specified typein the directory defined as the MATLAB working directory Enterhel p cd inthe MATLAB command window to display help on how to change the working directory See the section titled Printing Large Stateflow Diagrams on page 2 23 for information on printing large Stateflow diagrams 2 44 M ain Editor M enus Edit Menu The Edit menu provides th
267. o be awakened by the next event g Al entry entA during durAQ exit exitA State A is marked inactive By State B is marked active entry entB during durB exit exitBQ Event Driven Effects on Semantics Semantics of State Actions Anentry action is executed as a result of any transition into the state The state is marked active beforeits ent ry action is executed and completed A during action executes to completion when that stateis active and an event occurs that does not result in an exit from that state Anon event_name action executes to completion when the event specified event _name occurs and that state is active An active state executes its during andon event _name actions before processing any of its children s valid transitions During andon event _name actions are processed based on their order of appearance in the state label Anexit action is executed as a result of any transition out of the state The state is marked inactive after theexi t action has executed and completed Semantics of Transitions Transitions play a largerolein defining the animation or execution of a system Transitions have sources and destinations thus any actions associated with the sources or destinations are related to the transition that joins them The type of the source and destination is equally important to define the semantics The examples provided in this chapter show how the semantics are defined
268. o clock position on the junction A j a asz C_four 4 C_three 3 In this example thetransitions are of equivalent label priority The conditions C_three 3 and c_f our 4 are both true Given that the outgoing transitions from the junction are evaluated in this order 1 A gt B Since the condition C_one 1 is false this transition is not valid 2 A gt C Since the condition C_t wo 2 is false this transition is not valid 3 A gt D Since the condition C_t hr ee 3 is true this transition is valid and is taken 4 A gt E This transition even though it too is valid is not evaluated since the pre vious transition evaluated was valid 7 64 Execution O rder States Multiple outgoing transitions from states that are of equivalent label priority are evaluated in a clockwise progression starting from a twevle o clock position on the state C_three 3 P In this example the transitions are of equivalent label priority The conditions C_two 2 and C_thr ee 3 are both trueand C_one 1 is false Given that the outgoing transitions from the state are evaluated in this order 1 A gt B Since the condition C_one 1 is false this transition is not valid 2 A gt C Since the condition C_two 2 is true this transition is valid and is taken 3 A gt D This transition even though it too is valid is not evaluated since the pre vious transition evalu
269. of the segments are labeled with condition actions i 0 and i func1 Using the Connective junction and condition action notation in this manner is a closer representation of af or loop than could be otherwise represented using states Theelimination of unnecessary states also optimizes the use of memory For data that does not need to be persistent use of Temporary data objects provides a memory use optimization Definingi to bea Temporary data object parented by the chart also improves memory use See Data Scope on page 3 27 for more information on Temporary data objects Parsing Parsing Parser The parser evaluates the graphical and nongraphical objects in each Stateflow machine against the supported Stateflow notation and the action language syntax Parse the Machine or the Stateflow Diagram Explicitly parse each Stateflow diagram in the machine by choosing Parse from the graphics editor Tools menu Explicitly parse the current Stateflow diagram by choosing Parse Diagram from the graphics editor Tools menu The machine is implicitly parsed before code generation by e Choosing Start from the graphics editor Simulation menu e Choosing Start from the Simulink model Simulation menu Choosing Open Simulation Target from the graphics editor Tools menu to display the Target Configuration sfun properties dialog box Click on the Generate Code Only or Build Stateflow Target buttons in the Target Configuration sfun d
270. oints When a global breakpoint is encountered normal simulation execution stops and the Debugger takes control on any Chart entry Click on the Chart Entry checkbox check is displayed when enabled to enable this type of breakpoint Event broadcast Click on the Event Broadcast checkbox check is displayed when enabled to enable this type of breakpoint State entry Click on the State Entry checkbox check is displayed when enabled to enable this type of breakpoint The breakpoints can be changed during runtime and areimmediately enforced When you save the Stateflow diagram the breakpoint settings are saved Stateflow Debugger User Interface Debugger Action Control Buttons Use these buttons when debugging a Stateflow machine to control the Debugger s actions Go Click on the Go button to have simulation execution proceed until a breakpoint global or local is reached Once the Go button has been clicked the Stateflow diagram is marked read only The appearance of the graphics editor toolbar and menus changes so that object creation is not possible When the graphics editor is in this read only mode it is called iced Step Click on the Step button to single step through the simulation execution Break Click on the Break button to insert a breakpoint at that point in the simulation execution Stop Simulation Click on the Stop Simulation button to stop the simulation execution and relinquish debugging c
271. ok for text field and enter A2 3 Click on and enable the Exact word match radio button 5 28 Searching for an Exact String M atch Click on the Search button These are the results of the search EJ Stateflow Finder sf_exp_srch State O AZ EREET There is one match The Search History shows that the current search criterion isAl objects with A2 Thedisplay shows the match is an exclusive O state labeled A2 in a Stateflow diagram titledsearch_ ex The parentage of that stateis A 5 29 5 Exploring and Searching Searching for All Objects of a Specified Object Type Example This Stateflow diagram is used to show how to search for all objects of a specified type E_three C_one E_one C_one 1 Select Find from the Tools menu of the Stateflow graphics editor window to invoke the Finder 2 Ensure that the Transitions object type is checked A checkmark indicates that object is included in the search criteria By default all object types are included in the search criteria Deselect all other object types 5 30 Searching for All O bjects of a Specified O bject Type 3 Click on the Search button These are the results of the search Ey Stateflow Finder sf_exp_srch of x search_ex search_ex A search_ex A AZ three C_one search_ex A There are six matches The Search History shows that the current search criterion isTransi tions The display show
272. ols 10 10 break button 10 9 break on controls 10 8 breakpoints 10 3 breakpoints display 10 11 browse data display 10 11 call stack display 10 11 clear output display 10 11 conflicting transitions definition 10 18 detecting 10 18 example 10 18 coverage display 10 11 cyclic behavior definition 10 21 detecting 10 21 example 10 22 data range violation definition 10 20 detecting 10 20 example 10 20 debugging conflicting transitions 10 18 debugging cycle detection 10 21 debugging data range violations 10 20 debugging runtime errors example 10 12 choose options task 10 14 create mode task 10 13 debug simulation task 10 14 definesf un task 10 14 example Stateflow diagram 10 12 resolve errors task 10 15 solution Stateflow diagram 10 15 start simulation task 10 14 typical tasks 10 13 debugging state inconsistencies 10 16 display controls 10 11 dynamic check cyclic behavior 10 10 data range violation 10 10 state inconsistency 10 10 transition conflict 10 10 Dynamic Checker options 10 10 flow cyclic behavior example 10 23 glossary definition A 10 go button 10 9 including in the target build 10 3 main window 10 6 MATLAB command field 10 11 overview 10 2 runtime debugging 10 4 state inconsistency causes 10 16 definition 10 16 detecting 10 16 example 10 17 status display area 10 8 step button 10 9 stop simulation 10 9 typical tasks 10 3 user interface 10 6 Index debugging enable 9 24 overview 10 2 runtime 10 4 decom
273. on call that passes Stateflow data as arguments Notice the use of format specifiers g and d as are used in the C language function printf 6 51 6 Notations These data objects are defined e d1 anda are Local data objects of type double in the Stateflow diagram e d2 isan Output to Simulink data object of type integer in the Stateflow dia gram e x must be defined in the MATLAB workspace prior to the execution of the condition action where it is used if it is not defined a runtime error is gen erated These three values are passed as arguments toa user written function The g and d characters are format specifiers that print the current values of d1 and d2 intoeval String at appropriate locations For example if d1 equals 3 4 and d2 equals 5 using the format specifiers these are mapped into my_func 3 4 x 5 This string is then sent to MATLAB and is executed in the MATLAB workspace Example Three ml Function Call This is an example of aml function call with string arguments C_one a mI my_string_func g abed efg x d d1 d2 These data objects are defined in the Stateflow diagram e d1 isa Local data object of type double e d2 is an Output to Simulink data object of type integer The user written function my_string_func expects four arguments where the second argument is a string The g and d characters are format specifiers that print the current values of dl andd2 intoeval String at appr
274. onal matrix v in the MATLAB workspace Ifv does not exist prior to the execution of this statement then it is automatically created by MATLAB workspace If my_func returns a vector thefirst element is assigned to v 5 6 7 If it isa structure a cell array or a string the result is undefined Choosing Between the ml function and the ml Name Space Operator It is recommended to use the ml name space operator wherever possible The ml namespace operator is faster and more robust than theml function If you need to work with MATLAB matrices instead of scalars then usetheml function 6 55 6 Notations In this example the ml function must be used to specify an array argument a mi my_function 1 4 g d1 x isa MATLAB workspace matrix my_ function isa MATLAB function that expects a vector as its first argument and a scalar as a second argument Data and Event Arguments Unqualified data and event objects are assumed to be defined at the same level in the hierarchy as the reference to them in the action language Stateflow will attempt to resolve the object name by searching up the hierarchy If the data or event object is parented elsewhere in the hierarchy you need to define the hierarchy path explicitly Arrays Arrays specified as arguments to user written functions are essentially ignored by Stateflow and represented as is in the generated code Event Broadcasting You can specify an event to
275. onment sequential execution order is the only option In this case it may be necessary for you to know the implicit ordering determined by a Stateflow diagram The ordering is specific to transitions originating from the same source K nowing the order of execution for Stateflow diagrams with more than one parallel AND state may be important Werecommend that you do not design your Stateflow diagram based on an expected execution order Execution Order Guidelines Execution order of transitions originating from the same source is based on these guidelines The guidelines appear in order of their precedence 1 Transitions are evaluated based on hierarchy in a top down manner In this example when an event occurs and state A A1 is active the transition Execution O rder from state A A1 to state B is valid and takes precedence over the transition from stateA Al to state A A2 based on the hierarchy State A1 is active 2 Transitions are evaluated based on their labels a Labels with events and conditions b Labels with events c Labels with conditions d Nolabel 3 Equivalent transitions based on their labels are evaluated based on the geometry of the outgoing transitions The geometry of junctions and states is considered separately 7 63 7 Semantics Junctions Multiple outgoing transitions from junctions that are of equivalent label priority are evaluated in a clockwise progression starting from a twelve
276. ontrol Once the debug session is stopped the graphics editor toolbar and menus return to their normal appearance and operation so that object creation is again possible 10 9 10 Debugging 10 10 Dynamic Checker Options The Dynamic Checker functionality is available if this product has been licensed Enable checking for these conditions by turning on the checkbox for these options State inconsistency Click on the State Inconsistency checkbox check is displayed to enable Transition conflict Click on the Conflicting Transitions checkbox check is displayed to enable Data range values out of specified bounds Data object attributes include an Initial Minimum and Maximum value If the data object equals a value outside of this range enabling data range checking will detect the error Click on the Data Range Check checkbox check is displayed to enable Cyclic behavior Click on the Detect Cycles checkbox check is displayed to enable Animation Controls Activating animation causes visual color changes objects are highlighted in the selection color in the Stateflow diagram based on the simulation execution Activate animation by turning on the Enabled check box Deactivate animation by turning on the Disabled check box You can specify the animation speed from a range of 0 fast the default to 1 slow seconds Stateflow Debugger User Interface Display Controls Use these buttons to control the output d
277. opaste the most recently cut selection list of objects choose Paste from either e The Edit menu on the main window e The right mouse button shortcut menu Pressing the Ctrl and V keys simultaneously is the keyboard equivalent to the Paste menu item Copying Objects To copy and paste an object in the drawing area select the object s click and hold the right mouse button down and drag to the desired location in the drawing area This operation also updates the Stateflow clipboard Using the Graphics Editor Alternatively to copy from one Stateflow diagram to another choose the Copy and then Paste menu items from either e The Edit menu on the Stateflow graphics editor window e Any right mouse button shortcut menu Pressing the Ctrl and C keys simultaneously is the keyboard equivalent to the Copy menu item States that contain other states superstates can be grouped together See Grouping and Ungrouping States on page 2 26 Once selected you can copy a group as though it was a single object All objects in the group are copied 2 17 2 Using the Graphics Editor Working with Charts Stateflow Diagrams Overview In Simulink each chart Stateflow diagram is represented by a Stateflow block A Simulink model can consist of combinations of Simulink blocks toolbox blocks and Stateflow blocks Stateflow diagrams The collection of Stateflow blocks in the Simulink model is the Stateflow machine In Stateflow
278. opriate locations Notice that the string is enclosed in two single quotes 6 52 Action Language Use Guidelines These guidelines apply to ml functions e The first argument must be a string e If thereare multiple arguments ensure that the number and types of format specifiers g d etc match the actual number and types of the argu ments These format specifiers are the same as those used in the C function printf e A scalar of type double is returned e ml function calls can be nested Calls tomli functions should be avoided if you plan to build an RTW target that includes code from Stateflow Coder ml Name Space Operator The MATLAB name space operator ml is used to get and set variables in the MATLAB workspace Them operator can also be used to access MATLAB functions that operate on scalars in a convenient format Usethenotation a ml func_name tocall a MATLAB function that does not accept any arguments Omission of the empty brackets causes a search for a variable of the name specified The variable will not be found and a runtime error is encountered during simulation Use of the ml name space operator should be avoided if you plan to build an RTW target that includes code from Stateflow Coder 6 53 6 Notations Example Using the ml Operator to Access MATLAB Workspace Variables This is an example of using the ml operator to get and set variables in the MATLAB workspace C_one
279. or the new event Double click on the machine name the name you specified when you saved the Simulink model in the Object Hierarchy list Double click on the chart 8 19 8 Tutorial Entering a Stateflow Diagram name the name you specified on the Stateflow block The chart will be the parent for all the events in the carousel example 3 Choose Event from the E xplorer Add menu The Event properties dialog box is displayed 4 Enter Swi tch_on in the name field 5 Select Input from Simulink in the Scope field 6 Click on the Apply button to save the Scope field 7 Sincethe Scopeis Input from Simulink an index number is displayed Y ou do not need to change the index number 8 Select Either Edge in the Trigger field 9 Click on the Close button to save the changes and close the dialog box 10 Repeat these steps for each Input from Simulink event entering the appropriate text in the Name field Add and Define Data Objects Data are added removed and edited using the Explorer These data objects must be defined Ti me Speed Duration andMax_speed Add and Define Local Data TheTi me data object is local 1 Choose Explore from the Tools menu of the graphics editor 2 Select the parent for the new data object Double click on the machine name the name you specified when you saved the Simulink model in the Object Hierarchy list Double click on the chart 8 20 Procedure 5 6 name the name you specifi
280. orners resizes the state You know you are at the resizing location on the state border when the cursor appears as a double ended arrow Click on the within the superstate and enter the text Ri de Deselect the superstate to exit the edit Click on the State button B and place thePower_on state in the drawing area Resize the Power _on state to create a superstate Dragging any one of the state s corners resizes the state You know you are at the resizing location on the state border when the cursor appears as a double ended arrow Click on the within the OR superstate and enter the text Power _on Deselect the OR superstate to exit the edit Click on the State button E and placetheTi mer statein the drawing area ResizetheTi mer stateto create a superstate Dragging any one of the state s corners resizes the state You know you are at the resizing location on the state border when the cursor appears as a double ended arrow Click on the within the OR superstate and enter the text Ti mer Deselect the OR superstate to exit the edit 10 Display the state shortcut menu by placing the cursor inside the borders of the Power on state but outside the borders of any of Power _on s substates and clicking the right mouse button Choose the Parallel AND decomposition menu item Sample Snapshot Your Stateflow diagram should now look similar to this Stateflow diagram 8 13 8 Tutorial Entering a Stateflow Diagram 8 14
281. ould be simplified by using an inner transition E_one C_one E_one C_two E_one C_one E_one C_two 6 27 6 Notations Any event occurs and awakens the Stateflow diagram The default transition to the connective junction is valid The destination of the transition is determined by C_one and C_two If C_one istrue thetransition toAl is true If C_t wo is true the transition to A2 is valid If neither C_one nor C_two istrue thetransition toA3 is valid Thetransitions amongA1 A2 and A3 are determined by E_one C_one and C_two Example One Inner Transition to a Connective J unction This example shows a solution to the same problem Example One using an inner transition to a connective junction State Al is initially active Any event occurs and awakens the Stateflow diagram The default transition to the connective junction is valid The destination of the transitions is determined by C_one and C_two The Stateflow diagram is simplified by using an inner transition in place of the many transitions amongst all the states in the original example If state A is already active the inner transition is used to re evaluate which of the substates of state A is to be active When event E_one occurs the inner transition is potentially valid If C_one istrue thetransition toA1 is valid If C_two istrue thetransition toA2 is valid If neither C_one nor C_two is true the transition to 43 is vali
282. plete x x 6 TheStateflow diagram goes back tosleep waiting to be awakened by another event 7 Theband pass filter block is triggered executes and completes 4 15 4 Defining Stateflow Interfaces 4 16 Event Inputs from Simulink Tasks to Define an Event Input from Simulink These tasks describe how to add and define the necessary fields for an event input from Simulink e Add an event choosing a chart as the parent of the event e Choose Input from Simulink as the Scope e Specify the Trigger type e Apply and save the changes Add an Event Choosing a Chart as the Parent These steps describe how to add an event 1 Choose Explore from the graphics editor Tools menu to invoke the Explorer 2 Select the chart object in the hierarchy that you want to be the event s parent You must explicitly choose a parent to create an event Choosing the chart to be the parent of the event enables receive rights to Simulink tothe chart and all its offspring 3 Choose Event from the E xplorer Add menu The Event properties dialog box is displayed 4 Enter a name in the Name field Choose Input from Simulink as the Scope Once you have chosen the chart as the parent the choice of valid scopes includes Local Input from Simulink or Output to Simulink Choose Input from Simulink as the Scope to enable send rights to Simulink and any offspring of the chart and to enable receive rights to the chart and all of its offsprin
283. position glossary definition A 5 specifying 2 24 default transition anda history junction semantics example 7 21 creating 2 32 definition 1 20 glossary definition A 5 in an exclusive OR decomposition semantics example 7 18 labeled default transition semantics example 7 23 notation example 6 25 notation labeling 6 24 notation overview 6 24 to a junction notation example 6 26 to a junction semantics example 7 20 with a label notation example 6 26 defaults chart 2 51 colors 2 51 data 2 54 event 2 54 how to change 2 50 junction 2 53 machine 2 50 state 2 53 target 2 52 transition 2 53 defaults file overview 2 50 directed event broadcasting send semantics example 7 58 using qualified event names notation example 6 60 using qualified event names semantics example 7 60 usingsend notation example 6 59 document link customization 9 25 during keyword 2 26 E edge trigger type either edge 3 18 falling edge 3 18 rising edge 3 18 edge triggered defining output events 4 13 example output event semantics 4 13 either edge triggered 3 18 entry keyword 2 26 error messages code generation 9 32 code generation related 9 30 compilation 9 32 parsing 9 30 target building 9 32 1 5 Index event broadcasting 6 56 definition 1 14 description property 3 7 directed event broadcast using qualified names 6 60 directed event broadcasting 6 58 exported 4 25 exported to an external code source 3 13 imported 4 27 imported from an
284. product is required to generate code for stand alone and RTW targets Invoke the Explorer This section shows how to add a stand alone target using the E xplorer Y ou can also add a stand alone target by choosing Target from the graphics editor Add menu Toinvoke the Explorer 1 Open the Stateflow diagram 2 Choose Explore from the graphics editor Tools menu The Explorer is displayed Ed Exploring sf_exp_srch explore_ex O x File Edit Add Help Object Hierarchy Contents of chart sf_exp_srch explore_ex event2 local event input 1 C search ex eventi output 2 M untitled Data 6 data local datal input 1 data2 output 1 data4 workspace data3 temporary data5 constant Adding and Specifying a Stand Alone Target Add a Stand Alone Target These steps show how to add a stand alone target 1 In the Explorer window select a machine as the target s parent Choose New from the Explorer File menu The Stateflow Target Configuration dialog box is displayed a Stateflow Target Configuration untitled iofjx Imee 2 Enter the target name in the Name field 3 Specify the Coder Command The Coder Command field defines how the code is to be generated The code command consists of the name of the coder function without the file exten stion followed by any flags and the target name The default coder function 9 17 9 Generating Code 9 18 provided iss f c See Coder Command Customizatio
285. r The three transitions in the example are represented as switch_off Power_off Transition Parent Source Destination Label switch_off Power_on Low Heat Power_off Switch_high Power_on switch cold Power_on Low Power_on Low Heat Power_on Low Heat Power_on High Power_on Low Col d O verview Example Representing Event Hierarchy Event hierarchy is defined by specifying the parent of an event when you create it Events are nongraphical and are created using either the graphics editor Add menu or the Explorer Using hierarchy you can optimize event processing through directed event broadcasting Directed event broadcasting is the ability to qualify who can send and receive event broadcasts See Events on page 3 5 and Stateflow Explorer User Interface on page 5 5 for more information See Action Language on page 6 42 for more information on the notation for directed event broadcasting 6 9 6 Notations 6 10 States Overview A state describes a mode of a reactive system States in a Stateflow diagram represent these modes The activity or inactivity of the states dynamically changes based on events and conditions Every state has hierarchy In a Stateflow diagram consisting of a single state that state s parent is the Stateflow diagram itself A state also has history that applies to its level of hierarchy in the Stateflow diagram States can have actions that are
286. r You need to ungroup the superstate to select objects within the superstate Showing and Hiding States Hiding the contents of a superstate simplifies the Stateflow diagram if that level of detail is not necessary at a particular moment Tohidethe contents of a superstate move the cursor over the superstate press the right most mouse button to display the State shortcut menu and choose Show Hide Hiding the contents of an ungrouped state causes the state to be grouped Choosing the Show Hide menu item toggles between the two choices Resizing States Toresize a state drag one of the state s corners When the cursor is over a corner it appears as a double ended arrow PC only cursor appearance will vary on other platforms If you resize a grouped superstate the contents of the grouped superstate are resized appropriately The font size of state labels is proportionally resized Changing Font Size You can adjust font size through the shortcut menus using a virtual scrollbar To adjust font size with the virtual scrollbar 1 Select the state s whose label font size you want to change 2 Right click on a selected state whose font you want to change to display the shortcut menu 3 Place the cursor over the Font Size menu item 4 Click and drag horizontally on the Font Size menu item The shortcut menu disappears and a numeric size is displayed 5 Drag the mousetothe left to decrease the font size or tothe right toincrease the
287. r the Font Size menu item Arrowhead Size Fit To View SelectAll Explore Debug Find Properties 3 Click and drag horizontally on the Font Size menu item Theshortcut menu disappears and a numeric size is displayed 2 8 The Graphics Editor M ain W indow 4 Dragthemousetothe left to decrease the font size or tothe right toincrease the font size If you are using the general shortcut menu the font size of all labels on any selected objects is adjusted If you are using one of the object specific shortcut menus the font size of all labels on any selected objects of that type is adjusted 2 9 2 Using the Graphics Editor Shortcut Menus Overview Shortcut menus provide a quick way to perform common functions The shortcut menus are context sensitive Clicking the right mouse button displays the shortcut menu for the object the cursor is positioned over There are four shortcut menus that are displayed depending upon where the cursor is positioned e General not over any object see General Shortcut M enu on page 2 12 e State over a state see State Shortcut Menu on page 2 13 e Transition over a transition see Transition Shortcut M enu on page 2 14 e J unction over a junction see J unction Shortcut Menu on page 2 14 Menu Options Available on All Shortcut Menus All of the shortcut menus have these menu options Menu Choice Description Cut Moves selected object s
288. rable in stand alone targets Ensure that the appropriate check boxes are disabled See E nable Dynamic Checker Options on page 9 24 and Chapter 10 Debugging for more infor mation Specify any custom code Enter any customized code that you want to be prepended to the generated target code in this field See Add Customized Code on page 9 25 for more information Specify a document link See Specify a Document Link on page 9 25 for more information Save and apply the target information Click the Apply button to save and apply the target information you have specified Click on the Close button to save the changes and close the dialog box 9 19 9 Generating Code Customizing the Target 9 20 Overview You can customize the default sf un simulation target any stand alone target you have added as well as ther t w target if you are using Real Time Workshop You can customize thes f un target using the Target Configuration sfun dialog box You can customize ther t w target using the Target Configuration rtw dialog box You can customize any stand alone target by using its Target Configuration dialog box Potential Customizations These are common customizations you can make to the target e Modify the Coder Command field e Modify the Make Command field stand alone targets only e Enable Debugging Animation simulation targets only e Enable Dynamic Checker options simulation targets only e
289. ract with stand alone targets and the overhead incurred from the added instrumented code is undesirable in stand alone targets Debugging Animation should always be disabled for r t w targets The Debugger does not interact with r t w targets Enable Dynamic Checker Options Click on the checkboxes in the Target Configuration dialog box to include the necessary code for these dynamic checks e State inconsistencies State inconsistencies can occur as a result of event processing For example at least one but only one substate of a superstate with exclusive OR Customizing the Target decomposition should be active Another example is that all substates of a superstate with parallel AND decomposition should be active e Data range violations Data range checking verifies that a data object value does not assume a value less than the minimum nor greater than the maximum values specified in the object s definition e Transition conflicts Transition conflicts exist if more than one transition from the same source are equivalently valid at any one time Generally speaking the Dynamic Checker options should be disabled for stand alone targets The overhead incurred from the added instrumented code is undesirable in stand alone targets The Dynamic Checker options should always be disabled for r t w targets The Debugger does not interact with r tw targets The Debugger displays results of these dynamic checks as well as cycle
290. ransition as a result of E_ one A valid transition from stated to stateB is detected The Condition Actions condition C_one istrue The condition action A_one is detected on the valid transition and is immediately executed and completed Statea is still active 2 Stated exit actions execute and complete Exit A 3 Stated is marked inactive 4 Thetransition action A_t wo is executed and completed 5 States is marked active 6 StateB entry actions execute and complete ent B 7 TheStateflow diagram goes back tosleep waiting to be awakened by another event This sequence completes the execution of the Stateflow diagram associated with event E_one when stateA was active Example Using Condition Actions in For Loop Construct Condition actions and connective junctions are used to design af or loop construct This example shows the use of a condition action and connective junction to create af or loop construct Stated is f active entry entA E one i 0 Bs during durA entry entB exit exitA during durB exit exitBQ i lt 10 i funct See Example F or Loop Construct on page 7 35 to see the semantics of this example 7 15 7 Semantics 7 16 Example Using Condition Actions to Broadcast Events to Parallel AND States Condition actions can be used to broadcast events immediately to parallel AND states This example shows this use State Ala is active s en
291. ransitions 8 7 determining events 8 7 determining state decomposition 8 5 determining state labels 8 6 determining states 8 4 determining transitions 8 6 label the transitions task 8 16 objectives 8 2 overview 8 2 provided models 8 2 sample Stateflow diagram 8 10 save the model task 8 23 task overview 8 8 typographical conventions xxvii U unary actions 6 48 unary operations 6 47 user written functions 6 49 V virtual scrollbar example of adjusting font size 2 8 glossary definition A 11 overview 2 7 1 15
292. reis no valid transition c State A executes and completes during actions dur A d StateA s children are evaluated starting with stateA A1 StateA Al exe cutes and completes during actions dur A1 StateA A1 is evaluated for 7 51 7 Semantics End of event E two processing 7 52 valid transitions There are no valid transitions as a result of E_t wo within state Al StateA A2 is evaluated StateA A2 executes and completes dur i ng actions dur A2 State A A2 checks for valid transitions State A A2 has a valid transition as a result of E_t wo from state A A2 A2a tostateA A2 A2b State A A2 A2a exit actions execute and complete exi t A2a State A A2 A2a is marked inactive State A A2 A2b is marked active Stated A2 A2b entry actions execute and complete ent A2b The State flow diagram activity now looks like this A entry entA during durA exit exitA entry entA1 11 entry entA2 during durA1 11 during durA2 exit exitA 1 1 exit exitA2 i A2al peo entA tat E entry entA2a tia vt during durA2a during durAta exit exita2a exit exitAla E_one E_two Abi it A2b State A2b entry entA1b 11 entry entA2b p s during durA1b 11 during durA2b is active exit exitA 1b 1 exit exitA2b Parallel AN D States Continuation of event E_one 9 StateA A1 Alb is marked active processing 8 StateA Al
293. returns to the next statement in the execution sequence Using function call triggers the Stateflow block can control the execution of other Simulink blocks in the model Usea function call event output when you want a Stateflow block logic portion control flow to control one or more Simulink blocks algorithmic portion data flow This example shows a use of function call output events E funcall OL x File Edit Simulation Format Tools Gererstor Band Limited White Noise functon call u x band pass fiter2 tuncton call u y band pass filteri Thecontrol block is a Stateflow block that has one data input called pul se and two event Function Call outputs calledfilter1 andfilter2 A pulse generator provides input data tothecontrol block Within thecontrol block a determination is made whether to make a function call tofi lter1 or filter2 If for example the Output to Simulink event Function Call filter is broadcast theband pass filter1 block executes and then returns to the next execution step in thecontrol block As part of its execution band pass filter1 receives unfiltered input data and outputs filtered data for display on a scope The Stateflow block controls the execution ofband pass filterl andband pass filter2 4 11 4 Defining Stateflow Interfaces 4 12 Example Function Call Semantics In this examplethetransition from stated tostateB in the Stateflow diagram has a transition
294. rget hardware 6 61 6 Notations Literals Place action language you want the parser toignore but you want to appear as entered in the generated code within characters For example ptr gt field 1 0 The parser is completely disabled during the processing of anything between the characters F requent use of literals is discouraged Continuation Symbols Enter the characters at the end of a line to indicate the expression continues on the next line Comments These comment formats are supported e MATLAB comment line e C comment line e C comment line Use of the Semicolon Omitting the semicolon after an expression displays the results of the expression in the MATLAB command window If you use a semicolon the results are not displayed Semantics Overview Event Driven Effects on Semantics Transitions to and from Exclusive OR States Condition Actions Default Transitions Inner Transitions Connective J unctions Event Actions Parallel AND States Directed Event Broadcasting Execution Order Semantic Rules Summary 7 2 7 8 7 13 7 18 7 25 7 33 7 43 7 45 7 58 7 62 7 67 7 Semantics Overview What Are Semantics Semantics describe how the notation is interpreted and implemented A completed Stateflow diagram communicates how the system will behave A Stateflow diagram contains actions associated with trans
295. ription a expression Equivalent toa a expression bit operation a amp expression Equivalent toa a amp expression bit operation a expression Equivalent toa a expression bit operation Action Language User Written Functions You can specify calls to user written functions in the action language These guidelines apply to user written function calls e Define a function by its name any arguments in parenthesis and an optional semicolon e You can specify up to 50 arguments in the function call e String parameters to user written functions are passed between single quotes For example func string e You can nest function calls Example Function Call Transition Action These are example formats of function calls using transition action notation e c function_name arg1 arg2 arg3 e c function_name function_name2 arg1 arg2 arg3 IfS1 is active evente occurs c is true and the transition destination is determined then a function call is madetofunction_ name withargl arg2 andarg3 Thetransition action in thetransition froms2 toS3 shows a function call nested within another function call 6 49 6 Notations Example Function Call State Action These are example formats of function calls using state action notation si Gan function_name2 arg1 5 S27 Sn nmin When the default transition into 1 occurs S1 is marked active and then its entry action a functio
296. roduction 1 30 Defining the Stateflow Interface In this example there are no external code sources to include in the interface definition These steps show how to define the Stateflow block interface in the Simulink model 1 Add and define input events within the Stateflow diagram a h Choose Explore from the graphics editor Tools menu to invoke the Explorer Double click on the machine name same as the Simulink model name in the Object Hierarchy list Click on the0On_off chart entry in the Object Hierarchy list Select Event from the Add menu Enter Swi tch in the Name field of the Event properties dialog box Select Input from Simulink as the Scope value Select Rising Edge as the Trigger type Click on the Close button to apply the changes and close the window Choose Close from the Explorer File menu to close the E xplorer 2 Make connections in the Simulink model between other blocks and the Stateflow block b Enter Si mul i nk in the MATLAB command window to invoke Simulink Add a Sine Wave block located in the Simulink Sources block library and connect it to the input trigger port of the Stateflow block Using Stateflow c Adda Scope block located in the Simulink Sinks block library and con nect it to the Sine Wave block output as well Your model should look sim ilar to this Pe sf_intro_example Click on the Close button to apply the changes and close the dialog box 3 Define Si
297. rousel operator s console The switches allow you to e Turn the carousel power on and off e Start the ride e Stop the ride in case of emergency e Specify whether the speed is in the normal or overspeed range Run the Simulation for the Provided Solution Carousel Solution Stateflow Diagram This is the provided carousel Stateflow diagram solution Power_on pSSGSbctcccccececccceeecee i Switthone ort rrr rrr rrr ccc ccce os 8 lt a Speed gt Max_speedi Time gt Duration Ride_cone Pi EG A AE ae 4 time_base ar es Time 0 1 Procedure Follow these steps to run the simulation 1 Double click on the Examples block in the Stateflow model window Double click on the Carousel and then the Basic Functional Carousel block 2 Choose Start from the graphics editor Simulation menu The first time you run the simulation and any time you have modified the Stateflow diagram choosing Start will parse the machine generate simulation code and generate the simulation target If the target build takes 8 25 8 Tutorial Entering a Stateflow Diagram 8 26 place informational messages are displayed in popup windows and in the MATLAB command window In any case the graphics editor is ICED and modifications to the Stateflow diagram are prohibited during a simulation The power switch has an off down and an on up position Turn the power on by clicking the power switch
298. rt the simulation 5 Debug the simulation execution 6 Resolve runtime error and repeat from step 3 Create the Model and Stateflow Diagram Using the sample see E xample Stateflow Diagram on page 10 12 as a guide create the Simulink model and Stateflow diagram Using the graphics editor Add menu add the Swi tch Input from Simulink event and theshift Input from Simulink data object 10 13 10 Debugging 10 14 Define the sfun Target Choose Open Simulation Target from the Tools menu of the graphics editor Ensure that the checkbox to Enable Debugging Animation is enabled checked Click on the Close button to apply the changes and close the dialog box Invoke the Debugger and Choose Debugging Options Choose Debug from the Tools menu of the graphics editor Click on the Chart entry option under the Break Controls border When the simulation begins it will break on the entry into the chart Click on the Enabled radio button under the Animation border to turn animation on Start the Simulation Click on the Go button to start the simulation Informational messages are displayed in the MATLAB command window The graphics editor toolbar and menus change appearance to indicate a read only interface The Stateflow diagram is parsed the code is generated and the target is built Because you have specified a breakpoint on chart entry the execution stops at that point and the Debugger display status indicates Stopped J
299. ry data Temp_sensor Delay is defined as oT Delay lt 64 Delay Temporary Start_8bit_adc delay 0 ii Temp could af Temp read_8bit_adc be dennad as Temporary Temp gt 200 Temp lt 100 Del ay is used only as a counter in the loop Once the delay loop is complete the value of Del ay is no longer needed If you were interested only in whether the Low Nor mal or Hi gh stateis active the value of Temp could be defined as Temporary as well Workspace A Workspace data object is a value that typically does not change during a simulation Workspace data objects are passed in from MATLAB and or Simulink Workspace data objects can be defined at the MATLAB command line or through Simulink mask initialization Stateflow will attempt to resolve the symbol first locally then in Simulink and lastly in MATLAB See the Using Simulink document for more information on mask initialization 3 30 Data Constant A Constant data object is read only and retains the initial value set in its data properties dialog box Exported An Exported data object is parented by and declared within the machine Exporting a data object provides the ability for external sources to access the data object the machine also retains the ability to access the data object It is the responsibility of the external source to include the Exported data in the manner appropriate to the source to make use of these rights
300. s false However active state B has a valid self loop transition 2 StateB exit actions execute and complete exit B 3 StateB is marked inactive 4 The self loop transition action A_f our executes and completes 5 States is marked active 6 StateB entry actions execute and complete ent B 7 TheStateflow diagram goes back tosleep waiting to be awakened by another event 7 27 7 Semantics 7 28 This sequence completes the execution of this Stateflow diagram associated with event E_t wo This example shows the difference in semantics between inner transitions and self loop transitions Example Processing One Event with an Inner Tran sition to a Connective J unction This example shows the semantics of an inner transition to a connective junction Al entry entA during durA exit exitA ate oe is mar entry entA 1 Aa AJ active duriko WAT entry entA2 entry entA3 pee during durA2 during durA3 ian exit exita2 exit exit i Initially the Stateflow diagram is asleep StateA1 is active EventE_one occurs and awakens the Stateflow diagram Condition C_t wo istrue EventE_one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 TheStateflow diagram root checks to see if there is a valid transition at the root level as a result of fone There is no valid transition 2 StateA during actions execute and complete dur A
301. s the matches 5 31 5 Exploring and Searching Searching Based on Multiple Conditions Example This Stateflow diagram is used to show how to search based on multiple conditions E_three C_one S E_one C_one 1 Select Find from the Tools menu of the Stateflow graphics editor window to invoke the Finder 2 Click in the Look for text field and enter A2 3 Click on and enable the Normal Wildcard radio box 4 Ensure that the States object type is checked A checkmark indicates that object is included in the search criteria By default all object types are included in the search criteria Deselect all other object types 5 32 Searching Based on M ultiple C onditions 5 Click on the Search button These are the results of the search z Stateflow Finder sf_exp_srch iof x search_ex A There are four matches The Search History shows that the current search criterion isStates with A2 The display shows the matches 5 33 5 Exploring and Searching Searching for an Object to Edit Properties Example This Stateflow diagram is used to show how to search for an object and edit its properties E_three C_one S E_one C_one 1 Select Find from the Tools menu of the Stateflow graphics editor window to invoke the Finder 2 Click in the Look for text field and enter E 3 Choose Name from the Look In field pull down menu 4 Click on and enable the Normal
302. s valid The transition s label See the section titled Labeling a Transition on page 6 18 for more information on valid label formats Textual description comment Enter a web URL address or a general MATLAB command Examples are www mathworks com mailto email address edit spec data speed txt Click on the Apply button to save the changes Click on the Revert button to cancel any changes and return to the previous settings Click on the Close button to save the changes and close the dialog box Click on the Help button to display the Stateflow Online Help in an HTML browser window 2 37 2 Using the Graphics Editor Working with J unctions 2 38 What Can You Do with J unctions You can e Create delete e Change size e Change arrowhead size e Move e Invoke the junction properties dialog box to Hyperlink to the junction s parent Adda description Link toa document Creating Deleting J unctions Tocreate one junction at atime click on a J unction button in the toolbar and click on the desired location for the junction in the drawing area To create multiple junctions double click on the J unction button in the toolbar The button is now in multiple object mode Click anywherein the drawing area to place a junction in the drawing area Additional clicks in the drawing area create additional junctions Click on theJ unction button or press the Escape key to cancel the operation W orking with Ju
303. seis an S function MEX file See the Using Simulink document for information on S functions See Customizing the Target on page 9 20 and Compiling Building a Simulation Target on page 9 27 for more information RTW target generation RTW generates the target including code generated from Stateflow Coder Stateflow Stateflow Coder Simulink and RTW are required Building a RTW target is an example of a prototype target See Customizing the Target on page 9 20 and Compiling Building Targets with RTW on page 9 27 for more information Stand alone nonsimulation non RTW target generation Stateflow Coder generates the target Stateflow and Stateflow Coder are required Using Stateflow Coder you can create multiple targets using specific compilers for prototyping or production use on particular hardware platforms See Adding and Specifying a Stand Alone Target on page 9 16 Customizing the Target on page 9 20 and Compiling B uilding Stand Alone Targets on page 9 28 for more information Compiling Code Building Targets Compiling Building a Simulation Target These steps show how to build a simulation target assuming you have already specified any customizations see Customizing the Target on page 9 20 1 Choose Open Simulation Target from the graphics editor Tools menu to display the Target Configuration sfun dialog box 2 Click on the Generate Code button in the Target Configuration sfun
304. self also called the Stateflow diagram root You can place states within other higher level states In the Graphical Components figure St at eAl is a child in the hierarchy toSt at eA A state also has history History provides an efficient means of basing future activity on past activity Anatomy of a Model and Machine States have labels that can specify actions executed in a sequence based upon action type The action types are entry during exit andon In an automatic transmission example the transmission can either be in neutral or engaged in a gear Two states of the transmission system are neutral andengaged engaged Stateflow provides two types of states parallel AND and exclusive OR states You represent parallelism with AND parallel states Thetransmission example shows exclusive OR states Exclusive OR states are used to describe modes that are mutually exclusive The system is either in the neutral state or theengaged state at any onetime Transitions A transition is a graphical object that in most cases links one object to another One end of a transition is attached toa source object and the other end to a destination object The sourceis where the transition begins and the destination is where the transition ends A transition label describes the circumstances under which the system moves from one state to another It is always the occurrence of some event that causes a transition to take place In
305. state is a substate if it is contained by a superstate Substate Superstate Substate Superstate A state is a superstate if it contains other states called substates Superstate Substate Substate Transition A transition describes the circumstances under which the system moves from one state to another Either end of a transition can be attached to a source and a destination object The sourceis where the transition begins and the destination is where the transition ends It is often the occurrence of some event that causes a transition to take place Virtual Scrollbar A virtual scrollbar enables you to set a value by scrolling through a list of choices When you move the mouse over a menu item with a virtual scrollbar the cursor changes to a line with a double arrowhead Virtual scrollbars are either vertical or horizontal The direction is indicated by the positioning of the A 11 G lossary arrowheads Drag the mouse either horizontally or vertically to change the value See the section titled Virtual Scrollbar on page 2 7 for more information A 12 A action language array arguments 6 56 assignment operations 6 48 binary operations 6 45 bit operations 6 44 choosing between mi and ml 6 55 comments 6 62 components 6 44 continuation symbols 6 62 data and event arguments 6 56 definition 1 19 directed event broadcasting 6 58 event broadcasting 6 56 glossary definition A 2 literals 6 6
306. stem enters by default in the absence of any other information such as a history junction Default transitions are also used to specify that a junction should be entered by default The default transition object is a transition with a destination but no source object Click on the Default transition button in thetoolbar and click on a location in the drawing area close to the state or junction you want to be the destination for the default transition Drag the mouse to the destination object to attach the default transition In some cases it is useful to label default transitions Oneof the most common Stateflow programming mistakes is tocreate multiple exclusive OR states without a default transition In the absence of the default transition there is noindication of which state becomes active by default Note that this error is flagged when you simulate the model using the Debugger with the State Inconsistencies option enabled This table shows the button icon and briefly describes a default transition Name Button Icon Description Default Usea Default transition to indicate when transition entering this level in the hierarchy which object becomes active by default Labeling of Default Transitions In some circumstances you may want to label default transitions You can label default transitions as you would other transitions F or example you may want to specify that one state or another should become active depending upon
307. stems by placing states within other higher level states A hierarchical design usually reduces the number of transitions and produces neat more manageable diagrams See the section titled Hierarchy on page 1 15 for more information History Junction A History junction provides the means to specify the destination substate of a transition based on historical information If a superstate has a History junction thetransition tothe destination substate is defined to be the substate that was most recently visited The History junction applies to the level of the hierarchy in which it appears Name Button Icon Description History Use a History junction to indicate junction l when entering this level in the hier archy that the last state that was active becomes the next state to be active See these sections for more information What Is a History J unction on page 6 40 Example Default Transition and a History J unction on page 7 21 Example Labeled Default Transitions on page 7 23 Example Inner Transition to a History J unction on page 7 31 Inner Transitions An inne transition is a transition that does not exit the source state I nner transitions are most powerful when defined for superstates with XOR decomposition Use of inner transitions can greatly simplify a Stateflow diagram See the sections titled What Is an Inner Transition on page 6 27 and Example Inner Transi
308. struct Stated is active entry entA By during durA entry ma exit exitA during durB E_one C_one exit exitBQ C_two Ci C_three entry entC during durC exit exitCG Dy entry entDG during durDQ exit exitDQ Initially the Stateflow diagram is asleep Stated is active Event _one occurs and awakens the Stateflow diagram Condition C_t wo istrue Event _one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_one Thereis a valid transition segment from state A tothe connective junction The transition segments beginning from a twelve o clock position on the connective junction are evaluated for validity The first transition segment labeled with condition C_ one is not valid The next 7 33 7 Semantics 7 34 transition segment labeled with the condition C_t wo is valid The complete transition from state a tostatec is valid 2 State A executes and completes exit actions exit A 3 Stated is marked inactive 4 Statec is marked active 5 Statec executes and completes entry actions ent C 6 TheStateflow diagram goes back tosleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one Example Self Loop This example shows the semantics
309. t _one occurs awakening the Stateflow diagram Event E_one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 7 23 7 Semantics 7 24 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_ one Thereis a valid transition from state A to superstate B A pipe is used to represent that the transition is valid if event E_one or E_two occurs 2 Stated exit actions execute and complete exit A 3 Stated is marked inactive 4 StateB is marked active 5 StateB entry actions execute and complete ent B 6 StateB detects a valid default transition tostateB B1 The default transition is valid as a result of E_one 7 StateB B1 is marked active 8 StateB B1 entry actions execute and complete ent B1 9 TheStateflow diagram goes back tosleep waiting to be awakened by another event This sequence completes the execution of this Stateflow diagram associated with event E_one Inner Transitions Inner Transitions Example Processing One Event Within an Exclusive OR State This example shows the semantics of an inner transition JA_four Stated is A active entry entA 7A_two E_one C_one A_one during durAQ exit exit By entry entB during durB exit exitB E_two C_two A_three Initially the Stateflow diagram is asleep Stated is active Event E_one occurs and awakens the Stateflow diagram
310. t available in the manner appropriate to the source to make use of the right to access the data object If the external source is another machine then one machine defines an Imported data object and the other machine defines the same data object to be Exported Stateflow generates the appropriateimport and export data code for both machines Defining the Interface to External Sources This example shows the format required if the data is Imported from an external code source custom code EA sf_ev_d_inout_ex olx Eile Edit Simulation Format Tools Doo da Sine Wave Sine Wavei ext_data is defined as exported in the external code source ext_data added and defined as an Imported external code source data int ext_data void func_example voi d Stateflow generates this code 3 extern int ext_data 4 31 4 Defining Stateflow Interfaces 4 32 Exploring and Searching Overview Stateflow Explorer User Interface Example Getting Started Adding Events and Data Stateflow Finder User Interface Searching for a Wildcard String Searching for an Exact String Match Searching for All Objects of a Specified Object Type Searching Based on Multiple Conditions Searching for an Object to Edit Properties 5 2 5 16 5 20 5 26 5 28 5 30 5 32 5 34 5 Exploring and Searching Overview Ex ploring and Searching The Stateflow machine
311. t driven behavior to Simulink simulations Y ou create models that represent both data and control flow by combining Stateflow blocks with the standard Simulink and toolbox block libraries These combined models are simulated using Simulink Stateflow Debugger Use the Stateflow Debugger to debug and animate your Stateflow diagrams Each state in the Stateflow diagram simulation is evaluated for overall code coverage This coverage analysis is done automatically when the target is compiled and built with the debug options The Debugger can also be used to perform dynamic checking The Debugger operates on the Stateflow machine Stateflow Diagram Using Stateflow you create Stateflow diagrams A Stateflow diagram is also a graphical representation of a finite state machine where states and transitions form the basic building blocks of the system See the section titled Anatomy of a Model and M achine on page 1 8 for more information on Stateflow diagrams Stateflow Explorer Use the Explorer to add remove and modify data event and target objects See Stateflow Explorer User Interface on page 5 5 for more information Stateflow Finder Use the Finder to display a list of objects based on search criteria you specify You can directly access the properties dialog box of any object in the search output display by clicking on that object See Stateflow Finder User Interface on page 5 20 for more information Substate A
312. tC during durC exit exitC B entry entB during durB exit exitBG Initially the Stateflow diagram is asleep StateA is active Event E_ one occurs and awakens the Stateflow diagram Event E_one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_ one Thereis a valid transition segment from state A to the connective junction and from the junction to state C State A executes and completes exit actions exit A State A is marked inactive Statec is marked active State Cc executes and completes entry actions ent C The Stateflow diagram goes back to sleep waiting to be awakened by another event Connective Junctions This sequence completes the execution of this Stateflow diagram associated with event E_one Example Transitions from a Source to a Destination Based on a Common Event This example shows the semantics of transitions from multiple sources to a single destination based on the same event Al entry entAg during durAQ exit exitAQ CI entry entC during durC exit exitC Stated is active entry entB during durBQ exit exitBQ Initially the Stateflow diagram is asleep StateB is active Event _one occurs and awakens the Stateflow diagram Event E_ one is processed from the root of the Stateflow diagram
313. tate event broadcast condition action semantics ex ample 7 54 event broadcast state action semantics example 7 45 event broadcast transition action semantics ex ample 7 50 notation 6 11 parallelism definition 1 19 glossary definition A 8 parsing error messages 9 30 how to 9 11 tasks 9 12 prerequisites xxii Q quick start creating a Simulink model 1 23 creating a Stateflow diagram 1 26 debugging the Stateflow diagram 1 33 defining the Stateflow interface 1 30 generating code 1 35 overview 1 22 running a simulation 1 32 sample solution 1 22 Stateflow typical tasks 1 22 R Real Time Workshop glossary definition A 8 overview Xxv requirements for xxii references 1 7 regular expressions 5 21 rising edge triggered 3 18 rt w target compiling building 9 27 configuration dialog box 9 22 S searching based on multiple conditions example 5 32 Finder user interface 5 20 for a wildcard string example 5 26 for all objects of a specified object type example 5 30 for an exact string match example 5 28 for an object to edit properties example 5 34 self loop notation example 6 34 notation overview 6 31 semantics definition 1 7 execution order 7 62 glossary definition A 8 send keyword 6 6 notations example 6 59 semantics example 7 58 sfc cdr 9 5 sfexit 11 4 sfhelp 11 10 sfnew 11 3 1 11 Index 1 12 sfprint 11 9 sfsave 11 5 S function glossary definition A 8 shortcut menus general 2 12 junction 2 14 opt
314. tate in a superstate the system enters by default in the absence of any information History junctions override default transition paths in superstates with exclusive OR decomposition Creating Default Transitions Click on the Default transition button in the toolbar al and click on a location in the drawing area close to the state or junction you want to be the destination for the default transition Drag the mouse tothe destination object to attach the default transition The size of end point of the default transition is proportional to the arrowhead size Default transitions can be labeled just like other transitions See the section titled Labeling of Default Transitions on page 6 24 for an example Editing Transition Attach Points Placethecursor over an attach point until it changes toa small circle Click and drag the mouse to move the attach point release to drop the attach point You can edit both the source and destination attach points of a transition W orking with Transitions The appearance of the transition changes from a solid to a dashed line when editing a destination attach point Once you attach the transition toa destination the dashed line changes to a solid line The appearance of the transition changes to a default transition when editing a source attach point To delete a transition select it and choose Cut CtrI X from the Edit or any shortcut menu or press the Delete key Labeling Transitions
315. tateflow diagram that contains at least one state also has decomposition Representing hierarchy necessitates some rules around how states can be grouped in the hierarchy A superstate has either parallel AND or exclusive OR decomposition All substates at a particular level in the hierarchy must be of the same decomposition Parallel AND State Decomposition Parallel AND state decomposition is indicated when states have dashed borders This representation is appropriate if all states at that same level in the hierarchy are active at the same time The activity within parallel states is essentially independent Exclusive O R State Decomposition E xclusive OR state decomposition is represented by states with solid borders Exclusive OR decomposition is used to describe system modes that are mutually exclusive Only one state at the same level in the hierarchy can be active at a time Default Transition Default transitions are primarily used to specify which exclusive OR state is to be entered when there is ambiguity among two or more neighboring exclusive OR states For example default transitions specify which substate of a superstate with exclusive OR decomposition the system enters by default in the absence of any other information Default transitions are also used to specify that a junction should be entered by default A default transition is represented by selecting the default transition object from the toolbar and th
316. tates State 0n is initially active The transition 0n gt 0f f is valid when state 0n is active and the event Switch_off occurs Thetransition Of f gt 0n is valid when stateof f is active and event Swi tch_on occurs See the section titled Transitions to and from Exclusive OR States on page 7 8 for more information on the semantics of this notation Example Transitions to and from J unctions This example shows transitions to and from a connective junction s Orange Selection_made select 1 Cola 4 select 2 Rootbeer select 3 Lemon State Wai ti ng is initially active select 4 6 21 6 Notations 6 22 This is a Stateflow diagram of a soda machine The Stateflow diagram is called when the external event Sel ect i on_made occurs The Stateflow diagram awakens with the Wai ti ng state active The Wai ting state is a common source state When the event Sel ection_made occurs the Stateflow diagram transitions from the Wai t ing stateto one of the other states based on the value of the variable select One transition is drawn from the Wai ti ng state to the connective junction F our additional transitions are drawn from the connective junction to the four possible destination states See the section titled Example Transitions from a Common Source to Multiple Destinations on page 7 39 for more information on the semantics of this notation Example Transitions to a
317. te A A2 A2a iS marked inactive State A A2 A2b is marked active i StateA A2 A2b entry actions execute and complete ent A2b The State flow diagram activity now looks like this Af entry entA during durA exit exitAG entry entA1 1 entry entA2 during durA1 1 during durA2 on E_one E_two 11 exit exitA2 exit exitA1 StateAla i is active i Atal i RA vs entry entA2a pale gel i during durA2a uring dura taQ exit exitA2a exit exitAla i atbs 11 A2b i State A2b entry entA1b 11 entry entA2b is active 1 during durA1b 11 during durA2b l i exit exitA 1b 1 exit exitA2b 4 Theprocessing of E_one continues oncetheon event broadcast of E_t wo has been processed State A A1 checks for any valid transitions as a result of event E_one Thereisa valid transition from stateA Al Ala tostateA Al Alb 7 47 7 Semantics 7 48 5 StateA Al Ala executes and completes exit actions exit Ala 6 StateA Al Ala is marked inactive 7 State A A1 A1b executes and completes entry actions ent A1b 8 StateA Al Alb is marked active 9 Parallel stateA A2 is evaluated next StateA A2 during actions execute and complete dur A2 There are no valid transitions as a result of E_one 10 StateA A2 A42b now active as a result of the processing of theon event broad cast of E_t wo executes and completes during actions dur A2b
318. te contents Group Ungroup Toggles between grouping or ungrouping the selected superstate contents 2 13 2 Using the Graphics Editor Transition Shortcut Menu Move the cursor over a transition and click the right mouse button to display the Transition shortcut menu The Transition shortcut menu provides these transition specific options Menu Choice Description Font Size Arrowhead Size Changes the font size of all labels on any selected transitions using a virtual scrollbar Changes the arrowhead size on any selected transitions using a virtual scrollbar Changing one of the incoming arrowheads of an object causes all incoming arrowheads to that object to be adjusted to the same size Junction Shortcut Menu Click the right mouse button within a junction or on its border to display the J unction shortcut menu junction specific options TheJ unction shortcut menu provides these Menu Choice Description J unction Size Arrowhead Size History Connective Changes the junction size on any selected junctions using a virtual scrollbar Changes the arrowhead size on any selected junctions using a virtual scrollbar Changes any selected junction to a history junction Changes any selected junction to a connective junction Using the Graphics Editor Using the Graphics Editor Object Button Modes All object buttons state history junction default transition and con
319. ted a The broadcast of event E_one awakens state B This is a nested event broadcast Since state B is active the directed broadcast is received and stateB checks to see if there is a valid transition There is a valid transi tion fromB B1 toB B2 b StateB B1 executes and completes exit actions exit B1 c StateB B1 is marked inactive End of d StateB B2 is marked active event E_one processing 7 StateA A2 is marked active 8 Stated A2 entry actions execute and complete ent A2 This sequence completes the execution of this Stateflow diagram associated with an event broadcast and the directed event broadcast to a parallel state of event E_one 7 59 7 Semantics Example Directed Event Broadcasting Using Qualified Event Names This example shows the semantics of directed event broadcast using a qualified event name in a transition action State Al is active entry entA1 exit exitA1 A2 entry entA2 exit exitA 2 yi StateB1 is active entry entB1 exit exitB1 entry entB2 exit exitB2 Peis m Initially the Stateflow diagram is asleep Parallel substatesA A1 and B B1 are active By definition this implies parallel AN D superstates A and8 areactive An event occurs and awakens the Stateflow diagram The condition 7 60 Directed Event Broadcasting datal 1 is true The event is processed from the root of the Stateflow diagram dow
320. ted event broadcasting improves the efficiency of the generated code As is truein event broadcasting recursive event broadcasts can lead to definition of cyclic behavior The format of the directed broadcast is send event_ name state name whereevent_name is broadcast tost ate name and any offspring of that state in the hierarchy Thest at e_ name argument can includea full hierarchy path For example send event_name chart_name state namel state_name2 Thest at e_name specified must be active at the time thes end is executed for thestate_name to receive and potentially act on the directed event broadcast 6 58 Action Language Example Directed Event Broadcast Using send This is an example of a directed event broadcast using the send event name state name transition action as a transition action See E xample Directed Event Broadcasting Using Qualified E vent Names on page 7 60 for information on the semantics of this notation 6 59 6 N otations Example Directed Event Broadcast Using Qualified Event Names This example shows an alternate way to specify the same directed event broadcast as the previous example using a qualified event name B2 See Example Directed Event Broadcasting Using Qualified Event Names on page 7 60 for information on the semantics of this notation Action Language Conditions You sometimes want transitions or actions associated with transitions to tak
321. text link to bring the state to the foreground Parent Parent of this state the character indicates the Stateflow diagram is the parent read only click on this hypertext link to bring the parent to the foreground Debugger breakpoints Click on the checkboxes to set debugging breakpoints on stateentry during orexit actions Label The state s label See the section titled Labeling a State on page 6 13 for more information on valid label formats Description Textual description comment Document Link Enter a web URL address or a general MATLAB command Examples are www mathworks com mailto email address edit spec data speed txt Click on the Apply button to save the changes Click on the Revert button to cancel any changes and return to the previous settings Click on the Close button to save the changes and close the dialog box Click on the Help button to display the Stateflow online help in an HTML browser window 2 30 W orking with Transitions Working with Transitions What Can You Do with Transitions You can e Create delete Edit attach points Label Change font size Change arrowhead size Move labels Invoke the transition properties dialog box to Usethe hypertext link to transition s source destination or parent Specify debugger breakpoints Add or modify the label Add a description Link toa document Creating Deleting Transitions Placethe cursor at a straight portio
322. the Graphical Components figure the transition fromSt ateAl toStateA2 is labeled with the event transi tionAl_A2 that triggers the transition to occur 1 13 1 Introduction Consider again the automatic transmission system cl utch_ engaged is the event required to trigger the transition from neutral toengaged neutral Clutch_engaged engaged Events Events are nongraphical objects and are thus not represented directly in the Graphical Components figure Events drive the Stateflow diagram execution All events that affect the Stateflow diagram must be defined The occurrence of an event causes the status of the states in the Stateflow diagram to be evaluated The broadcast of an event can trigger a transition to occur or can trigger an action to be executed Events are broadcast in a top down manner starting from the event s parent in the hierarchy Events are created and modified using the Stateflow Explorer Events can be created at any level in the hierarchy Events have properties such as ascope Thescope defines whether the event is Local to the Stateflow diagram An input to the Stateflow diagram from its Simulink model An output from the Stateflow diagram to its Simulink model Exported to a code destination external to the Stateflow diagram and Simulink model I mported from a code source external to the Stateflow diagram and Simulink model Anatomy of a Model and Machine Data Data are nongraphical obje
323. this example the Simulink model titledsf intro example consists of a Simulink Sine Wave source block a Simulink Scope sink block and a single Stateflow block titled Example Simulink model title sf_intro_example File Edit Simulation Format Tools Stateflow block Stateflow diagram title See Defining the Stateflow Interface on page 1 30 and Chapter 4 Defining Stateflow Interfaces for more information Stateflow Diagram Objects This sample Stateflow diagram highlights some key graphical components The sections that follow describe these graphical components as well as some nongraphical objects and related concepts in greater detail 1 11 1 Introduction 1 12 Figure 1 1 Graphical Components History Connective junction Exclusive OR state junction Default transition decision point Transition StateA S a StateA2 Statea 1 H Sate StateAic AY transitionA1_A2 1 K condiiont fe StateA2b conditioni fune1 Aunc2 i i transitionA1a_Atb i i transitionA2_A1 47 Transition label Condition Condition Parallel AND state action Transition action States A state describes a mode of an event driven system The activity or inactivity of the states dynamically changes based on events and conditions Every state has a parent In a Stateflow diagram consisting of a single state that state s parent is the Stateflow diagram it
324. thods of having the chart awakened entered and executed Triggered l nherited This is the default update method Triggered The Stateflow block is explicitly triggered by a signal originating from a connected Simulink block The edge trigger can be set to Rising Falling Either or Function Call Inherited The Stateflow block inherits implicitly triggers from the Simulink model Theseimplicit events are the sample times discrete time or continuous of the Simulink signals providing inputs to the chart The sample times are determined by Simulink to be consistent with the rates of all the incoming signals Sampled Simulink will awaken sample the Stateflow block at the rate you specify An implicit event is generated by Simulink at regular time intervals corresponding to the specified rate The sample time is in the same units as the Simulink simulation time Note that other blocks in the Simulink model may have different sample times Continuous Simulink will awaken sample the Stateflow block at each step in the simulation as well as at intermediate time points that may be requested by the Simulink solver See Defining the Interface to External Sources on page 4 25 and Using Simulink for more information 2 22 W orking with Charts Stateflow Diagrams Printing Large Stateflow Diagrams To print complete Stateflow diagrams that are larger than the Stateflow graphics editor display area 1 Press the
325. tion Call Semantics 0000 eee 4 12 Defining Edge Triggered Output Events 4 13 Example Edge Triggered Semantics 00e eae 4 13 Event Inputs from Simulink 000055 4 16 Tasks to Define an Event Input from Simulink 4 16 Add an Event Choosing a Chart as the Parent 4 16 Choose Input from Simulink as the Scope 4 16 Select the Trigger siese ae eR ey ee ee we hee 4 17 Apply the Changes 0000 e eee eee 4 17 Data Inputs from Simulink 5 4 18 Tasks to Define a Data Input from Simulink 4 18 Add a Data Object Choosing a Chart as the Parent 4 18 Choose Input from Simulink as the Scope 4 18 Specify Data Attributes ec eee 4 19 Apply and Save the Changes 2 cee eee eee eee 4 19 Event Outputs to Simulink 4 20 Tasks to Define an Event Output to Simulink 4 20 Add an Event Choosing a Chart as the Parent 4 20 Choose Output to Simulink as the Scope 4 20 Apply the Changes 0 00 cece eee eens 4 21 Data Outputs to Simulink 005 4 22 Tasks to Define a Data Output to Simulink 4 22 Add a Data Object Choosing a Chart astheParent 4 22 Choose Output to Simulink as the Scope 4 22 Specify Data Attributes 0 ees 4 23 App
326. tion to a History J unction on page 7 31 for more information Machine The machineis the collection of all Stateflow blocks in the Simulink model Notation A notation defines a set of objects and the rules that govern the relationships between those objects Stateflow notation provides a common language to communicate the design information conveyed by a Stateflow diagram A 7 G lossary Stateflow notation consists of e A set of graphical objects e A set of nongraphical text based objects e Defined relationships between those objects Parallelism A system with paralldism can havetwoor morestates that can be active at the same time The activity of parallel states is essentially independent Parallelism is represented with a parallel AND state decomposition See the section titled What Is a State Decomposition on page 6 10 for more information Real Time Workshop The Real Time Workshop is an automatic C language code generator for Simulink It produces C code directly from Simulink block diagram models and automatically builds programs that can be run in real time in a variety of environments See the Real Time Workshop User s Guide for more information S function When using Simulink together with Stateflow for simulation Stateflow generates an S function ME X file for each Stateflow machine to support model simulation This generated code is a simulation target and is called the sfun target within
327. tive The history junction applies only to the level of the hierarchy in which it appears Example Use of History J unctions This example shows a use of history junctions Power_on C switch_high silicon switch_off High switch_low Superstate Power on has a history junction and contains two substates If statePower off is active and event swi tch_on occurs the system could enter either Power _on Low orPower_on Hi gh Thefirst time superstate Power on is entered substate Power on Low will be entered because it has a default transition At some point afterwards if statePower_on Hi gh is active and event switch_off occurs superstate Power _on is exited and state Power _ off becomes active Then event switch _on occurs SincePower_on Hi gh was the last active state it becomes active again After thefirst timeP ower on becomes active the choice between entering Power _on Low orPower_on Hi gh is determined by the history junction See the section titled Example Default Transition and a History J unction on page 7 21 for more information on the semantics of this notation H isto ry History Junctions and Inner Transitions By specifying an inner transition to a history junction you can specify that based on a specified event and or condition the active state is to be exited and then immediately re entered See the section titled Example Inner Transition to a History J unction on page 6 30 for an examp
328. to Simulink data object Output to Simulink data must be parented by the chart Output to Simulink data objects are passed using a port and connection to a Simulink block or another Stateflow block Data defined to be an Output to Simulink is also an interface to the Simulink model of which the Stateflow block is a part When you define a data object as an Output to Simulink the appropriate notation is automatically added tothe Stateflow block in the Simulink model Each data Output to Simulink is represented by a Simulink output port Multiple data outputs from the 3 28 Data Stateflow block to the Simulink model must be scalar they cannot be vectorized sf_ev_d_inout_ex File Edit Simulation Format Tools Sine Wave Output to Simulink Sine Weaver data Temporary Temporary data is non persistent Temporary data is accessible only by its parent Defining a loop counter to be Temporary is a good use of this Scope since the value is used only as a counter and the value does not need to persist The Temporary data remains defined and accessible only while the parent is executing For a state the Temporary data is defined when that stateis active and processing state actions For a chart the Temporary data is defined and accessible when the chart is active and processing condition and or transition 3 29 3 Events and Data actions This is an example Stateflow diagram of an Analogto Digital converter that uses Tempora
329. to display the list of percentages Click on the percentage to change the zoom factor to that per centage The default percentage is initially 100 and is subsequently calcu lated as the closest discrete value to the current zoom factor Double click on the Zoom Factor Selector or choose Fit to View from any shortcut menu to apply the maximum zoom that includes all selected objects If there is no selection list all objects are fit to the view Press the F key to apply the maximum zoom that includes all selected objects Press the spacebar to fit all objects tothe view If thereis no selection list all objects are fit to the view Use the Zoom virtual scrollbar to choose a zoom percentage from a sliding scale Click on the percentage value and drag the mouse vertically to usethe virtual scrollbar Dragging the mouse upward increases the zoom factor Dragging the mouse downward decreases the zoom factor Release the mouse button to make a zoom factor selection Alternatively right clicking and dragging on the percentage value resizes while you are dragging Scroll Bars Clicking on the arrows in the scroll bar adjusts your view of the drawing area to view objects that may be outside of the current drawing area Stateflow Diagram Stateflow Block Name Thenameof a new untitled Stateflow diagramisUnti tl ed The name appears in the upper left hand side of the main window Use the Save Model As menu item on the File menu to specify a St
330. tomizations 0 0c cece eee 9 20 Displaying the Target Configuration sfun Dialog Box 9 21 Displaying the Target Configuration rtw Dialog Box 9 22 Displaying the Target Configuration Dialog Box 9 23 Coder Command Customization 0020 ee eee 9 23 Make Command Customization 0020 ee eee 9 23 Enable Debugging Animation 2 0 eae 9 24 Enable Dynamic Checker Options 20005 9 24 Add Customized Code 2 0 20 e eee eee 9 25 Specify a Document Link 0 cee eee 9 25 Compiling Code Building Targets 9 26 Compile Build Options 0 00 0 c eee 9 26 Compiling Building a Simulation Target 9 27 Compiling Building Targets with RTW 0 9 27 Compiling Building Stand Alone Targets 9 28 Typical Code Generation Related Error Messages 9 30 OVERVICW oi eee a Sle A Le ees 9 30 Typical Parsing Error Messages ccc eee ees 9 30 Code Generation Error Messages 000 eee eaee 9 32 Compilation Error Messages 0 0c cece eee eee 9 32 xvii Debugging 10 Overview 0 teen tee eee 10 2 Debugging sasana naaa eaa 10 2 Stateflow Dynamic Checker 0 0c eee eee 10 2 Typical Debugging TaSkS 00 cee eee eee 10 3 Including Debugging in the Target Build 10 3 BreakpointS 00 cece ects 10 3 Runtime
331. trol the execution of other Simulink blocks in the model See Defining the Stateflow Block Update Method on page 4 4 for more information Determining Overall Input Trigger Type Each Stateflow block can only have one overall Trigger type If multiple input events are defined for a Stateflow block the following algorithm is applied to arrive at a single Trigger type for the Stateflow block e Function Call triggers take precedence over Edge trigger types If one of the Input from Simulink event s trigger type is Function Call then the State flow block Trigger type is set to Function Call See Combining Function Call and Edge Triggers on page 3 19 for an example of how to effectively model a combination of Function Call and Edge trigger types e If all events are Rising Edge trigger type then the Stateflow block Trigger type is set to Rising Edge e If all events are Falling Edge trigger type then the Statefl ow block Trigger type is set to Falling Edge e Otherwise the Stateflow block Trigger type is set to Either Edge Events The Trigger type must be consistent between the source and destination of Simulink blocks For example if a Stateflow block has a Function Call Trigger type and is connected toa Simulink triggered subsystem thetriggered subsystem must define function call triggering See Defining the Stateflow Block Update M ethod on page 4 4 for more information Combining Function Call and Edge Tr
332. try entAg during durAg exit exitAQ i entry entA1 during durA1 exit exitA1 Ala entry entA lat during dura 1a exit exitA1a E_one E_two Albi 1 entry entA 1b 1 during dur amp 1b exit exitA1b 11 entry entA2 1 during durA2 exit exitA2 A2al entry entA2a during durA2a exit exitA2a A2b entry entA2b during durA2b exit exitA2b State A2a is active See Example Event Broadcast Condition Action on page 7 54 to see the semantics of this example Condition Actions Example Cyclic Behavior to Avoid When Using Condition Actions This example shows a notation to avoid when using event broadcasts as condition actions because the semantics result in cyclic behavior Ont entry entOn during durOn exit exitOn E_one E_one E_one Off entry entOffg during durCff exit exitOffG State 0n is active Initially the Stateflow diagram is asleep StateOn is active EventE _one occurs and awakens the Stateflow diagram Event E_ one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_one A valid transition from state 0n to state Of f is detected A condition action broadcast of event E_ one is detected on the valid transition and is immediately e
333. ty Boosts These features of the graphics editor increase productivity by providing shortcut methods for performing common graphic editor tasks e Virtual scrollbars see Virtual Scrollbar on page 2 7 e Double click fit to view see Zooming Options on page 2 4 e F key and spacebar zooming operations see Zooming Options on page 2 4 e Shortcut menus see Shortcut Menus on page 2 10 e Escape key see Canceling Operations on page 2 15 e Multiple object mode see Object Button Modes on page 2 15 Virtual Scrollbar A virtual scrollbar enables you to set a value When you move the mouse over amenu item with a virtual scrollbar the cursor changes toa line with a double arrowhead Virtual scrollbars are either vertical or horizontal The direction is indicated by the positioning of the arrowheads Click on the menu item and drag the mouse either horizontally or vertically to change the value These menu items on the various shortcut menus see Shortcut Menus on page 2 10 have virtual scrollbars e Font Size e J unction Size e Arrowhead Size The Zoom Factor Selector also has a virtual scrollbar 2 Using the Graphics Editor Example Adjusting Font Size Font size is adjusted through the shortcut menus using a virtual scrollbar To adjust font size with the virtual scrollbar 1 Right click on the object s whose font you want to change to display the shortcut menu 2 Placethe cursor ove
334. u Cut Copy Paste Font Size Junction Size Arrowhead Size Exclusive OR Parallel AND Fit To View Select All Explore Debug Find Properties The General shortcut menu provides these additional general options Menu Choice Description Font Size J unction Size Arrowhead Size Exclusive OR Parallel AND Changes the font size of all labels on any selected objects using a virtual scrollbar Changes the junction size on any selected junctions using a virtual scrollbar Changes the arrowhead size on any selected destination object s using a virtual scrollbar Sets the parent decomposition on any selected states to be exclusive OR Sets the parent decomposition on any selected states to be parallel AND Shortcut M enus State Shortcut Menu Move the cursor over a state or its border and click the right mouse button to display the State shortcut menu The State shortcut menu provides these state specific options Menu Choice Description Font Size Changes the font size of all labels on any selected states using a virtual scrollbar Arrowhead Size Changes the arrowhead size on any selected states using a virtual scrollbar Exclusive OR Sets the parent decomposition on any selected states to be exclusive OR Parallel AND Sets the parent decomposition on any selected states to be parallel AND Show Hide Toggles between showing or hiding the selected supersta
335. uble click on the Stateflow block in the Simulink model window to invoke the graphics editor window Ed Stateflow On_off File Edit Simulation Style Tools Add Help E Ki Ready 2 Create states Click on the State button in the toolbar Click in the drawing area to place the statein the drawing area Position the cursor over that state click 1 26 Using Stateflow the right mouse button and drag to make a copy of the state Release the right mouse button to drop the state at that location Label states Click on the character within each stateto enter each state label Label the states with these titles Power _on andPower_of f Deselect the state to exit the edit Your Stateflow diagram should look similar to this sample Power_on Power_off Create transitions Draw a transition starting from Power _on and ending at Power _off Place the cursor at a straight portion of the border of thePower on state Click the border when the cursor changes toa crosshair Without releasing the mouse button drag the mouse toa straight portion on the border of the Power _ of f state When the transition snaps to the border of the Power off state 1 27 1 Introduction 1 28 release the mouse button The crosshair will not appear if you place the cursor on a corner since corners are used for resizing Draw another transition starting from Power_off and ending on Power _on Your Stateflow diagram should look simil
336. urA1 exit exitA1 entry entA lat during dura 1a exit exitA1a E_one E_two 1 Alb i entry entA1b i during durA amp 1b i exit exitA1b 11 entry entA2 1 during durA2 exit exitA2 A2al entry entA2a during durA2at exit exitA2a A2bi entry entA2b during durA2b exit exitA2b State A2a is active Initially the Stateflow diagram is asleep Parallel substates A Al Ala and A A2 A2a are active Event E_one occurs and awakens the Stateflow diagram Event E_ one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_ one Thereis no valid transition State A executes and completes during actions dur A State A s children are parallel AND states Parallel states are evaluated and executed from top to bottom In the case of a tie they are evaluated from Parallel AN D States left to right StateA A1 is evaluated first StateA A1l executes and completes during actions dur Al State A A1 checks for any valid transitions as a result of event E_ one There is a valid transition from stateA A1 Ala to state A A1 A1b Thereis alsoa valid condition action The condition action event broadcast of E_t wo is exe cuted and completed State A A1 A1a is still active a The broadcast of event E_t wo
337. urOffQ exit exitOff Again initially the Stateflow diagram is asleep State On is active Event _t wo occurs and awakens the Stateflow diagram Event E_t wo is processed from the Transitions to and from Exclusive O R States root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 The Stateflow diagram root checks to see if there is a valid transition as a result of E_t wo Thereis none 2 StateOn during actions execute and complete dur On 3 TheStateflow diagram goes back to sleep waiting to be awakened by another event This sequence completes the execution of the Stateflow diagram associated with event E_t wo when State 0n was active Example Transition from a Substate to a Substate This example shows the semantics of a transition from an OR substate to an OR substate Al Bi entry entA A2 entry entB during durA during durB B2 exit exitA exit exitBQ entry entA1 Bis during durA 10 E_one C_one A entry entB1 exit exit 1 during durB1 exit exitB1 State Al is active Initially the Stateflow diagram is asleep State A A1 is active Event E_one occurs and awakens the Stateflow diagram Condition C_one is true Event 7 11 7 Semantics 7 12 E_one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 8 9 The Stateflow diagram root c
338. ust after entering during function of Chart debug power Executing sf_debug_ex_debug_ power Current Event Input event Switch Debug the Simulation Execution At this point you can single step through the simulation and see whether the behavior is what you expect Click on the Step button and watch the Stateflow diagram animation and the Debugger status area to see the sequence of execution Single stepping shows that the desired behavior is not occurring The occurrence of the event input Swit ch is occurring faster than the data input Shift Thusthetransitions fromPower_on First toPower_on Second etcare not occurring The output display of code coverage also confirms this observation Debugging Runtime Errors Resolve Runtime Error and Repeat Choose Stop from the Simulation menu of the graphics editor The Stateflow diagram is now writeable The generation of event Swit ch is driving the simulation and the simulation time is passing too quickly for the input data object Shi f t tohavean effect The model may need to be completely rethought In the meantime there is a test that verifies the conclusion Modify the transition fromPower_on toPower_off toincludeacondition Thetransition is not to be taken until simulation time is greater than 10 0 Make this modification and click on the Go button to start the simulation again Repeat the debugging single stepping and observe the behavior Solution Stateflow Diagram This is the corr
339. ut port is added to the Stateflow block Output events from the Stateflow block to the Simulink model are scalar Apply the Changes Click on the Apply button to save the properties Click on the Close button to save the properties and close the dialog box 4 21 4 Defining Stateflow Interfaces 4 22 Data Outputs to Simulink Tasks to Define a Data Output to Simulink These tasks describe how to add and define the necessary fields for a data output to Simulink e Add a data object choosing a chart as the parent of the data e Choose Output to Simulink as the Scope e Specify data attributes e Apply and save the changes Add a Data Object Choosing a Chart as the Parent These steps describe how to add a data object 1 Choose Explore from the graphics editor Tools menu to invoke the Explorer 2 Select a chart object in the hierarchy that you want to be the data object s parent You must explicitly choose a parent to create a data object Choosing the Chart to be the parent determines that the data resides within the chart 3 Choose Data from the Explorer Add menu The Data properties dialog box is displayed 4 Enter anamein the Name field Choose Output to Simulink as the Scope Once you have chosen the chart as the parent the choice of valid scopes includes Local Input from Simulink or Output to Simulink Choose Output to Simulink as the Scope to enable access rights to Simulink and any offspring of the chart
340. x or implicitly via the Start menu item on the Simulation menu Coder File and Coder Function The coder file cdr is an ASCII template file that is used to generate target language code The cdr file implements a defined set of semantics for a particular notation 9 5 9 Generating Code Stateflow provides the coder file called sf c cdr to generate C language code Stateflow generates two target code files s f c mandsfc p that have the same name as the target Using the N otation Efficiently Using the Notation Efficiently Where to Find Information on Creating a Stateflow Diagram See Chapter 2 Using the Graphics Editor Chapter 6 Notations and Chapter 7 Semantics for information on creating Stateflow diagrams See Chapter 4 Defining Stateflow Interfaces for information on defining events and data objects Designing for Efficiency The Stateflow notation supports many different ways of representing desired system behavior The representation you choose directly affects the efficiency of the generated code You can use the notation to optimize for these code attributes e Speed e Code size e Memory use Optimizing for Speed If execution speed is the most important efficiency criterion for the generated code take advantage of the top down processing of events Designing the Stateflow diagram so that execution of speed critical actions occurs at the highest hierarchy level possible
341. xample Representing Transition Hierarchy 68 Example Representing Event Hierarchy 69 x Contents OVERVIEW 2 teed aed ata Lt er Le es 6 10 What Is a State Decomposition 0002 cea 6 10 Active and Inactive States 0 0 0 0 cece ees 6 11 What Are Combination States 0 0 cee eee 6 12 Labeling a State dioei eels ae kel aaa eek h Saah 6 13 Example Labeling a State 0 0 c cea eee 6 14 Example Unique State Names 0 000 ees 6 15 Transitions OE ee EE AEM 6 17 What Is a Transition 0 ee ees 6 17 Labeling a Transition 0 e eee ee eee 6 18 Example Transition Label 00000 eee eee 6 18 What Is a Valid Transition 0 0 c eee eee 6 19 Types of Transitions 0 0 c eee ees 6 20 Example Transitions to and from Exclusive OR States 621 Example Transitions to and from J unctions 6 21 Example Transitions to and from Exclusive OR Superstates 6 22 Example Transitions to and from Substates 6 23 What is a Default Transition saasaa cee eee 6 24 Labeling of Default Transitions 00 e eee 6 24 Example Use of Default Transitions 0000 6 25 Example Default Transition toaJ unction 6 26 Example Default Transition with a Label 6 26 What Is an Inner Transition asasan cee ees 6 27 Example
342. xecuted State 0n is still active a The broadcast of event E_one awakens the Stateflow diagram a second time The Stateflow diagram root checks to see if there is a valid transi tion as a result of E_one The transition from state 0n tostate Off is still valid The condition action broadcast of eventE_one is immediately exe cuted again 2 Step la continues to execute in a cyclical manner The transition label indi cating a trigger on the same event as the condition action broadcast event results in unrecoverable cyclic behavior This sequence never completes when event E_one is broadcast and state 0n is active 7 17 7 Semantics Default Transitions 7 18 Example Default Transition in an Exclusive OR Decomposition This example shows a transition from an OR state to a superstate with exclusive OR decomposition where a default transition to a substate is defined Bi entry entBG during durB exit exitBQ Stated is By active entry entA entry entB1 Q during durA E_one A during durB1 exit exitA B2 exit exitB1 i Default Transitions Initially the Stateflow diagram is asleep Stated is active Event _one occurs and awakens the Stateflow diagram Event E_ one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 8 9 The Stateflow diagram root checks to see if there is a valid transition asa result of E_one
343. xecutes and completes during actions dur A State A executes and completes theon event E_three action A_one State A checks its children for valid transitions There are no valid transi tions State Al executes and completes during actions dur A1 The Stateflow diagram goes back to sleep waiting to be awakened by another event 7 43 7 Semantics This sequence completes the execution of this Stateflow diagram associated with event E_three 7 44 Parallel AN D States Parallel AND States Example Event Broadcast State Action This example shows the semantics of event broadcast state actions StateAla is active Al entry entA during durA exit exit entry entAi during durA1 on E_one E_two exit exitA1 Ala entry entA lat during durA laf exit exitA 1a faib entry entA1b during durAib exit exitA1 bt 11 entry entA2 11 during durA2 1 exit exitA2 entry entA2a during durA2a exit exitA2a A2b entry entA2b during durA2b exit exitA2b State A2a is active Initially the Stateflow diagram is asleep Parallel substates A A1 Ala and A A2 A2a are active Event E_one occurs and awakens the Stateflow diagram 7 45 7 Semantics 7 46 Event E_ one is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram 1 TheStateflow diagram root checks to see if
344. yes yes Data yes yes yes Target yes no no Targets are parented exclusively by machines Although all other combinations are valid there are guidelines describing how Scope affects choice of parent and vice versa The default s f un simulation target is automatically defined for every machine If you have a Real Time Workshop license an RTW target is also automatically added e When you select Open RTW Target from the graphics editor Tools menu e f you build a target that includes a Stateflow machine using Real Time Workshop For convenience a hypertext link tothe parent of the currently selected object in the Object Hierarchy is included following the Contents of label Click on the hypertext link to bring that object to the forefront File Menu Select Close Ctrl W from the File menu to close the Explorer window Edit Menu Select Cut Ctri X from the Edit menu to delete the selected data event or target object in the Contents of pane Stateflow Explorer User Interface Add Menu The Add menu provides these options Menu Choice Description Event Ctrl Data Ctrl D Target Ctri T Creates a new event at the selected level in the object hierarchy displays an Event properties dialog box Creates a new data object at the selected level in the object hierarchy displays a Data properties dialog box Creates a new untitled standalone target at the selected machine level in the object hier
Download Pdf Manuals
Related Search
Related Contents
日本エコテック株式会社 日本エコテック株式会社 TEL.0800-100-1519 Série HI 149-00 - Hanna Instruments Canada XEM3010 User`s Manual 23 décembre 2004, sommaire du N°7 REUNION FU_SKL3VL_Sigma V Manuale Tecnico sintetico Tecumseh AKA9460ZXAXC Drawing Data Copyright © All rights reserved.
Failed to retrieve file