Stateflow Users Guide
Stateflow Users Guide
Users Guide
Version 4
Web Newsgroup Technical support Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information Phone Fax Mail
508-647-7000 508-647-7001 The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site. Stateflow Users Guide COPYRIGHT 1997 - 2001 by The MathWorks, Inc.
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 reproduced in any form without prior written consent from The MathWorks, Inc. FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by or for the federal government of the United States. By accepting delivery of the Program, the government hereby agrees that this software qualifies as "commercial" computer software within the meaning of FAR Part 12.212, DFARS Part 227.7202-1, DFARS Part 227.7202-3, DFARS Part 252.227-7013, and DFARS Part 252.227-7014. The terms and conditions of The MathWorks, Inc. Software License Agreement shall pertain to the governments use and disclosure of the Program and Documentation, and shall supersede any conflicting contractual terms or conditions. If this license fails to meet the governments minimum needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to MathWorks. MATLAB, Simulink, Stateflow, Handle Graphics, and Real-Time Workshop are registered trademarks, and Target Language Compiler is a trademark of The MathWorks, Inc. Other product or brand names are trademarks or registered trademarks of their respective holders.
Printing History: May 1997 January 1999 September 2000 June 2001 October 2001
First printing Revised for Stateflow 2.0 (Release 11) Revised for Stateflow 4.0 (Release 12) Revised for Stateflow 4.1 (Release 12.1) Revised for Stateflow 4.2 (Online only)
Contents
Preface
System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx Using Stateflow on a Laptop Computer . . . . . . . . . . . . . . . . . xxi Related Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii Using This Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiv Chapter Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiv Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi Installing Stateflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
Introduction
1
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is Stateflow? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Examples of Stateflow Applications . . . . . . . . . . . . . . . . . . . . . . Stateflow Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Design Approaches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-2 1-2 1-2 1-3 1-3
Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 The Power Switch Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Creating a Simulink Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6 Creating a Stateflow Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9 Defining Input Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12 Defining the Stateflow Interface . . . . . . . . . . . . . . . . . . . . . . . 1-13 Defining Simulink Parameters . . . . . . . . . . . . . . . . . . . . . . . . . 1-14 Parsing the Stateflow Diagram . . . . . . . . . . . . . . . . . . . . . . . . 1-15
2
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exploring a Real-World Stateflow Application . . . . . . . . . . Analysis and Physics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Control Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Running the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-2 2-2 2-2 2-2 2-3 2-3 2-3 2-4 2-4 2-6 2-8 2-19 2-19 2-22 2-25
Creating Charts
3
Creating a Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2 Using the Stateflow Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5 Displaying Context Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 Drawing Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6
ii
Contents
Specifying Colors and Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7 Selecting and Deselecting Objects . . . . . . . . . . . . . . . . . . . . . . . 3-10 Cutting and Pasting Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11 Copying Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11 Editing Object Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12 Exploring Objects in the Editor Window . . . . . . . . . . . . . . . . . 3-12 Zooming a Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13 Creating and Changing States . . . . . . . . . . . . . . . . . . . . . . . . . Moving and Resizing States . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Substates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Grouping States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specifying State Decomposition . . . . . . . . . . . . . . . . . . . . . . . . Specifying Activation Order for Parallel States . . . . . . . . . . . . Labeling States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the State Properties Dialog Box . . . . . . . . . . . . . . . . . . . Naming States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining State Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Outputting State Activity to Simulink . . . . . . . . . . . . . . . . . . .
3-15 3-15 3-16 3-16 3-16 3-17 3-17 3-18 3-19 3-19 3-21
Creating and Changing Boxes . . . . . . . . . . . . . . . . . . . . . . . . . 3-22 Creating and Changing Junctions . . . . . . . . . . . . . . . . . . . . . Changing Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Moving a Junction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Editing Junction Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating and Changing Transitions . . . . . . . . . . . . . . . . . . . . Creating Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Straight Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . Moving Transition Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting Smart Behavior in Transitions . . . . . . . . . . . . . . . . . . Labeling Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing Transition Arrowhead Size . . . . . . . . . . . . . . . . . . . . Changing Transition Properties . . . . . . . . . . . . . . . . . . . . . . . . Creating Self-Loop Transitions . . . . . . . . . . . . . . . . . . . . . . . . . Creating Default Transitions . . . . . . . . . . . . . . . . . . . . . . . . . .
3-23 3-23 3-24 3-24 3-26 3-26 3-26 3-27 3-28 3-29 3-30 3-31 3-32 3-33
iii
What Smart Transitions Do . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34 What Non-Smart Transitions Do . . . . . . . . . . . . . . . . . . . . . . . 3-40 Entering Chart Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Chart Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Editing Existing Chart Notes . . . . . . . . . . . . . . . . . . . . . . . . . . Changing Note Font and Color . . . . . . . . . . . . . . . . . . . . . . . . . Moving Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deleting Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-43 3-43 3-43 3-44 3-45 3-45
Specifying Chart Properties . . . . . . . . . . . . . . . . . . . . . . . . . . 3-46 Waking Up Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-49 Working with Graphical Functions . . . . . . . . . . . . . . . . . . . . Creating a Graphical Function . . . . . . . . . . . . . . . . . . . . . . . . . Invoking Graphical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . Exporting Graphical Functions . . . . . . . . . . . . . . . . . . . . . . . . . Specifying Graphical Function Properties . . . . . . . . . . . . . . . . Working with Subcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating a Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Manipulating Subcharts as Objects . . . . . . . . . . . . . . . . . . . . . Opening a Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Navigating Subcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Editing a Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Working with Supertransitions . . . . . . . . . . . . . . . . . . . . . . . . About Supertransitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Drawing a Supertransition . . . . . . . . . . . . . . . . . . . . . . . . . . . . Labeling Supertransitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-50 3-50 3-54 3-55 3-55 3-58 3-59 3-60 3-61 3-61 3-62 3-64 3-64 3-64 3-69
Creating Chart Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-70 Stateflow Printing Options . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-71 Printing the Current View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-71 Printing a Stateflow Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-72
iv
Contents
4
Defining Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 Adding Events to the Data Dictionary . . . . . . . . . . . . . . . . . . . . 4-2 Changing Event Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4 Event Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5 Naming Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 Defining Local Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 Defining Input Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 Defining Output Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8 Exporting Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9 Importing Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9 Specifying Trigger Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10 Describing Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11 Documenting Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11 Implicit Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11 Defining Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding Data to the Data Dictionary . . . . . . . . . . . . . . . . . . . . . Setting Data Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining Data Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining Input Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining Output Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Associating Ports with Data . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining Temporary Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exporting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Importing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Documenting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-14 4-14 4-15 4-17 4-21 4-23 4-23 4-24 4-24 4-25 4-25 4-26
5
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Interfaces to Stateflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Typical Tasks to Define Stateflow Interfaces . . . . . . . . . . . . . . . Where to Find More Information on Events and Data . . . . . . . Defining the Stateflow Block Update Method . . . . . . . . . . . . Stateflow Block Update Methods . . . . . . . . . . . . . . . . . . . . . . . . Defining a Triggered Stateflow Block . . . . . . . . . . . . . . . . . . . . . Defining a Sampled Stateflow Block . . . . . . . . . . . . . . . . . . . . . . Defining an Inherited Stateflow Block . . . . . . . . . . . . . . . . . . . . Defining a Continuous Stateflow Block . . . . . . . . . . . . . . . . . . .
5-2 5-2 5-2 5-3 5-4 5-4 5-5 5-5 5-6 5-7
Defining Output to Simulink Event Triggers . . . . . . . . . . . . 5-9 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9 Defining Function Call Output Events . . . . . . . . . . . . . . . . . . . . 5-9 Defining Edge-Triggered Output Events . . . . . . . . . . . . . . . . . 5-12 Inputting Events from Simulink . . . . . . . . . . . . . . . . . . . . . . . Add an Event Choosing a Chart as the Parent . . . . . . . . . . . . Choose Input from Simulink as the Scope . . . . . . . . . . . . . . . . Select the Trigger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Apply the Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inputting Data from Simulink . . . . . . . . . . . . . . . . . . . . . . . . . Add a Data Object Choosing a Chart as the Parent . . . . . . . . Choose Input from Simulink as the Scope . . . . . . . . . . . . . . . . Specify Data Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Apply and Save the Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . Outputting Events to Simulink . . . . . . . . . . . . . . . . . . . . . . . . Add an Event Parented by the Chart . . . . . . . . . . . . . . . . . . . . Choose Output to Simulink as the Scope . . . . . . . . . . . . . . . . . Apply the Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5-15 5-15 5-15 5-16 5-16 5-17 5-17 5-17 5-18 5-18 5-19 5-19 5-19 5-19
Outputting Data to Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20 Add a Data Object Parented by the Chart . . . . . . . . . . . . . . . . 5-20 Choose Output to Simulink as the Scope . . . . . . . . . . . . . . . . . 5-20
vi
Contents
Specify Data Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20 Apply the Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-21 MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22 What Is the MATLAB Workspace? . . . . . . . . . . . . . . . . . . . . . . 5-22 Using the MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . 5-22 Defining the Interface to External Sources . . . . . . . . . . . . . What Are External Sources? . . . . . . . . . . . . . . . . . . . . . . . . . . . Exported Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Imported Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exported Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Imported Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5-23 5-23 5-23 5-24 5-26 5-28
6
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2 Exploring Charts with Stateflow Explorer . . . . . . . . . . . . . . . Overview of Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Opening Stateflow Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . Explorer Main Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Object Icons in the Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . Objects and Properties in the Explorer Contents Pane . . . . . . . Targets in Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Explorer Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Searching (Only) in Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . Opening Stateflow Finder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Stateflow Finder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Finder Display Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Searching and Replacing in Charts . . . . . . . . . . . . . . . . . . . . Using Different Search Types . . . . . . . . . . . . . . . . . . . . . . . . . . Specify the Search Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the Search Button and View Area . . . . . . . . . . . . . . . . .
6-3 6-3 6-3 6-4 6-5 6-5 6-7 6-7 6-14 6-14 6-15 6-18 6-21 6-23 6-25 6-27
vii
Specifying the Replacement Text . . . . . . . . . . . . . . . . . . . . . . . Using the Replace Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . Search and Replace Messages . . . . . . . . . . . . . . . . . . . . . . . . . . The Search & Replace Tool Is a Product of Stateflow . . . . . . .
Notations
7
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is Meant by Notation? . . . . . . . . . . . . . . . . . . . . . . . . . . . . Motivation Behind the Notation . . . . . . . . . . . . . . . . . . . . . . . . . How Notation Is Checked . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Graphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How Hierarchy Is Represented . . . . . . . . . . . . . . . . . . . . . . . . . .
7-2 7-2 7-2 7-2 7-3 7-4 7-4
States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7 State Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7 Active and Inactive States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8 Combination States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9 Labeling a State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10 Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Labeling a Transition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Valid Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Types of Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Default Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Labeling Default Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . What Is an Inner Transition? . . . . . . . . . . . . . . . . . . . . . . . . . . What Is a Self-Loop Transition? . . . . . . . . . . . . . . . . . . . . . . . .
7-14 7-15 7-16 7-17 7-21 7-21 7-24 7-26
Connective Junctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-28 What Is a Connective Junction? . . . . . . . . . . . . . . . . . . . . . . . . 7-28 What Is Flow Diagram Notation? . . . . . . . . . . . . . . . . . . . . . . . 7-28 History Junctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-35
viii Contents
History Junctions and Inner Transitions . . . . . . . . . . . . . . . . . 7-35 Action Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is an Action Language? . . . . . . . . . . . . . . . . . . . . . . . . . . Objects with Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Transition Action Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . State Action Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Action Language Components . . . . . . . . . . . . . . . . . . . . . . . . . . Bit Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Unary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Unary Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Assignment Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Calling C Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . min and max Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Calling User-Written C Code Functions . . . . . . . . . . . . . . . . . . ml() Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Name Space Operator . . . . . . . . . . . . . . . . . . . . . . . . The ml() Function Versus ml Name Space Operator . . . . . . . . Data and Event Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pointer and Address Operators . . . . . . . . . . . . . . . . . . . . . . . . . Single and Double Precision Floating Point Numbers . . . . . . . Hexadecimal Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Typecast Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Event Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Directed Event Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Time Symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Continuation Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Use of the Semicolon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Temporal Logic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . After Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Before Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . At Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Every Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Temporal Logic Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7-37 7-37 7-37 7-37 7-40 7-41 7-42 7-43 7-44 7-46 7-46 7-47 7-47 7-48 7-48 7-51 7-54 7-56 7-56 7-56 7-57 7-58 7-58 7-59 7-59 7-61 7-63 7-64 7-64 7-65 7-65 7-65 7-65 7-66 7-68 7-69 7-70 7-71
ix
Semantics
8
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2 List of Semantic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2 Event-Driven Effects on Semantics . . . . . . . . . . . . . . . . . . . . . What Does Event-Driven Mean? . . . . . . . . . . . . . . . . . . . . . . . . . Top-Down Processing of Events . . . . . . . . . . . . . . . . . . . . . . . . . Semantics of Active and Inactive States . . . . . . . . . . . . . . . . . . . Semantics of State Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Semantics of Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-5 8-5 8-5 8-5 8-7 8-7
Transitions to and from Exclusive (OR) States . . . . . . . . . . . 8-8 Condition Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-13 Default Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-18 Inner Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-23 Connective Junctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-31 Event Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-42 Parallel (AND) States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-44 Directed Event Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . 8-56 Execution Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Execution Order Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . Parallel (AND) States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Semantic Rules Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Entering a Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Executing an Active Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . Entering a State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Executing an Active State . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-60 8-60 8-60 8-63 8-64 8-64 8-64 8-64 8-65
Contents
Exiting an Active State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-65 Executing a Set of Flow Graphs . . . . . . . . . . . . . . . . . . . . . . . . 8-65 Executing an Event Broadcast . . . . . . . . . . . . . . . . . . . . . . . . . 8-66
Building Targets
9
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Target Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Building a Target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How Stateflow Builds Targets . . . . . . . . . . . . . . . . . . . . . . . . . . .
9-2 9-2 9-2 9-3
Setting Up Target Build Tools . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5 Setting Up Build Tools on UNIX . . . . . . . . . . . . . . . . . . . . . . . . . 9-5 Setting Up Build Tools on Windows . . . . . . . . . . . . . . . . . . . . . . 9-5 Configuring a Target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7 Adding a Target to a State Machines Target List . . . . . . . . . . . 9-7 Starting the Target Builder Dialog . . . . . . . . . . . . . . . . . . . . . . . 9-9 Select a Build Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-10 Specifying Code Generation Options . . . . . . . . . . . . . . . . . . . . 9-11 Starting the Build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-14 Starting a Simulation Target Build . . . . . . . . . . . . . . . . . . . . . 9-14 Starting an RTW Target Build . . . . . . . . . . . . . . . . . . . . . . . . . 9-14 Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-16 Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-16 Parse the Machine or the Stateflow Diagram . . . . . . . . . . . . . 9-16 Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Parser Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Code Generation Error Messages . . . . . . . . . . . . . . . . . . . . . . . Compilation Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . .
9-20 9-20 9-21 9-21
xi
Code Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-22 Make Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-24 Integrating Custom and Generated Code . . . . . . . . . . . . . . . 9-25 Specifying Custom Code Options . . . . . . . . . . . . . . . . . . . . . . . 9-25 Invoking Graphical Functions from Custom Code . . . . . . . . . . 9-29
10
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Typical Debugging Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Including Checking in the Target Build . . . . . . . . . . . . . . . . . . Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Run-Time Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Stateflow Debugger User Interface . . . . . . . . . . . . . . . . . . . . Debugger Main Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Status Display Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Breakpoint Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugger Action Control Buttons . . . . . . . . . . . . . . . . . . . . . . . Animation Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Display Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Command Field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debugging Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . Example Stateflow Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . Typical Scenario to Debug Run-Time Errors . . . . . . . . . . . . . Create the Model and Stateflow Diagram . . . . . . . . . . . . . . . Define the sfun Target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Invoke the Debugger and Choose Debugging Options . . . . . . Start the Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Debug the Simulation Execution . . . . . . . . . . . . . . . . . . . . . . Resolve Run-Time Error and Repeat . . . . . . . . . . . . . . . . . . . Solution Stateflow Diagram . . . . . . . . . . . . . . . . . . . . . . . . . .
10-2 10-2 10-2 10-3 10-4 10-5 10-5 10-6 10-7 10-7 10-8 10-8 10-9 10-10 10-10 10-11 10-11 10-12 10-12 10-12 10-12 10-13 10-13
xii
Contents
Causes of State Inconsistency . . . . . . . . . . . . . . . . . . . . . . . . . 10-14 Detecting State Inconsistency . . . . . . . . . . . . . . . . . . . . . . . . . 10-14 Debugging Conflicting Transitions . . . . . . . . . . . . . . . . . . . 10-16 Detecting Conflicting Transitions . . . . . . . . . . . . . . . . . . . . . . 10-16 Debugging Data Range Violations . . . . . . . . . . . . . . . . . . . . 10-18 Detecting Data Range Violations . . . . . . . . . . . . . . . . . . . . . . 10-18 Debugging Cyclic Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . 10-19 Detecting Cyclic Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-19 Stateflow Chart Model Coverage . . . . . . . . . . . . . . . . . . . . . Specifying Coverage Report Settings . . . . . . . . . . . . . . . . . . . Decision Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Condition Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MCDC Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Coverage Reports for Stateflow Charts . . . . . . . . . . . . . . . . .
10-22 10-22 10-23 10-26 10-26 10-27
11
Overview of the Stateflow API . . . . . . . . . . . . . . . . . . . . . . . . Stateflow API Object Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . Object Properties and Methods . . . . . . . . . . . . . . . . . . . . . . . . . API References to Properties and Methods . . . . . . . . . . . . . . .
11-2 11-2 11-3 11-4
Quick Start with the Stateflow API . . . . . . . . . . . . . . . . . . . . 11-5 Create a New Model and Chart . . . . . . . . . . . . . . . . . . . . . . . . . 11-5 Access the Root Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-5 Access the Machine Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-6 Access the Chart Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-6 Open the Stateflow Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-7 Create New Objects in the Chart . . . . . . . . . . . . . . . . . . . . . . . 11-7 Save the New Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-11 Create a MATLAB Script of API Commands . . . . . . . . . . . . . 11-11
xiii
Naming and Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Naming Conventions for Properties and Methods . . . . . . . . . Using Dot Notation with Properties and Methods . . . . . . . . . Calling Methods with Function Notation . . . . . . . . . . . . . . . . Displaying Properties and Methods . . . . . . . . . . . . . . . . . . . Displaying the Names of Properties and Methods . . . . . . . . . Displaying Property Subproperties . . . . . . . . . . . . . . . . . . . . . Displaying Enumerated Values for Properties . . . . . . . . . . . . Creating, Connecting to, and Destroying Objects . . . . . . Creating and Connecting to Stateflow Objects . . . . . . . . . . . . Connecting to Editor and Clipboard Objects . . . . . . . . . . . . . Establishing Object Containment . . . . . . . . . . . . . . . . . . . . . . Destroying Stateflow Objects . . . . . . . . . . . . . . . . . . . . . . . . . Accessing Existing Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the find Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Special find Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Getting and Setting the Properties of Objects . . . . . . . . . . . . Copying Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Clipboard Object and Methods . . . . . . . . . . . . . . . . . . . . . . . . copy Method Features and Limitations . . . . . . . . . . . . . . . . . Copying by Grouping (Recommended) . . . . . . . . . . . . . . . . . . Copying Objects Individually . . . . . . . . . . . . . . . . . . . . . . . . . Copying Data, Event, and Target Objects . . . . . . . . . . . . . . .
11-13 11-13 11-13 11-14 11-15 11-15 11-16 11-16 11-18 11-18 11-19 11-19 11-20 11-21 11-21 11-22 11-23 11-24 11-24 11-24 11-25 11-26 11-27
xiv Contents
A
API Reference by Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2 Reference Table Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4 Structural Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-6 Structural Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-13 Behavioral Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-14 Behavioral Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-20 Deployment Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-21 Deployment Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-25 Utility and Convenience Properties . . . . . . . . . . . . . . . . . . . . . A-26 Utility and Convenience Methods . . . . . . . . . . . . . . . . . . . . . . . A-28 Graphical Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-30 Graphical Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-36
B
API Reference by Object Type . . . . . . . . . . . . . . . . . . . . . . . . . . B-2 Reference Table Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-3 Global Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-4 Methods that Apply to All Objects . . . . . . . . . . . . . . . . . . . . . . . B-5 Editor Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-6 Editor Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-7 Clipboard Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-8 Root Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-9 Machine Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-10 Machine Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-13 Chart Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-14 Chart Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-19 State Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-20 State Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-23 Box Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-24 Box Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-26
xv
Function Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Function Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Note Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Note Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Transition Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Transition Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Junction Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Junction Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Data Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Event Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Event Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Target Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Target Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
B-27 B-29 B-30 B-32 B-33 B-36 B-37 B-38 B-39 B-43 B-44 B-46 B-47 B-50
C
API Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C-2 Method Reference Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C-4 build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--5 classhandle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--6 copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--7 defaultTransitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--8 delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--9 dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--10 find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--11 findDeep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--14 findShallow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--15 generate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--16 get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--17 getCodeFlag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--18 help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--19 innerTransitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--20 make . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--21 methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C--22
xvi Contents
outerTransitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . outputData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . parse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pasteTo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rebuildAll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . regenerateAll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . setCodeFlag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sfclipboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sfexit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sfhelp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sfnew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sfprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sfroot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sfsave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sourcedTransitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . stateflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . zoomIn and zoomOut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
C--23 C--24 C--26 C--27 C--28 C--29 C--30 C--31 C--33 C--34 C--35 C--36 C--37 C--39 C--40 C--41 C--42 C--44 C--45 C--46
Regular Expressions
D
Regular Expression Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . Metacharacters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Quantifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
D-3 D-3 D-4 D-5
xvii
Obsolete Features
E
Error on Transition Action into Junction with Following Condition Action E-3
Glossary
xviii Contents
Preface
System Requirements . . . . . . . . . . . . . . . . xvi Using Stateflow on a Laptop Computer . . . . . . . . xvii Related Products . . . . . . . . . . . . . . . . . . xviii Using This Guide . . . . . . . . . . . . . . . . . . . xx Chapter Quick Reference . . . . . . . . . . . . . . . . xx Typographical Conventions . . . . . . . . . . . . . xxi Installing Stateflow . . . . . . . . . . . . . . . . . xxii
Preface
System Requirements
Stateflow is a multiplatform product, running on Microsoft Windows 95, Windows 98, Windows NT, and UNIX systems. Stateflow 4.1 requires: MATLAB 6.1 (Release12.1) Simulink 4.1 The UNIX version of Stateflow requires a C or C++ compiler for generating code from a Stateflow model. See Setting Up Target Build Tools on page 9-5 for more information. Generating code for the Simulink elements of a Stateflow model requires Version 4.1 (Release 12.1) of the Real-Time Workshop .
MATLAB Simulink
Stateflow
Real-Time Workshop
Stateflow Coder
iv
menu.
2 Select Properties from the desktop menu to display the Windows Display
Properties dialog.
3 Select the Settings panel on the Display Properties dialog. 4 Choose a setting that is more than 256 colors from the Color Palette colors
list.
5 Select OK to apply the new setting and dismiss the Display Properties
dialog.
Preface
Related Products
The MathWorks provides several products that are especially relevant to the kinds of tasks you can perform with Stateflow. For more information about any of these products, see either: The online documentation for that product if it is installed or if you are reading the documentation from the CD The MathWorks Web site, at http://www.mathworks.com; see the products section The Stateflow Web site, at www.stateflow.com
Note The toolboxes listed below all include functions that extend MATLABs capabilities. The blocksets all include blocks that extend Simulinks capabilities.
Product
Description
MATLAB
Integrated technical computing environment that combines numeric computation, advanced graphics and visualization, and a high-level programming language Tool that generates customizable C code from Simulink models and automatically builds programs that can run in real time in a variety of environments Interactive, graphical environment for modeling, simulating, and prototyping dynamic systems
Real-Time Workshop
Simulink
vi
Related Products
Product
Description
Tool for documenting information in Simulink and Stateflow in multiple output formats Tool for generating highly readable, efficient C code from Stateflow diagrams
vii
Preface
viii
See Appendix D, Regular Expressions, for a list of regular expression metacharacters supported in Stateflows Search & Replace tool. See Appendix E, Obsolete Features, for a list of obsoleted features from previous versions of Stateflows and suggested modifications/workarounds. See the Appendix F, Glossary, for definitions of key terms and concepts.
ix
Preface
Typographical Conventions
This manual uses some or all of these conventions.
Item Convention Used Monospace font Example
Example code
Function names/syntax
Monospace font
The cos function finds the cosine of each array element. Syntax line example is
MLGetVar ML_var_name
Keys Literal strings (in syntax descriptions in reference chapters) Mathematical expressions
Italics for variables Standard text font for functions, operators, and constants
Monospace font
MATLAB output
Menu titles, menu items, dialog boxes, and controls New terms Omitted input arguments
Italics (...) ellipsis denotes all of the input/output arguments from preceding syntaxes.
Monospace italics
sysc = d2c(sysd,'method')
Installing Stateflow
Installing Stateflow
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 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. Stateflow and Stateflow Coder have certain product prerequisites that must be met for proper installation and execution.
Licensed Product Prerequisite Products Additional Information
If you experience installation difficulties and have Web access, connect to the MathWorks home page (http://www.mathworks.com). Look for the license manager and installation information under the Tech Notes/FAQ link under Tech Support Info.
xi
Preface
xii
1
Introduction
Overview . . . . . . . . . . What Is Stateflow? . . . . . . . Examples of Stateflow Applications Stateflow Components . . . . . Design Approaches . . . . . . . Quick Start . . . . . . . . The Power Switch Model . . . Creating a Simulink Model . . Creating a Stateflow Diagram . Defining Input Events . . . . Defining the Stateflow Interface Defining Simulink Parameters . Parsing the Stateflow Diagram . Running a Simulation . . . . . Generating Code . . . . . . . Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 1-2 1-2 1-3 1-3
. 1-5 . 1-5 . 1-6 . 1-9 . 1-12 . 1-13 . 1-14 . 1-15 . 1-15 . 1-16 . 1-18
Introduction
Overview
What Is Stateflow?
Stateflow is a powerful graphical design and development tool for complex control and supervisory logic problems. Using Stateflow you can: Visually model and simulate complex reactive systems based on finite state machine theory. Design and develop deterministic, supervisory control systems. Easily modify your design, evaluate the results, and verify the system's behavior at any stage of your design. Automatically generate integer or floating-point code directly from your design (requires Stateflow Coder). Take advantage of the integration with the MATLAB and Simulink environments to model, simulate, and analyze your system. Stateflow allows you to use flow diagram notation and state transition notation seamlessly in the same Stateflow diagram. 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 systems logic and avoids the use of unnecessary states. Flow diagram notation is an effective way to represent common code structures like for loops and if-then-else 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.
1-2
Overview
- Commercial (computer peripherals, appliances, etc.) - Programmable logic controllers (PLCs) (process control) - Industrial (machinery) Man-machine interface (MMI) - Graphical user interface (GUI) Hybrid systems - Air traffic control systems (digital signal processing (DSP) + Control + MMI)
Stateflow Components
Stateflow consists of these primary components: Stateflow graphics editor (see Chapter 3, Creating Charts) Stateflow Explorer (see Chapter 6, Exploring and Searching Charts) Stateflow simulation code generator (see Chapter 9, Building Targets) Stateflow Debugger (see Chapter 10, Debugging and Testing) Stateflow Coder is a separately available product and generates code for nonsimulation targets. (See Chapter 9, Building Targets for information relevant to Stateflow Coder.) Stateflow Dynamic Checker supports run-time checking for conditions such as cyclic behavior and data range violations. The Dynamic Checker is currently available if you have a Stateflow license.
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 subsystems and event detection).
1-3
Introduction
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 from a Simulink (algorithmic) perspective and then later add Stateflow diagrams. You may have an 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 is a 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 the sfun target within Stateflow. Stateflow Coder generates integer or floating-point code based on the Stateflow machine. Real-Time Workshop 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 Real-Time Workshop. You may want to design a solution that targets code generated from both products for a specific platform. This generated code is specifically a Real-Time Workshop target and within Stateflow is called the RTW target. Using Stateflow and Stateflow Coder you can generate code exclusively for the Stateflow machine portion of the Simulink model. This generated code is for stand-alone (nonsimulation) targets. You uniquely name this target within Stateflow. In summary, the primary design approach options are: Use Stateflow together with Simulink for simulation. Use Stateflow, Stateflow Coder, Simulink, and Real-Time Workshop to generate target code for the complete model. Use Stateflow and Stateflow Coder to generate target code for a machine.
1-4
Quick Start
Quick Start
This section provides you with a quick introduction to using Stateflow. In this section, you will use Stateflow to create, run, and debug a model of a simple power switch.
1-5
Introduction
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.
At the MATLAB prompt enter stateflow. MATLAB displays the Stateflow block library.
1-6
Quick Start
The library contains an untitled Stateflow block icon, an Examples block, and a manual switch. Stateflow also displays an untitled Simulink model window with an untitled 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.
1-7
Introduction
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-8
Quick Start
Double-click on the Stateflow block in the Simulink model window to invoke the graphics editor window.
2 Create states.
Click on the State button in the toolbar. Click in the drawing area to place the state in the drawing area. Position the cursor over that state, click 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.
1-9
Introduction
3 Label states.
Click on the ? character within each state to enter each state label. Label the states with the titles Power_on and Power_off. Deselect the state to exit the edit. To deselect a state, click anywhere outside the state or press the Esc key. Your Stateflow diagram should look similar to this sample.
4 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 the Power_on state. Click the border when the cursor changes to a crosshair. Without releasing the mouse button, drag the mouse to a straight portion on the border of the Power_off state. When the transition snaps to the border of the Power_off state, release the mouse button. (The crosshair will not appear if you place the cursor on a corner, since corners are used for resizing.)
1-10
Quick Start
Draw another transition starting from Power_off and ending on Power_on. Your Stateflow diagram should look similar to this sample.
Click on the transition from Power_on to Power_off to select it. Click on the ? alongside the transition and enter the label Switch. Press the Escape key to deselect the transition label and exit the edit. Label the transition from Power_off to Power_on with the same text, Switch. Your Stateflow diagram should look similar to this sample.
Click and release the mouse on the Default Transition button in the toolbar. Drag the mouse to a straight portion on the border of the Power_off state. Click and release the mouse when the arrowhead snaps to the border of the Power_off state. Your Stateflow diagram should look similar to this sample.
1-11
Introduction
Explorer.
2 Double-click on the machine name (same as the Simulink model name) in
1-12
Quick Start
it to the Sine Wave block output as well. Your model should look similar to this.
1-13
Introduction
Click on the OK button to apply the changes and close the dialog box.
2 Choose Parameters from the Simulation menu of the Simulink model
window and edit the values to match the values in this dialog box.
1-14
Quick Start
Running a Simulation
These steps show how to run a simulation:
1 Ensure that the Stateflow diagram and the Scope block are open.
Double-click on the On_off 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.
Click on the OK button to apply the change. Close the Simulation Coder Options and the Simulation Target Builder dialog boxes.
5 Select Debug from the graphics editor Tools menu. Ensure that the
Enabled radio button under Animation is checked to enable Stateflow diagram animation. Click on the Close button to apply the change and close the window.
1-15
Introduction
simulation of the model. By default the S-function is the simulation target for any Stateflow blocks. Stateflow displays code generation status messages in the MATLAB command window. Before starting the simulation, Stateflow temporarily sets the model to read-only to prevent accidental modification while the simulation is running. The input from the Sine block is defined as the Input from Simulink event Switch. When the simulation starts the Stateflow diagram is animated reflecting the state changes triggered by the input sine wave. Each input event of Switch toggles the model between the Power_off and Power_on state.
7 Choose Stop from the graphics editor Simulation menu to stop a
simulation. Once the simulation stops, Stateflow resets the model to writable.
ote Running a simulation may require setting up the tools used to build Stateflow targets. See Setting Up Target Build Tools on page 9-5 for more information.
Generating Code
When you simulate a Simulink model containing Stateflow charts (like you did in the previous section), Stateflow generates a Simulink S-function (sfun) target that enables Simulink to simulate the Stateflow blocks. The sfun target can be used only with Simulink. Before generating code, Stateflow creates a directory called sfprj in the current MATLAB directory if the directory does not already exist. Stateflow uses the sfprj directory during code generation to store generated files. See the section Generated Files on page 922.
1-16
Quick Start
Note Do not confuse the sfprj directory created in the MATLAB current directory for generated files with the sfprj directory in the directory containing the model file (see the section Saving the Model on page 1-19). The latter sfprj directory is used for storing information on the model while the former stores generated files. However, if the MATLAB current directory is set equal to the model directory, the same sfprj directory (under the model directory) is used to store both model information and generated files.
If you have the Stateflow Coder, you can generate stand-alone code suitable for a particular processor. See Building a Target on page 9-2 for more information on code generation.
1-17
Introduction
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 Breakpoints: Chart Entry check box to specify you want the
messages related to the S-function code generation for Stateflow blocks are displayed in the MATLAB command window. When the target is built, the graphics editor becomes read-only (frozen) and the Debugger window will be updated and look similar to this.
4 Click on the Step button to proceed one step at a time through the
1-18
Quick Start
Where the simulation is stopped What is executing The current event The simulation time The current code coverage percentage 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
1-19
Introduction
Note Do not confuse the sfprj directory in the directory containing the model file with the sfprj directory created in the MATLAB current directory. The latter is used for generated files such as generated code. While the former is used to save model information. However, if the MATLAB current directory is set equal to the model directory, the same sfprj directory (under the model directory) is used to store both model information and generated files.
1-20
2
How Stateflow Works
Finite State Machine Concepts What Is a Finite State Machine? . FSM Representations . . . . . . Stateflow Representations . . . . Notations . . . . . . . . . . . Semantics . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 2-2 2-2 2-2 2-3 2-3 2-3 2-4 2-4 2-6 2-8
Anatomy of a Model and Machine . . . The Simulink Model and Stateflow Machine Defining Stateflow Interfaces . . . . . . . Stateflow Diagram Objects . . . . . . . .
Exploring a Real-World Stateflow Application Analysis and Physics . . . . . . . . . . . . . Control Logic . . . . . . . . . . . . . . . . Running the Model . . . . . . . . . . . . . .
FSM Representations
Traditionally, designers used truth tables to represent relationships among the inputs, outputs, and states of an FSM. 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 transitions among states. The state that is active is determined based on the 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. You 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
2-2
specify the destination state of a transition based on historical information. 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 communicate the design information conveyed by a Stateflow diagram. Stateflow notation consists of: A set of graphical objects A set of nongraphical text-based objects Defined relationships between those objects See Chapter 7, 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 8, Semantics.
References
For more information on finite state machine theory, consult these sources: [1] Harel, David, Statecharts: A Visual Formalism 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.
2-3
2-4
2-5
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 machine, the chart (Stateflow diagram), or by a state. Targets can only be parented by the machine. Once a parent is chosen, that object is known in the hierarchy from the parent downwards (including the parents offspring). For 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.
2-6
See Defining Input Events on page 4-7 and Chapter 5, Defining Stateflow Interfaces, for more information.
2-7
Transition label
Condition
Condition action
Transition action
2-8
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 states parent is the Stateflow diagram itself (also called the Stateflow diagram root). You can place states within other higher-level states. In the Graphical Objects Diagram on page 8, StateA1 is a child in the hierarchy to StateA. A state also has history. History provides an efficient means of basing future activity on past activity. States have labels that can specify actions executed in a sequence based upon action type. The action types are entry, during, exit, and on. 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 and engaged.
Stateflow provides two types of states: parallel (AND) and exclusive (OR) states. You represent parallelism with AND (parallel) states. The transmission 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 the engaged state at any one time.
2-9
Transitions
A transition is a graphical object that, in most cases, links one object to another. One end of a transition is attached to a source object and the other end to a destination object. The source is 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 Graphical Objects Diagram on page 8, the transition from StateA1 to StateA2 is labeled with the event transitionA1_A2 that triggers the transition to occur. Consider again the automatic transmission system. clutch_engaged is the event required to trigger the transition from neutral to engaged.
Events
Events drive the Stateflow diagram execution but are nongraphical objects and are thus not represented directly in a Stateflow chart. 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 events 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 a scope. The scope defines whether the event is: Local to the Stateflow diagram
2-10
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 Imported from a code source external to the Stateflow diagram and Simulink model
Data
Data objects are used to store numerical values for reference in the Stateflow diagram. They are nongraphical objects and are thus not represented directly in a Stateflow chart. Data objects are created and modified using the Stateflow Explorer. Data objects can be created at any level in the hierarchy. Data objects have properties such as a scope. The scope defines whether the data object 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 Nonpersistent temporary data Defined in the MATLAB workspace A constant Exported to a (code) destination external to the Stateflow diagram and Simulink model Imported from a code source external to the 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 both charts and states. Charts can exist within charts. A chart that exists in another chart is known as a subchart. Similarly, states can exist within other states. Stateflow represents state hierarchy with superstates and substates. For example, this Stateflow diagram has a superstate that contains two substates.
2-11
The engaged superstate contains the first and second substates. The engaged superstate is the parent in the hierarchy to the states first and second. When the event clutch_engaged occurs, the system transitions out of the neutral state to the engaged superstate. Transitions within the engaged 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, [condition1] represents a Boolean expression that must be true for the transition to occur. In the automatic transmission system, the transition from first to second occurs if the Boolean condition [speed > threshold] is true.
2-12
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, the transition to the 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 transitions. In the component summary Stateflow diagram, the history junction in StateA1 indicates that when a transition to StateA1 occurs, the substate that becomes active (StateA1a, StateA1b, or StateA1c) 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 from neutral to the engaged superstate, the substate that becomes active, either first or second, is based on which of those substates was most recently active.
2-13
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 Graphical Objects Diagram on page 8, the transition segment from StateA1b to the connective junction is labeled with a condition action (func1()) and the transition segment from the connective junction to StateA1c is labeled with a transition action (func2()). The semantics of how and why actions take place are discussed throughout the examples in Chapter 8, Semantics.. Transitions ending in a state can have condition actions and transition actions, as shown in the example below.
Transition action
Condition action
2-14
States can have entry, during, exit, and on event_name actions. For example,
The action language defines the types of actions you can specify and their associated notations. An action can be a 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 7-37.
Parallelism
A system with parallelism has two or 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 Objects Diagram on page 8, StateA2a and StateA2b are parallel (AND) states. StateA2 has parallel (AND) state decomposition. For example, this Stateflow diagram has parallel superstate decomposition.
2-15
The transmission, 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 wiper 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 there is ambiguity between two or more exclusive (OR) states at the same level in the hierarchy. For example, in Graphical Objects Diagram on page 8, the default transition to StateA1 resolves the ambiguity that exists with regard to whether StateA1 or StateA2 should be active when State A becomes active. In this case, when StateA is active, by default StateA1 is also active. In the following Lights subsystem, the default transition to the Lights.Off substate indicates that when the Lights superstate becomes active, the Off substate becomes active by default.
2-16
Default transition
Note History junctions override default transition paths in superstates with exclusive (OR) decomposition.
Note In parallel (AND) states, a default transition must always be present to indicate which of its exclusive (OR) states is active when the parallel state becomes active.
Connective Junctions
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. Connective junctions provide alternative ways to represent desired system behavior. In the Graphical Objects Diagram on page 8, the connective junction is used as a decision point for two transition segments that complete at StateA1c.
2-17
The following example shows how connective junctions (displayed as small circles) are used to represent the flow of an if code structure.
2-18
2-19
The fuel rate controller uses signals from the systems sensors to determine the fuel rate which gives a stoichiometric mixture. The fuel rate combines with the actual air flow in the engine gas dynamics model to determine the resulting mixture ratio as sensed at the exhaust. The user can selectively disable each of the four sensors (throttle angle, speed, EGO and manifold absolute pressure [MAP]), to simulate failures. Simulink accomplishes this with Manual Switch blocks. The user can toggle the position of a switch by double-clicking its icon prior to, or during, a simulation. Similarly, the user can induce the failure condition of a high engine speed by toggling the switch on the far left. A Repeating Table block provides the throttle angle input and periodically repeats the sequence of data specified in the mask The controller uses the sensor input and feedback signals to adjust the fuel rate to give a stoichiometric ratio. The model uses four subsystems to implement this strategy: control logic, sensor correction, airflow calculation, and fuel calculation. Under normal operation, the model estimates the airflow rate and
2-20
multiplies the estimate by the reciprocal of the desired ratio to give the fuel rate. Feedback from the oxygen sensor provides a closed-loop adjustment of the rate estimation in order to maintain the ideal mixture ratio.
A detailed explanation of the algorithmic (Simulink) part of the fault tolerant control system is given in Using Simulink and Stateflow in Automotive Applications, a Simulink-Stateflow Technical Examples booklet published by The MathWorks. This section concentrates on the supervisory logic part of the system that is implemented in Stateflow, but the following points are crucial to the interaction between Simulink and Stateflow: The supervisory logic monitors the readings from the sensors as data inputs into Stateflow. The logic determines from these readings which sensors have failed and outputs a failure state Boolean array as fail_state. Given the current failure state, the logic determines in which fueling mode the engine should be run.
2-21
The fueling mode can be either a: Low emissions mode, the normal mode of operation where no sensors have failed Rich mixture mode, used when a sensor has failed to ensure smooth running of the engine Shutdown mode, where more than one sensor has failed rendering the engine inoperable The fueling mode and failure state are output from the Stateflow as fuel_mode and fail_state respectively into the algorithmic part of the model where they determine the fueling calculations.
Control Logic
The single Stateflow chart that implements the entire control logic is shown below.
2-22
The chart consists of six parallel states (denoted by dash-dotted boundaries) that represent concurrent modes of operation. The four parallel states at the top of the diagram correspond to the four individual sensors. Each state has submodes or substates that represent the status of that particular sensor, i.e., whether it has failed or not. These substates are mutually exclusiveif the throttle sensor has failed, then it is in the throt_fail state. Transitions determine how states can change and can be guarded by conditions. For example, the throt_norm state can change to the throt_fail state when the measurement from the throttle sensor exceeds max_throt or is below min_throt.
2-23
The remaining two parallel states at the bottom consider the status of the four sensors simultaneously and determine the overall system operating mode. The Sens_Failure_Counter superstate acts as a store for the resultant number of sensor failures. This state is polled by the Fueling_Mode state that determines the fueling mode of the engine. If a single sensor fails, operation continues but the air/fuel mixture is richer to allow smoother running at the cost of higher emissions. If more than one sensor has failed, the engine shuts down as a safety measure, since the air/fuel ratio cannot be controlled reliably. Although it is possible to run Stateflow charts asynchronously by injecting events from Simulink when required, the fueling control logic is polled synchronously at a rate of 100 Hz. Consequently, the sensors are checked every 1/100 second to see if they have changed status and the fueling mode adjusted accordingly.
2-24
After a given time period, defined by o2_t_thresh, the sensor is deemed to have reached operating temperature and the system settles into the normal mode of operation, shown above, in which the fueling mode is set to NORMAL. As the simulation progresses, the chart is woken up synchronously every 0.01 second. The events and conditions that guard the transitions are evaluated and if a transition is valid, it is taken. The transition itself can be seen animated on the Stateflow diagram. To illustrate this, we can provoke a transition by switching one of the sensors to a failure value on the top level Simulink model. The system detects throttle
2-25
and pressure sensor failures when their measured values fall outside their nominal ranges. A manifold vacuum in the absence of a speed signal is deemed to indicate a speed sensor failure. The oxygen sensor also has a nominal range for failure conditions but, because zero is both the minimum signal level and the bottom of the range, failure can be detected only when it exceeds the upper limit. Switching the Simulink switch for the manifold air pressure sensor causes a value of zero to be read by the fuel rate controller. When the chart is next woken up, the transition from the press_norm state becomes valid as the reading is now out of bounds and the transition is taken to the press_fail state as shown below.
2-26
also
Regardless of which sensor fails, the model always generates the directed event broadcast Sens_Failure_Counter.INC. (thus making the triggering of the universal sensor failure logic independent of the sensor). This event causes a second transition from FL0 to FL1 to be taken in the Sens_Failure_Counter superstate. Note that both transitions can be seen animated on the Stateflow diagram above. With the Sens_Failure_Counter state showing one failure, the condition that guards the transition from the Low_Emissions.Normal state to the Rich_Mixture.Single_Failure state is now valid and is therefore taken. As
2-27
the Fuel_Disabled state is entered, the, output fuel_mode is set to RICH, as shown below.
A second sensor failure causes the Sens_Failure_Counter to enter the Multifail state, broadcasting an implicit event that immediately triggers the transition from the Running state to the Shutdown state. On entering the Fuel_Disabled superstate the fueling_mode is DISABLED.
2-28
You may decide that when the oxygen sensor is warming up, changing the warmup fueling mode to a rich mixture would be beneficial. In the Stateflow chart this can easily be achieved by changing the parent of the Warmup state to the Rich_Mixture state.
2-29
Once made, the alteration is obvious to all who need to inspect or maintain the code. The results of changing the algorithm can be seen in the graphs of air/fuel mixture ratio for the first few seconds of engine operation after startup.
The left graph shows the air fuel ratio for the unaltered system whereas the right graph for the altered system shows how the air/fuel ratio stays low in the warming up phase indicating a rich mixture.
2-30
3
Creating Charts
Creating a Chart . . . . . . . . . . . . . . . . . . 3-2 Using the Stateflow Editor . . . . . . . . . . . . . 3-5
Creating and Changing States . . . . . . . . . . . . 3-15 Creating and Changing Boxes . . . . . . . . . . . . 3-22 Creating and Changing Junctions . . . . . . . . . . 3-23 Creating and Changing Transitions Using Smart Transitions . . . . . . . . . 3-26
. . . . . . . . . . . . . . 3-34
Entering Chart Notes . . . . . . . . . . . . . . . . 3-43 Specifying Chart Properties . . . . . . . . . . . . . 3-46 Waking Up Charts . . . . . . . . . . . . . . . . . 3-49 . . . . . . . . . 3-50
. . . . . . . . . . . . . . 3-58 . . . . . . . . . . . 3-63
Creating Charts
Creating a Chart
To create a Stateflow chart:
1 Create a new model with an empty chart block or copy an empty chart from
the Stateflow block library into your model. To create a new model with an empty chart, enter sfnew or stateflow at the MATLAB command prompt. The first command creates a new model.
Chart block
3-2
Creating a Chart
The second command also displays the Stateflow block library in case you want to create multiple charts in your model.
For information on creating your own chart libraries, see Creating Chart Libraries on page 3-70.
2 Open the chart by double-clicking on the chart block.
3-3
Creating Charts
3 Use the Stateflow editor to draw and connect states representing the desired
state machine or a component of the desired state machine. See Using the Stateflow Editor on page 3-5 for more information.
4 Specify a wake up method for the chart.
events and data. See Chapter 4, Defining Events and Data and Chapter 5, Defining Stateflow Interfaces for more information.
6 Rename and save the model chart by selecting Save Model As from the
3-4
Object palette
Status bar
The editor window includes the following elements: Title bar Full chart name appears here in <model name>/<chart name> format. The * character appears on the end of the chart name for a newly created chart or for an existing chart that has been edited but not saved yet. Menu bar Most editor commands are available from the menu bar. Toolbar Contains buttons for cut, copy, paste, and other commonly used editor commands. The toolbar also contains buttons for navigating a charts subchart hierarchy (see Navigating Subcharts on page 3-61).
3-5
Creating Charts
Object palette Displays a set of tools for drawing states, transitions, and other state chart objects. See Drawing Objects on page 3-6 for more information. Drawing area Displays an editable copy of a state diagram. Zoom control See Exploring Objects in the Editor Window on page 3-12 for information on using the zoom control. Shortcut menus These menus pop up from the drawing area when you press the right mouse button. They display commands that apply only to the currently selected object or to the chart as a whole, if no object is selected. See Displaying Context Menu for more information. Status bar Displays tooltips and status information.
Drawing Objects
A state diagram comprises seven types of objects: states, boxes, functions, transitions, default transitions, history junctions, and connective junctions. Stateflow provides tools for creating instances of each of these types of objects. The Transition tool, used to draw transitions, is available by default. You select and deselect the other tools by clicking their icons in the Stateflow editors object palette.
3-6
State Tool History Junction Tool Default Transition Tool Connective Junction Tool
In general, you can draw a chart object by first selecting one of the tools and then click-dragging on the chart area to form the object. This rule has two exceptions: Junctions require only a single click to place them at the cursors position. Transitions do not require the pre-selection of a drawing tool. For detailed information on creating Statechart objects, see the following topics: Creating and Changing States on page 3-15 Creating and Changing Boxes on page 3-22 Creating a Graphical Function on page 3-50 Creating and Changing Transitions on page 3-26 Creating and Changing Junctions on page 3-23 Entering Chart Notes on page 3-43
3-7
Creating Charts
2 From the resulting submenu, select Font Size > <size of font>.
You can also specify the label font size of a particular object:
1 Left-click an individual text item in the editor. 2 From the editors Edit menu select Set Font Size. 3 From the resulting submenu, select the font size.
The drawing area of the dialog displays examples of the types of objects whose colors and font labels you can specify. The examples use the colors and label fonts specified by the current color scheme for the chart. To choose another color scheme, select the scheme from the dialogs Schemes menu. The dialog displays the selected color scheme. Choose Apply to apply the selected scheme to the chart or Ok to apply the scheme and dismiss the dialog.
3-8
To make the selected scheme the default scheme for all Stateflow charts, select Make this the Default scheme from the dialogs Options menu. To modify the current scheme, position the cursor over the example of the type of object whose color or label font you want to change. Then click the left mouse button to change the objects color or the right mouse button to change the objects font. If you click the left mouse button, Stateflow displays a color chooser dialog.
Use the dialog to select a new color for the selected object type. If the selected object is a label and you click the right mouse button, Stateflow displays a font selection dialog.
3-9
Creating Charts
Use the font selector to choose a new font for the selected label. To save changes to the default color scheme, select Save defaults to disk from the Colors & Fonts dialogs Options menu.
Note Choosing Save defaults to disk has no effect if the modified scheme is not the default scheme.
3-10
on the selection list. This is useful to select objects within a state without selecting the state itself. 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 Esc key deselects all selected objects. Pressing the Esc key again displays the parent of the current chart.
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.
3-11
Creating Charts
Alternatively, to copy from one Stateflow diagram to another, choose the Copy and then Paste menu items from either: The Edit menu on the Stateflow graphics editor window 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.
Stateflow changes the font size of all labels on all selected states to the selected size.
3-12
To view events and data defined by a transition or junctions parent state, select Explore from the transition or junctions context menu.
Zooming a Diagram
You can magnify or shrink a diagram, using the following zoom controls: Zoom Factor Selector. Selects a zoom factor (see Using the Zoom Factor Selector). Zoom In button. Zooms in by the current zoom factor. You can also press the R key to increase the zoom factor. Zoom Out button. Zooms out by the current zoom factor. You can also press the V key to decrease the zoom factor.
3-13
Creating Charts
F space bar R V
Highlight (select) an object and press F to fit it to view. Set to full view of diagram. Increase zoom factor. Decrease zoom factor.
3-14
State Tool
To activate the State tool, click or double-click on the State button in the Stateflow toolbar. Single-clicking on the button puts the State tool in single-creation mode. In this mode, you create a state by clicking the tool in the drawing area. Stateflow creates the state at the specified location and returns to edit mode. Double-clicking on the State button puts the State tool in multiple-creation mode. This mode works the same way as single-creation mode except that the State tool remains active after you create a state. You can thus create as many states as you like in this mode without having to reactivate the State tool. To return to edit mode, click on the State button, or right click in the drawing area, or press the Esc key. To delete a state, select it and choose Cut (Ctrl+X) from the Edit or any shortcut menu or press the Delete key.
3-15
Creating Charts
a double-ended arrow (PC only; cursor appearance will vary on other platforms).
Creating Substates
A substate is a state that can be active only when another state, called its parent, is active. States that have substates are known as superstates. To create a substate, click the State tool and drag a new state into the state you want to be the superstate. Stateflow creates the substate in the specified parent state. You can nest states in this way to any depth. To change a substates parentage, drag it from its current parent in the state diagram and drop it in its new parent.
Note A parent state must be large enough to accommodate all its substates. You may therefore need to resize a parent state before dragging a new substate into it.
Grouping States
Grouping a state causes Stateflow to treat the state and its contents as a graphical unit. This simplifies editing a state diagram. For example, moving a grouped state moves all its substates as well. To group a state, double-click on it or its border or select Grouped from the Make Contents submenu on the state or box shortcut menu. Stateflow thickens the states border and grays its contents to indicate that it is grouped. To ungroup a state, double-click it or its border or select Ungrouped from the Make Contents submenu units shortcut menu. You need to ungroup a superstate to select objects within the superstate.
3-16
You can also specify the state decomposition of a chart. In this case, Stateflow treats the charts top-level states as substates of the chart. Stateflow creates states with exclusive decomposition. To specify a charts decomposition, deselect any selected objects, press the right mouse button to display the charts shortcut menu, and choose either Parallel (AND) or Exclusive (OR) from the menu. The appearance of a superstates substates indicates the superstates decomposition. Exclusive substates have solid borders, parallel substates, dashed borders. A parallel substate also contains a number in its upper right corner. The number indicates the activation order of the substate relative to its sibling substates.
Note Stateflow displays the activation order of a parallel state in its upper right corner.
Labeling States
Every state has a label. A states label specifies its name and actions that a state machine takes when entering or exiting the state or while the state is active. Initially, a states label is empty. Stateflow indicates this by displaying a ? in the states label position (upper left corner). Click on the label or display the states properties dialog (see Using the State Properties Dialog Box on page 3-18) to add to or change its contents. For more information on labeling states, see the following topics: Naming States on page 3-19
3-17
Creating Charts
Stateflow diagram name; read-only; click on this hypertext link to bring the state to the foreground. Check this box to cause Stateflow to output the activity status of this state to Simulink via a data output port on the chart block containing the state. See Outputting State Activity to Simulink on page 3-21 for more information. Parent of this state; a / character indicates the Stateflow diagram is the parent; read-only; click on this hypertext link to bring the parent to the foreground.
Parent
3-18
Field
Description
Debugger breakpoints
Click on the check boxes to set debugging breakpoints on state entry, during, or exit actions. See Chapter 10, Debugging and Testing for more information. The states label. See the section titled Labeling States on page 3-17 for more information. Textual description/comment. Enter a URL address or a general MATLAB command. Examples are: www.mathworks.com, mailto:email_address, edit /spec/data/ speed.txt.
Click on the dialog 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.
Naming States
Naming a state allows a state machine to reference the state. To name a state, enter the states name in the first line of the states label. Names are case-sensitive. To avoid naming conflicts, do not assign the same name to sibling states. However, you can assign the same name to states that do not share the same parent.
3-19
Creating Charts
entry or en, followed by a colon, followed by one or more action statements on one or more lines. You must separate statements on the same line by a comma or semicolon. See Action Language on page 7-37 for information on writing action statements.
Note You can also begin a states entry action on the same line as the states name. In this case, begin the entry action with a forward slash (/) instead of the entry keyword.
A state machine can respond to multiple events, with either the same or different actions, when a state is active. If you want more than one type of
3-20
event to trigger the same action, specify the keyword as on events, where events is a comma-separated list of the events that trigger the actions, for example,
on ev1, ev2: exit();
If you want different events to trigger different actions, enter multiple event blocks in the states label, each specifying the action for a particular event or set of events, for example,
on ev1: action1(); on ev2: action2(); on ev3, ev4: exit();
Note Use a during block to specify actions that you want a state machine to take in response to any visible event that occurs while the machine is in a particular state (see Defining During Actions on page 3-20).
Note If a chart has multiple states with the same name, only one of those states can output activity data. If you check the Output State Activity property for more than one state with the same name, Stateflow outputs data only from the first state whose Output State Activity property you specified.
3-21
Creating Charts
Stateflow converts the state to a box, redrawing its border with sharp corners to indicate its changed status. Once you create a box you can move or draw objects inside of it. You could also draw the box first as a state around the objects you want inside of it and then convert it to a box. Like states, you can group (and ungroup) a box and its contents into a single graphical element or you can hide or show them. See Grouping States on page 3-16 and Working with Subcharts on page 3-58 for more information. For the most part, boxes do not contribute to the semantics of a state machine. They do, however, affect the activation order of a diagrams parallel states. A box wakes up before any parallel states or boxes that are lower or to the right of it in a Stateflow diagram. Within a box, parallel states still wake up in top down, right-to-left order.
3-22
Connective junction
One use of a connective junction is 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. 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 be active.
History junction
Changing Size
To adjust the junction size from the Junction shortcut menu:
1 Select the junction(s) whose size you want to change. The size of any selected
junctions is adjusted.
2 Place the cursor over a selected junction, click the right mouse button to dis-
play the shortcut menu and place the cursor over Junction Size. A menu of junction sizes appears.
3 Select a junction size from the menu.
3-23
Creating Charts
Moving a Junction
To move a junction, select, drag, and release it in a new position.
3-24
Parent
Parent of this state; read-only; click on the hypertext link to bring the parent to the foreground. Textual description/comment. Enter a URL address or a general MATLAB command. Examples are www.mathworks.com, mailto:email_address, and edit/spec/data/ speed.txt.
Click on the Apply button to save the changes. Click on the Cancel button to cancel any changes since the last apply. Click on the OK 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.
3-25
Creating Charts
destination state or junction. Notice that the source of the transition sticks to the initial source point for the transition. Attached transitions obey the following roles: Transitions will not attach to the corners of states. Corners are used exclusively for resizing. Transitions exit a source and enter a destination at perpendicular angles to the source or destination surface. Newly created transitions have smart behavior. See the section Setting Smart Behavior in Transitions on page 3-28. To delete a transition, select it and choose Ctrl+X or Cut from the Edit menu, or select the Delete key. See the following sections for help with creating self-loop and default transitions: Creating Self-Loop Transitions on page 3-32 Creating Default Transitions on page 3-33
3-26
Press the S key (works on all platforms). Right-click the mouse (works on most platforms). Either of these actions straightens the transition perpendicular to the transitions source state or junction surface, if possible, and allows the transition source point to slide to maintain straightness. For states, if the cursor is out of range of perpendicularity with the source state, the transition is unaffected.
location. Only the transition line moves. The arrow and attachment points do not move.
3 Release the mouse button to specify the transition point location.
The final result is a bowed transition line. Repeat the steps above to move the transition back into its original shape or into another shape.
3-27
Creating Charts
The appearance of the transition changes from a solid to a dashed line when you detach and release a destination attach point. Once you attach the transition to a destination, the dashed line changes to a solid line. The appearance of the transition changes to a default transition when you detach and release a source attach point. Once you attach the transition to a source, the appearance returns to normal.
If you mistakenly click and then immediately release the left mouse button on the label, you will be in edit mode for the label. Press the Esc key to deselect the label and try again. You can also click the mouse on an empty location in the diagram editor to deselect the label.
3-28
1 Right-click on a transition.
On the resulting popup observe the selection entitled Smart. If a check mark appears in front of Smart, the transition has smart behavior.
2 If Smart is not checked, select Smart to enable smart behavior.
Labeling Transitions
Valid transition labels are defined by the following: Can have any alphanumeric and special character combination, with the exception of embedded spaces Cannot have a beginning numeric character Can have any length Can have carriage returns in most cases Must have an ellipsis (...) to continue on the next line 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
3-29
Creating Charts
Specify, as appropriate, relevant names for event, condition, condition_action, and transition_action. Transitions do not have to have labels. You can specify some, all, or none of the parts of the label.
Label Field event condition Description
Event that causes the transition to be evaluated. Defines what, if anything, has to be true for the condition action and transition to take place. If the condition is true, the action specified executes and completes. This action executes after the source state for the transition is exited but before the destination state is entered.
condition_action
transition_action
To apply and exit the edit, deselect the object. See these sections in Chapter 7, Notations for more information: Transitions on page 7-14 Action Language on page 7-37
3-30
play the shortcut menu. Place the cursor over Arrowhead Size. A menu of arrowhead sizes appears
3 Select a size from the menu.
3-31
Creating Charts
Source
Source of the transition; read-only; click on the hypertext link to bring the transition source to the foreground. Destination of the transition; read-only; click on the hypertext link to bring the transition destination to the foreground. Parent of this state; read-only; click on the hypertext link to bring the parent to the foreground. Click on the check boxes to set debugging breakpoints either when the transition is tested for validity or when it is valid. The transitions label. See the section titled Labeling a Transition on page 7-15 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, and edit/spec/data/speed.txt.
Destination
Parent
Debugger breakpoints
Label
Click on the Apply button to save the changes. Click on the OK button to save the changes and close the dialog box. Click on the Cancel button to close the dialog without applying any changes made since the last time you clicked the Apply button. Click on the Help button to display the Stateflow online help in an HTML browser window.
3-32
self-loop transitions
or junction.
2 Continue dragging the transition tip back to a location on the source state or
junction. For the semantics of self-loops, see the section What Is a Self-Loop Transition? on page 7-26.
3-33
Creating Charts
Note Transitions with smart behavior differ graphically only. Apart from graphical behavior, there is do difference between a transition with and without smart behavior.
3-34
transition turns to a very light shade of gray, a sure sign of smart behavior. Dragging direction is shown by the arrows.
1 2 3
Note the following figure by figure behavior for the above example:
1 The first capture shows state A and B at the beginning of movement. 2 As B moves upward, the transitions back end slides upward on A
a hop around As upper right-hand corner. In order to do this, the transition is now curved from As top surface to Bs left side maintaining perpendicularity with each attached state side. Note A hop around a states corner is a necessary since transitions are restricted from attaching there.
4 As B moves on top of A, the transition stays curved but its front end slides
3-35
Creating Charts
5 As B continues to move to the left over A, the transitions front end hops
bottom edge. As B continues to circle A, the procedure, steps 1 through 6, repeats for each of As remaining sides.
In the following example, the ends of a pair of transitions with smart behavior emanate from a junction and terminate in a state. As the junction is dragged around the state, the ends slide around the state and maintain the same relative spacing between each other. Direction is indicated by the arrow.
1 2 3
3-36
1 The junction starts with two straight smart transition connections to states
A and B.
2 Stateflow chooses to connect the junction to state A through its left side.
Since the junction is below A, only a curved connection is possible. State B could be connected by a straight line through the junctions left side, but this is already occupied by the connection to A. Therefore, B is connected through the junctions bottom, which must be curved.
3-37
Creating Charts
junctions top connection. No straight line connection to A is possible, therefore the junction is connected to state A with a curved transition through its left side.
4 At this location (under A, to the left of B), straight line transitions to A and
B are possible from the junctions top and right connection points, respectively.
5 At the location left of state A, Stateflow chooses to connect to state B through
its right connection point. Since the junction is above B, only a curved connection is possible.
6 Above A a straight line transition to state A is possible through the
junctions bottom connector. A straight line connection to state B is not possible so the junction is connected to state B through a curved transition from its right connection
Here, the invisible grid is depicted for each of the three junctions by dashed vertical and horizontal lines. Each junction is connected to each other through nonlinear smart transitions:
3-38
1 In the first scene, the snap grid for each junction does not overlap. The arrow
indicates that junction A is being moved towards the vertical snap line for junction B.
2 When A gets within a very small distance of Bs snap line, A snaps into
position directly above B and centered in its vertical snap line. The arrow indicates that A is now being moved towards the horizontal snap line for junction C.
3 When A gets within a very small distance of Cs horizontal snap line, A snaps
into position directly to the side of C and centered in its horizontal snap line.
Bow Symmetrically
Transitions with smart behavior bow symmetrically between junctions. In the following examples, transitions with smart behavior are drawn between two junctions:
1 2 3
1 In the first case, a transition is originated at the junction on the left and
terminated on the left-hand side of the right junction. This results in a straight line.
2 In the second case, a transition is originated at the junction on the left and
terminated on the top of the right junction. This results in a transition line bowed up.
3 In the third case, a transition is originated at the junction on the left and
terminated on the right-hand side of the right junction. This results in transition line bowed up even more.
3-39
Creating Charts
Bowed smart transitions maintain symmetry by maintaining equality between transition entry and exit angles as shown below.
You can bow a smart transition between two junctions to any degree by placing the mouse cursor on any point in the transition (except the attachment points) and click-dragging with the left mouse button in a direction perpendicular to a straight line connecting the two junctions. You can move the mouse in any direction to bow the transition but Stateflow only uses the component perpendicular to the line connecting the two junctions. Disabling smart behavior for a transition allows you to distort the transition asymmetrically (see section Distort Asymmetrically on page 3-41). However, if you enable smart behavior again, the transition automatically returns to its prior symmetric bowed shape.
3-40
A static transition connects state A to state B. The mouse cursor is then placed over state B and left-click dragged to new locations counter-clockwise around A. When this occurs, state B turns to its highlight color but the transition remains unchanged, a sure sign of a static transition. As B is moved around A, the transition changes into a distorted curve which seeks to maintain the original attachment points. These remain unchanged in position although the angle of attachment is always perpendicular to the side of the state.
Distort Asymmetrically
Simply by click-dragging on different locations along a transition without smart behavior, you can re-shape it into an asymmetric curve suited to your individual preferences. You can do this as follows: For the example below, the following procedure was taken:
1 Drag a horizontal transition between two junctions.
3-41
Creating Charts
2 Disable smart behavior. 3 Place the mouse cursor on any point on the transition. 4 Click-drag the mouse cursor up and to the left.
3-42
Note Chart notes are descriptive only. They do not contribute in any way to the behavior or code generation of a chart.
A blinking cursor appears at the location you selected. Default text is italic, 9 point.
4 Begin typing your comments.
text.
3-43
Creating Charts
TeX Format
In the above procedure, note a third selection called TeX Format. This selection sets the text Interpreter property to Tex, which allows you to use a subset of TeX commands embedded in the string to produce special characters such as Greek letters and mathematical symbols. TeX Format is used in the following example:
1 Right-click on the text of an example note. 2 In the resulting submenu, select Text Format. 3 In the submenu that results, select Tex Format if a check mark is not
\it{\omega_N = e^{(-2\pii)/N}}
6 Left-click on a point in the editor outside of the note.
3-44
Moving Notes
To move your notes:
1 Place the cursor over the text of the note.
Notice that the mouse cursor changes from an arrow to a vertical text-editing bar.
2 Click the left mouse button and hold down. 3 While holding down the left mouse button, drag the note to a new location. 4 Lift up on the left mouse button.
Deleting Notes
To delete your notes, do one of the following:
1 Place the mouse cursor over the text of the note. 2 Click and hold the left mouse button on the note.
or
4 Place the mouse cursor over the text of the note. 5 Click the right mouse button on the note. 6 From the resulting menu, select Cut.
3-45
Creating Charts
Name
Stateflow diagram name; read-only; click on this hypertext link to bring the chart to the foreground. Simulink subsystem name; read-only; click on this hypertext link to bring the Simulink subsystem to the foreground. Parent name; read-only; click on this hypertext link to display the parents property dialog box.
Simulink Subsystem
Parent
3-46
Field
Description
Update method
Choose from Triggered or Inherited, Sampled, or Continuous. If Update method is Sampled, enter a sample time. Check this box to recognize C bit-wise operators (~, &, |, ^, >>, etc.) in action language statements and encode them as C bit-wise operations. If this box is not checked, the following occurs: & and | are interpreted as logical operators ^ is interpreted as the power operator (e.g., 2^3 = 8) The remaining expressions (>>, <<, etc.) result in parse errors. To specify this interpretation for all charts in the model (machine), select the Apply to all charts in machine now button.
Check this box to specify that no code is emitted when building for a custom target. This feature is useful for using Stateflow charts to simulate test environments during simulation testing before building to an actual embedded target. Exports graphical functions defined at the charts root level. See Exporting Graphical Functions on page 3-55 for more information.
3-47
Creating Charts
Field
Description
If this option is checked, this chart block can accept and output signals of any data type supported by Simulink. The type of an input signal must match the type of the corresponding chart input data item (see Defining Input Data on page 4-23). Otherwise, a type mismatch error occurs. If this item is unchecked, this chart accepts and outputs only signals of type double. In this case, Stateflow converts Simulink input signals to the data types of the corresponding chart input data items. Similarly, Stateflow converts chart output data (see Defining Output Data on page 4-23) to double, if this option is unchecked. Check this option if you want a charts state configuration to be initialized at time 0 instead of at the first occurrence of an input event. Click on the check box to set a debugging breakpoint On chart entry. Click on the Locked check box to mark the Stateflow diagram as read-only and prohibit any write operations. Textual description/comment. Enter a Web URL address or a general MATLAB command. Examples are www.mathworks.com, mailto:email_address, and edit/spec/data/ speed.txt.
Click on the Apply button to save the changes. Click on the Cancel button to cancel any changes since the last apply. Click on the OK 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.
3-48
Waking Up Charts
Waking Up Charts
Stateflow lets you specify the method by which a simulation updates (wakes up) a chart. To specify a wake up method for a chart, set the charts Update method property (see Specifying Chart Properties on page 3-46) to one of the following options: Triggered or Inherited This is the default update method. Specifying this method causes inputs from the Simulink model to determine when the chart wakes up during a simulation. If you define input events for the chart (see Defining Input Events on page 4-7), the chart awakens when trigger signals appear on the charts trigger port. If you define data inputs (see Defining Input Data on page 4-23) but no event inputs, the chart awakens at the rate of the fastest data input. If you do not define any inputs for the chart, the chart wakes up at the models solver sample rate. Sampled Simulink awakens (samples) the Stateflow block at the rate you specify as the blocks Sample Time property. 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 The Stateflow block wakes up 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 5-23 and Using Simulink for more information.
3-49
Creating Charts
A function can reside anywhere in a diagram, either at the top level or within any state or subchart. The location of a function determines its scope, that is, the set of states and transitions that can invoke the function. In particular, the scope of a function is the scope of its parent state or chart, with the following exceptions. - The chart containing the function exports its graphical functions. In this case, the scope of the function is the scope of its parent state machine. See Exporting Graphical Functions on page 355 for more information. - A child of the functions parent define a function of the same name. In this case, the function defined in the parent is not visible anywhere in the child or its children. In other words, a function defined in a state or subchart shadows any functions of the same defined in the ancestors of that state or subchart.
3-50
2 Select Function from the Type submenu of the newly created states
The function prototype specifies a name for the function and formal names for its arguments and return value. A prototype has the syntax
y = f(a1,a2,...an)
where f is the functions name, a1, a2, an are formal names for its arguments, and y is the formal name for its return value. The following example shows a prototype for a graphical function named f1 that takes two arguments and returns a value.
3-51
Creating Charts
The return values and arguments that you declare in the prototype appear in the Explorer as data items parented by the function object.
The Scope field in the Explorer indicates the role of the corresponding argument or return value. Arguments have scope Input. Return values have scope Output. The number that appears in parentheses for the scope of each argument is the order in which the argument appears in the functions prototype. When a Stateflow action invokes a function, it passes arguments to the function in the same order. In the context of graphical function prototypes, the term scope refers to the role (argument or return value) of the data items specified by the functions prototype. The term scope can also refer to a data items visibility. In this sense, arguments and return values have local scope. They are visible only in the flow diagram that implements the function. Note You can use the Stateflow editor to change the prototype of a graphical function at any time. When you are done editing the prototype, Stateflow updates the data dictionary and the Explorer to reflect the changes.
4 Specify the data properties (data type, initial value, etc.) of the functions
arguments and return values (if it has any). SeeSetting Data Properties on page 415 for information on setting data properties. The following restrictions apply to argument and return value properties. - A function cannot return more than one value.
3-52
- Arguments and return values cannot be arrays. - Arguments cannot have initial values. - Arguments must have scope Input. - Return values must have scope Output.
5 Create any additional data items that the function may need to process
when it is invoked. See Adding Data to the Data Dictionary on page 414 for information on how to create data items. A function can access only items that it owns. Thus, any items that you create for use by the function must be created as children of the function. The items that you create can have any of the following scopes: - Local A local data item persists from invocation to invocation. For example, if the item is equal to 1 when the function returns from one invocation, the item will equal 1 the next time the function is invoked. - Temporary Stateflow creates and initialize a copy of a temporary item for each invocation of the function. - Constant A constant data items retains its initial value through all invocations of the function. Note You can also assign Input and Output scope to data items that you create (i.e, to items that do not correspond to the functions formal arguments and return value). However, Input and Output items that do not correspond to your functions formal arguments and return values will cause parse errors. In other words, you cannot create arguments or return values by creating data items.
All data items (other than arguments and return values) parented by a graphical function can be initialized from the workspace. However, only local items can be saved to the workspace.
3-53
Creating Charts
6 Create a flow diagram within the function that performs the action to be
performed when the function is invoked. At a minimum, the flow diagram must include a default transition terminated by a junction. The following example shows a minimal flow diagram for a graphical function that computes the product of its arguments.
7 If you prefer, hide the functions contents by selecting Subcharted from the
3-54
3-55
Creating Charts
Name Parent
Function name; read-only; click on this hypertext link to bring the function to the foreground. Parent of this function; a / character indicates the Stateflow diagram is the parent; read-only; click on this hypertext link to bring the parent to the foreground. Click on the check box to set a breakpoint where the function is called. See Chapter 10, Debugging and Testing for more information.
Debugger breakpoints
3-56
Field
Description
This option controls the inlining of this graphical function in generated code through the following selections: Auto Stateflow decides whether or not to inline the function based on an internal calculation. Force Inline Stateflow inlines the function as long as it is not exported to other charts and is not part of a recursion. A recursion exists if the function calls itself either directly or indirectly through another called function. No Inline The function is not inlined.
Label
The functions label. Specifies the functions prototype. See Creating a Graphical Function on page 3-50 for more information. Textual description/comment. Enter a URL address or a general MATLAB command. Examples are www.mathworks.com, mailto:email_address, and edit/spec/data/ speed.txt.
3-57
Creating Charts
3-58
Creating a Subchart
You create a subchart by converting an existing state, box, or graphical function into the subchart. The object to be converted can be one that you have created expressly for the purpose of making a subchart or it can be an existing object whose content you want to turn into a subchart. To convert a new or existing state, box, or graphical function to a subchart:
1 Select the object and click your mouses right button to display the Stateflow
shortcut menu.
3-59
Creating Charts
Note When you convert a box to a subchart, the subchart retains the attributes of a box. In particular, the resulting subcharts position in the chart determines its activation order (see Creating and Changing Boxes on page 3-22 for more information).
To convert the subchart back to its original form, select the subchart and uncheck the Subcharted item of the Make Contents submenu of the Stateflow shortcut menu.
3-60
a subchart and any other state or subchart at the same or different levels in the chart hierarchy (see Working with Supertransitions on page 3-64).
Opening a Subchart
Opening a subchart allows you to view and change its contents. To open a subchart, double-click your mouse anywhere in the block that represents the subchart. Stateflow replaces the current contents of the editor window with the contents of the subchart.
A shaded border surrounds the contents of the subchart. Stateflow uses the border to display supertransitions. To return to the previous view, select Back from the Stateflow shortcut menu, press the Esc key on your keyboard, or select the up or back arrow on the Stateflow toolbar.
Navigating Subcharts
The Stateflow toolbar contains a set of buttons for navigating a charts subchart hierarchy.
3-61
Creating Charts
Back
Forward
Up
Up If the Stateflow editor is displaying a subchart, this button replaces the subchart with the subcharts parent. If the editor is displaying a top-level chart, this button raises the Simulink model window containing the chart. The next two buttons allow you to retrace your steps as you navigate up and down a subchart hierarchy. Back Returns to the chart that you visited before the current chart. Forward Returns to the chart that you visited after visiting the current chart.
Editing a Subchart
You can perform any editing operation on a subchart that you can perform on a top-level chart. You can create, copy, paste, cut, relabel, resize, and group states, transitions, and other subcharts. You can also create transitions among states and junctions in a subchart in the same way you create them among states in a top-level chart. (See Working with Supertransitions on page 3-64 for information on creating transitions to and from a subchart). It is also possible to cut-and-paste objects between different levels in your chart. For example, to copy objects from a top-level chart to one of its subcharts, first open
3-62
the top-level chart and copy the objects. Then open the subchart and paste the objects into the subchart.
3-63
Creating Charts
In this example, supertransition t1 goes from state A in the parent chart to state C in the subchart and supertransition t2 goes from state C in the subchart to state B in the parent chart. Note that both segments of t1 and t2 have the same label.
Drawing a Supertransition
The procedure for drawing a supertransition differs slightly, depending on whether you are drawing the transition from an object outside a subchart to an object inside the chart, or vice versa.
3-64
Dragging the mouse causes a supertransition segment to appear. The segment looks like a regular transition. It is curved and is tipped by an arrowhead.
3-65
Creating Charts
3 Drag the segments tip anywhere just inside the border of the subchart.
If you are not happy with the initial position of the slit, you can continue to drag the slit around the inside edge of the subchart to the desired location.
4 Continue dragging the cursor toward the center of the subchart.
Wormhole
3-66
The subchart opens. Now the wormhole and supertransition are visible inside the subchart.
6 Drag and drop the tip of the supertransition anywhere on the border of the
object that you want to terminate the transition. This completes the drawing of the supertransition.
Note If the terminating object resides within a subchart in the current subchart, simply drag the tip of the supertransition through the wormhole of the inner subchart and complete the connection inside the inner chart. You can draw a supertransition to an object at any depth in the chart in this fashion.
3-67
Creating Charts
2 Keep dragging the transition away from the border of the subchart.
A wormhole appears.
3-68
Note If the parent chart is itself a subchart and the terminating object resides at a higher level in the subchart hierarchy, you can continue drawing by dragging the supertransition into the border of the parent subchart. This allows you to continue drawing the supertransition at the higher level. In this way, you can connect objects separated by any number of layers in the subchart hierarchy.
Labeling Supertransitions
To label a supertransition, label any of its segments using the same procedure used to label a regular transition (see Labeling Transitions on page 3-29). The resulting label appears on all segments of the transition. If you change the label on any segment, the change appears on all segments.
3-69
Creating Charts
Note Events parented by a library state machine are invalid. Stateflow allows you to define such events but flags them as errors when parsing a model.
3-70
3-71
Creating Charts
To Printer Prints the current view on the current printer. You can also print the current view from the command line using the sfprint command. See Appendix C, "API Methods Reference".
3 Check the desired print options on the dialog. 4 Select the Print button to generate the report.
3-72
4
Defining Events and Data
Defining Events . . . . . . . . Adding Events to the Data Dictionary Changing Event Properties . . . . Event Dialog Box . . . . . . . . . Naming Events . . . . . . . . . Defining Local Events . . . . . . . Defining Input Events . . . . . . Defining Output Events . . . . . . Exporting Events . . . . . . . . Importing Events . . . . . . . . Specifying Trigger Types . . . . . Describing Events . . . . . . . . Documenting Events . . . . . . . Implicit Events . . . . . . . . . Defining Data . . . . . . . . Adding Data to the Data Dictionary Setting Data Properties . . . . . Data Dialog Box . . . . . . . . Defining Data Arrays . . . . . . Defining Input Data . . . . . . Defining Output Data . . . . . . Associating Ports with Data . . . Defining Temporary Data . . . . Exporting Data . . . . . . . . Importing Data . . . . . . . . Documenting Data . . . . . . . Symbol Autocreation Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 . 4-2 . 4-4 . 4-5 . 4-7 . 4-7 . 4-7 . 4-8 . 4-9 . 4-9 . 4-10 . 4-11 . 4-11 . 4-11 . 4-14 . 4-14 . 4-15 . 4-17 . 4-21 . 4-23 . 4-23 . 4-24 . 4-24 . 4-25 . 4-25 . 4-26
. . . . . . . . . . . . 4-27
Defining Events
An event is a Stateflow object that triggers actions in a state machine or its environment. Stateflow defines a set of events that typically occur whenever a state machine executes (see Implicit Events on page 4-11). You can define other types of events that occur only during execution of a specific state machine or its environment. To define an event:
1 Add a default definition of the event to the Stateflow data dictionary (see
page 4-5 for an explanation). Stateflow adds a default definition of the new event to the Stateflow data dictionary and displays the Event dialog box.
3 Use the Event dialog box to specify event options (see Event Dialog Box on
page 4-5).
4-2
Defining Events
2 Select the object (state machine, chart, or state) in the Explorers object
4-3
Stateflow adds a default definition for the new event in the data dictionary and displays an entry for the new event in the Explorers content pane.
4 Set the new events properties to values that reflect its intended usage (see
Stateflow displays the Event dialog box for the selected event (see Event Dialog Box on page 4-5).
4 Edit the dialog box. 5 Select OK to apply your changes and dismiss the Event dialog.
Note You can also set an events Scope (see Defining Local Events on page 4-7) and Trigger properties by editing the corresponding fields in the events entry in the Explorers contents pane. If you want to set only these properties, you do not need to open the Event dialog for the event.
4-4
Defining Events
Name
Name of this event. The name allows you to specify this event in Stateflow actions. See Naming Events on page 4-7 for more information.
Parent
Clicking on this field displays the parent of this event in the Stateflow editor. The parent is the object in which this event is visible. When an event is triggered, Stateflow broadcasts the event to the parent and all the parents descendants. An events parent can be a state machine, a chart, or a state. You specify an events parent when you add it to the data dictionary (see Adding Events to the Data Dictionary on page 4-2).
Scope
Scope of this event. The scope specifies where the event occurs relative to its parent. The sections below detail each scope setting.
Local. This event occurs in a state machine and is parented by the state
machine or one of its charts or states. See Defining Local Events on page 4-7 for more information.
Input from Simulink. This event occurs in one Simulink block and is broadcast in another. The first block may be any type of Simulink block. The second block
4-5
must be a chart block. See Defining Input Events on page 4-7 for more information.
Output to Simulink. This event occurs in one Simulink block and is broadcast in
another. The first block is a chart block. The second block may be any type of Simulink block. See Defining Output Events on page 4-8 for more information.
Exported. An exported event is a Stateflow event that can be broadcast by external code built into a stand-alone or Real-time Workshop target. See Exporting Events on page 4-9 for more information. Imported. An imported event is an externally defined event that can be broadcast by a state machine embedded in the external code. See Importing Events on page 4-9 for more information.
Note If you copy a Stateflow chart block from one Simulink model to another, all objects in the chart hierarchy are copied except those parented by the Stateflow machine. This means that events parented by the original Stateflow machine (local, imported, exported) are not copied to the new machine. You can, however, use the Explorer tool to copy individual events by click-dragging them from machine to machine.
Trigger
Type of signal that triggers an input or output event. See Specifying Trigger Types on page 4-10 for more information.
Index
Index of the input signal that triggers this event. This option applies only to input events and appears when you select Input from Simulink as the scope of this event. See Associating Input Events with Control Signals on page 4-8 for more information.
Port
Index of port that outputs this event. This property applies only to output events and appears when you select Output to Simulink as the scope of this
4-6
Defining Events
event. See Associating an Output Event with an Output Port on page 4-8 for more information.
Description
Description of this event. Stateflow stores the contents of this field in the data dictionary. See Describing Events on page 4-11 for more information.
Document Link
Clicking this field displays online documentation for this event. See Documenting Events on page 4-11 for more information.
Naming Events
Event names enable actions to reference specific events. You assign a name to an event by setting its Name property. You can assign any name that begins with an alphabetic character, does not include spaces, and is not shared by sibling events.
4-7
4-8
Defining Events
Exporting Events
Stateflow allows a state machine to export events. Exporting events enables external code to trigger events in the state machine. To export an event, first add the event to the data dictionary as a child of the state machine (see Adding Events to the Data Dictionary on page 4-2). Then set the new events Scope property to Exported.
Note External events can be parented only by a state machine. This means that you must use the Explorer to add external events to the data dictionary. It also means that external events are visible everywhere in a state machine.
When encoding a state machine that parents exported events, the Stateflow code generator generates a function for each exported event. The C prototype for the exported event function has the form
void external_broadcast_EVENT()
where EVENT is the name of the exported event. External code built into the target containing the state machine can trigger the event by invoking the event function. For example, suppose you define an exported event named switch_on. External code can trigger this event by invoking the generated function external_broadcast_trigger_on. See Exported Events on page 5-23 for an example of how to trigger an exported event.
Importing Events
A state machine can import events defined by external code. Importing an event allows a state machine built into a stand-alone or Real-Time Workshop target to trigger the event in external code. To import an event, first add the event to the data dictionary as a child of the state machine that needs to trigger the event (see Adding Events to the Data Dictionary on page 4-2). Then set the new events Scope property to Imported.
Note The state machine serves as a surrogate parent for imported events. This means that you must use the Explorer to add imported events to the data dictionary.
4-9
Stateflow assumes that external code defines each imported event as a function whose prototype is of the form
void external_broadcast_EVENT
where EVENT is the Stateflow name of the imported event. For example, suppose that a state machine imports an external event named switch_on. Then Stateflow assumes that external code defines a function named external_broadcast_switch_on that broadcasts the event to external code. When encoding the state machine, the Stateflow code generator encodes actions that signal imported events as calls to the corresponding external broadcast event functions defined by the external code.
event.
Falling Edge. A falling level on the control signal triggers the event.
4-10
Defining Events
In all cases, the signal must cross 0 to constitute a valid trigger. For example, a change from -1 to 1 constitutes a valid rising edge, but not a change from 1 to 2. If you specify an edge trigger type that differs from the edge type previously defined for a chart, Stateflow changes the Trigger type of the charts input events to Either Edge.
Describing Events
Stateflow allows you to store brief descriptions of events in the data dictionary. To describe a particular event, set its Description property to the description.
Documenting Events
Stateflow allows you to provide online documentation for events defined by a model. To document a particular event, set its Documentation property to a MATLAB expression that displays documentation in some suitable online format (for example, an HTML file or text in the MATLAB command window). Stateflow evaluates the expression when you click on the events documentation link (the blue text that reads Document Link displayed at the bottom of the events Event dialog box).
Implicit Events
Stateflow defines and triggers the following events that typically occur whenever a chart executes: Chart waking up Entry into a state Exit from a state Value assigned to an internal (noninput) data object These events are called implicit events because you do not have to define or trigger them explicitly. Implicit events are children of the chart in which they occur. Thus, they are visible only in the charts in which they occur.
4-11
where event is the name of the implicit event and object is the state or data in which the event occurred. Valid implicit event names (and their shortcuts) are wakeup ( also referred to as tick), enter (en), exit (ex), and change (chg). If more than one object has the same name, the event reference must qualify the objects name with that of its ancestor. The following are some examples of valid implicit event references.
enter(switch_on) en(switch_on) change(engine.rpm)
Note The wakeup ( or tick) event always refers to the chart of the action being evaluated. It cannot reference a different chart by argument.
Example
This example illustrates use of an implicit enter event.
4-12
Defining Events
Fan and Heater are parallel (AND) superstates. By default, the first time the Stateflow diagram is awakened by an event, the states Fan.Off and Heater.Off become active. The first time event Fan_switch occurs, the transition from Fan.Off to Fan.On occurs. When Fan.Ons entry action executes, an implicit local event is broadcast (i.e., en(Fan.On) == 1). This event broadcast triggers the transition from Heater.Off to Heater.On (triggered by the condition en(Fan.On). Similarly, when the system transitions from Fan.On to Fan.Off and the implicit local event Fan.Off is broadcast, the transition from Heater.On to Heater.Off is triggered.
4-13
Defining Data
A state machine can store and retrieve data that resides internally in its own workspace. It can also access data that resides externally in the Simulink model or application that embeds the state machine. When creating a Stateflow model, you must define any internal or external data referenced by the state machines actions. To define an item of data:
1 Add the item to the data dictionary (see Adding Data to the Data
Dictionary).
2 Set the new items properties (see Setting Data Properties on page 4-15).
page 4-17). Stateflow adds a default definition of the new item to the Stateflow data dictionary and displays a Data dialog that displays the new items default properties.
3 Use the Data dialog box to set the new items properties to reflect its
4-14
Defining Data
2 Select the object (state machine, chart, or state) in the Explorers object
Stateflow adds a default definition for the new item in the data dictionary and displays an entry for the item in the Explorers content pane.
4 Set the new items properties to values that reflect its intended usage (see
4-15
2 Select the item in the Explorers contents pane. 3 Select Properties from the Explorers Edit or context menu.
Stateflow displays the Data dialog box for the selected item.
4 Use the dialog boxs controls to set the items properties.
See Data Dialog Box on page 4-17 for a description of the dialog boxs controls and how to use them to set the data items properties.
5 Select OK to apply your changes and dismiss the Data dialog box.
Note You can also set a data items scope, type, sizes, initial value, minimum and maximum value, and to and from workspace properties by editing the corresponding fields in the items entry in the Explorers contents pane. If you want to set only these properties, you do not need to open the Data dialog box for the event.
4-16
Defining Data
Name
Name of the data item. A data name can be of any length and can consist of any alphanumeric and special character combination, with the exception of embedded spaces. The name cannot begin with a numeric character.
Parent
Parent of this data item. The parent determines the objects that can access it. Specifically, only the items parent and descendants of that parent can access the item. You specify the parent of a data item when you add the item to the data dictionary.
Scope
Scope of this data item. A data objects scope specifies where it resides in memory relative to its parent. These are the options for the Scope property:
Local. A local data object resides and is accessible only in a machine, chart, or
state.
4-17
Input from Simulink. This is a data item that is accessible in a Simulink chart block but resides in another Simulink block that may or may not be a chart block. The receiving chart block reads the value of the data item from an input port associated with the data item. See Importing Data on page 4-25 for more information. Output to Simulink. This is a data item that resides in a chart block and is
accessible in another block that may or may not be a chart block. The chart block outputs the value of the data to an output port associated with the data item. See Defining Output Data on page 4-23 for more information.
Temporary. A temporary data item exists only while its parent is executing. See Defining Temporary Data on page 4-24 for more information. Constant. A Constant data object is read-only and retains the initial value set in its Data properties dialog box. Exported. An exported data item is state machine data that can be accessed by external code that embeds the state machine. See Exporting Data on page 4-25 for more information. Imported. Imported data is data defined by external code that can be accessed by a state machine embedded in the external code. See Importing Data on page 4-25 for more information.
Note If you copy a Stateflow chart block from one Simulink model to another, all objects in the chart hierarchy are copied except those parented by the Stateflow machine. This means that data parented by the original Stateflow machine (local, imported, exported) is not copied to the new machine. You can, however, use the Explorer tool to copy individual data by click-dragging them from machine to machine.
Type
Data type of this data item, e.g., integer, double, etc.
4-18
Defining Data
Port
Index of the port associated with this data item (see Associating Ports with Data on page 4-24). This control applies only to input and output data.
Units
Units, e.g., inches, centimeters, etc., represented by this data item. The value of this field is stored with the item in the state machines data dictionary.
Array
If checked, this data item is an array. Checking this option enables the next two options.
Sizes. Size of this array. The value of this property may be a scalar or a MATLAB vector. If it is a scalar, it specifies the size of a one-dimensional array (i.e., a vector). If a MATLAB vector, it indicates the size of each dimension of a multidimensional array whose number of dimensions corresponds to the length of the vector. First Index. Specifies the index of the first element of this array. For example, the first index of a zero-based array is 0.
Limit Range
This control group specifies values used by the state machine to check the validity of this data item. It includes the next two controls.
Min. Minimum value that this data item can have during execution or simulation of the state machine. Max. Maximum value that this data item can have during execution or simulation of the state machine.
Initialize from
Source of the initial value for this data item: either the Stateflow data dictionary or the MATLAB workspace. If this data item is an array, Stateflow sets each element of the array to the specified initial value. If the source is the data dictionary, enter the initial value in the adjacent text field. Stateflow stores the value that you enter in the data dictionary.
4-19
If the source is the MATLAB workspace, this item gets its initial value from a similarly named variable in the MATLAB workspace. For example, suppose that the name of a Stateflow data item is A. If the parent workspace has a variable named A, this value is used to initialize the data item. The following table summarizes the time of initialization for each data scope.
Parent Scope Initializes at ...
Machine
Chart
Not applicable Start of simulation or when chart is re-initialized as part of an enabled Simulink subsystem.
local State activation (state entered) Start of simulation or when chart is re-initialized as part of an enabled Simulink subsystem. input output local Not applicable When function is invoked Start of simulation or when chart is re-initialized as part of an enabled Simulink subsystem.
Graphical Function
Note For information on enabled Simulink subsystems, see Chapter 8, Conditionally Executed Subsystems, of the Using Simulink manual.
4-20
Defining Data
Note You can also use the Stateflow Explorer to set the Initialize from field.
Watch in debugger
If checked, this option causes the debugger to halt if this data item is modified.
Description
Description of this data item.
Document link
Clicking this field displays user-supplied online documentation for this data item. See Documenting Data on page 4-26 for more information.
or machine that needs to access the data (see Adding Data to the Data Dictionary on page 4-14).
2 Open the Data dialog box. Check the Array check box on the dialog. Set the
items Sizes property to the size of each of the arrays dimensions (Setting Data Properties on page 4-15). For example, to define a 100-element vector, set the Sizes property to 100. To define a 2-by-4 array, set the Sizes property to [2 4].
4-21
3 Set the items Initial Index property to the index of the arrays first
element. For example, to define a zero-based array, set the Initial Index property to 0.
4 Set the items initialization source and, if initialized from the data
dictionary, initial value. For example, to specify that an arrays elements be initialized to zero, set the Initialized from option in the Data dialog box to data dictionary and the enter 0 in the adjacent text field.
5 Set the other options in the dialog box (e.g., Name, Type, and so on) to reflect
Example
Suppose that you want to define a local, 4-by-4, zero-based array of type Integer named rotary_switches. Further, suppose that each element of the array was initially 1 and could have no values less than 1 or greater than 10. The following Data dialog box shows the settings for such an array.
4-22
Defining Data
Set the items other properties (e.g., Name, Type, etc.) to appropriate values. You can set an input items data type to any Stateflow-supported type. If the charts strong data typing option is enabled (see Specifying Chart Properties on page 3-46), input signals must match the specified type. Otherwise, a mismatch error occurs. If strong data typing is not enabled, input signals must be of type double. In this case, Stateflow converts the input value to the specified type. If the input item is a vector, the model must supply the data via a signal vector connected to the corresponding input port on the chart.
4-23
property to Output to Simulink. Stateflow adds an output port to the chart for each item that it outputs.
Output to Simulink
You can set an output items type to any supported Stateflow data type (for example, Integer). If the charts strong data typing option is enabled (see Specifying Chart Properties on page 3-46), the chart outputs a Simulink signal of the same data type as the output data items type. If the option is not enabled, the Stateflow chart block converts the output data to Simulink type double.
4-24
Defining Data
the parent chart or graphical function can access the temporary data. 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.
Exporting Data
Stateflow can export definitions of state machine data to external code that embeds the state machine. Exporting data enables external code, as well as the state machine, to access the data. To export a data item, first add it to the data dictionary as the child of the state machine in which it is defined. Then set its Scope property to Exported and its other properties (e.g., Name and Type) to appropriate values.
Note Only a state machine can parent external data. This means that you must use the Explorer to add external data to the data dictionary. It also means that external data are visible everywhere in its state machine (model).
The Stateflow code generator generates a C declaration for each exported data item of the form
type ext_data;
where type is the C type of the exported item (e.g., int, double) and data is the items Stateflow name. For example, suppose that your state machine defines an exported integer item named counter. The Stateflow code generator exports the item as the C declaration
int ext_counter;
The code generator includes declarations for exported data in the generated targets global header file, thereby making the declarations visible to external code compiled into or linked to the target.
Importing Data
A state machine can import definitions of data defined by external code that embeds the state machine. Importing externally defined data enables a state machine to access data defined by the system in which it is embedded. To import an externally defined data item into a state machine, add a default item to the data dictionary as a child of the state machine. Then set the new items
4-25
Scope property to Imported, its Name property to the name used by the machines actions to reference the item, and its other properties (i.e., Type, Initial Value, etc.) to appropriate values.
The Stateflow code generator assumes that external code provides a prototype for each imported item of the form
type ext_data;
where type is the C data type corresponding to the Stateflow data type of the imported item (e.g., int for Integer, double for Double, etc.) and data is the items Stateflow name. For example, suppose that your state machine defines an imported integer item named counter. The Stateflow code generator expects the item to be define in the external C code as
int ext_counter;
Documenting Data
Stateflow allows you to provide online documentation for data defined by a model. To document a particular item of data, set its Documentation property to a MATLAB expression that displays documentation in some suitable online format (for example, an HTML file or text in the MATLAB command window). Stateflow evaluates the expression, when you click on the items documentation link (the blue text that reads Document Link displayed at the bottom of the events Data dialog box).
4-26
To reject a recommendation, click the check mark next to the symbols type. The wizard unchecks the entry for the symbol. To change the recommended type, scope, or parent of the symbol, click the corresponding entry for the symbol in the Symbol Wizard. The wizard replaces the entry with an alternative value. Keep clicking until the desired alternative appears. When you are satisfied with the proposed symbol definitions, click the wizards Add button to add the symbols to Stateflows data dictionary.
4-27
4-28
5
Defining Stateflow Interfaces
Overview . . . . . . . . . . . . . . . . . . . . . 5-2 Defining the Stateflow Block Update Method . . . . . 5-4 Defining Output to Simulink Event Triggers . . . . . 5-9 Inputting Events from Simulink . . . . . . . . . . . 5-15 Inputting Data from Simulink . . . . . . . . . . . . 5-17 Outputting Events to Simulink Outputting Data to Simulink MATLAB Workspace . . . . . . . . . . . 5-19 . . . . . . . . . . . . 5-20
. . . . . . . . . . . . . . . . 5-22
Overview
Interfaces to Stateflow
Each Stateflow block interfaces to its Simulink model. Each Stateflow block can 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 blocks 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 model. The Stateflow block interface includes: Physical connections between Simulink blocks and the Stateflow block Event and data information exchanged between the Stateflow block and external sources Graphical functions exported from a chart The MATLAB workspace Definitions in external code sources
5-2
Overview
5-3
5-4
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.
5-5
The Sample Time (set in the Chart Properties dialog box) takes precedence over the sample time of any Input from Simulink data.
The outputs of a sampled Stateflow block are held after the execution of the block.
5-6
In this example, more than 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.
The outputs of an inherited trigger Stateflow block are held after the execution of the block.
5-7
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 example, as modes of control strategy.
5-8
5-9
triggered subsystem executes and then 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. Use a 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.
The control block is a Stateflow block that has one data input called pulse and two event Function Call outputs called filter1 and filter2. A pulse generator provides input data to the control block. Within the control block, a determination is made whether to make a function call to filter1 or filter2. If, for example, the Output to Simulink event Function Call filter1 is broadcast, the band pass filter1 block executes and then returns to the next execution step in the control block. As part of its execution, band
5-10
pass filter1 receives unfiltered input data and outputs filtered data for display on a scope.
The Stateflow block controls the execution of band pass filter1 and band pass filter2.
5-11
This sequence is followed when state A is active and the transition from state A to state B is valid and is taken:
1 State A exit actions execute and complete. 2 State A is marked inactive. 3 The transition action is executed and completed. In this case the transition
action is a broadcast of event1. Because event1 is an event output to Simulink with a function call trigger, the band 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 State B is marked active. 5 State B entry actions execute and complete (x = x + y). The value of y is the
event.
5-12
This sequence is followed when state A is active and the transition from state A to state B is valid and is taken:
1 State A exit actions execute and complete. 2 State A is marked inactive. 3 The transition 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 State B is marked active.
5-13
5 State B entry actions execute and complete (x = x++). 6 The Stateflow diagram goes back to sleep waiting to be awakened by another
event.
7 The band pass filter1 block is triggered, executes, and completes.
5-14
Explorer.
2 Select the chart object in the hierarchy that you want to be the events
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, to the chart, and all its offspring.
3 Choose Event from the Explorer Add menu. The Event Properties dialog
box is displayed.
4 Enter a name in the Name field.
5-15
Rising Edge
Rising edge trigger, where the control signal changes from either 0 or a negative value to a positive value. Falling edge trigger, where the control signal changes from either 0 or a positive value to a negative value. Either rising or falling edge trigger. Function call triggered.
Falling Edge
Each Stateflow block can only have one overall trigger type, either function call or edge. See Specifying Trigger Types on page 4-10 for more information.
5-16
Explorer.
2 Select a chart object in the hierarchy that you want to be the data objects
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 a name in the Name field.
5-17
Note If you want the input port corresponding to this input data item to accept Simulink data of type other than double, you must select the charts strong data typing option. See Defining Input Data on page 4-23 and Specifying Chart Properties on page 3-46 for more information.
5-18
Explorer.
2 Select the chart that you want output the event. 3 Choose Event from the Explorer Add menu. The Event dialog box appears. 4 Enter a name in the Name field.
5-19
Explorer.
2 Select the chart that you want to output data. 3 Choose Data from the Explorer Add menu. The Data dialog box is displayed. 4 Enter a name in the Name field.
5-20
Arrays are of fixed size only. It is not possible to change the array size at run-time.
Note If you want the output port corresponding to this output data item to emit data of type other than double, you must select the charts strong data typing option. See Defining Input Data on page 4-23 and Specifying Chart Properties on page 3-46 for more information.
5-21
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 the MATLAB online or printed documentation for more information.
5-22
Exported Events
Consider a real world example to clarify when to define an Exported event. You have purchased a communications pager. There are a 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. You 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 persons 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 events 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 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 Imported. Stateflow generates the appropriate export and import event code for both machines.
5-23
This example shows the format required in the external code source (custom code) to take advantage of an Exported event.
e is imported in the
Imported Events
Consider the same pager example 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
5-24
and you take note of the number by writing it down. You can then use the number to page that person. Similarly, you may want to broadcast an event that is defined externally (outside the Stateflow diagram, the machine, and the Simulink model). By defining an events scope to be Imported, the event can be broadcast anywhere within the hierarchy of that machine (including any offspring of the machine). An Imported events parent is external. However, the event needs an adoptive parent to resolve symbols for code generation. An Imported events adoptive parent must be the machine because the machine is the (highest) level in the Stateflow hierarchy that can interface to external sources. It is the responsibility of the external source to make the Imported event available (in the manner appropriate to the source). If the external source is another machine, it must define the same event to be Exported. Stateflow generates the appropriate import and export event code for both machines.
5-25
This example shows the format required in the external code source (custom code) to make the event available.
e is exported in the
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 objects 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
5-26
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 object 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.
...
ext_data = 123;
...
}
5-27
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 a datas 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 objects parent is external. However, the data object needs an adoptive parent to resolve symbols for code generation. An Imported data objects adoptive parent must be the machine because the machine is the (highest) level in the Stateflow hierarchy that can interface to external sources. It is the responsibility of the external source to make the Imported data object available (in the manner appropriate to the source) . If the external source is another machine, it must define the same data object to be Exported. Stateflow generates the appropriate import and export data code for both machines.
5-28
This example shows the format required if the data is Imported from an external code source (custom code).
5-29
5-30
6
Exploring and Searching Charts
Overview . . . . . . . . . . . . . . . . . . . . . 6-2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3 6-3 6-3 6-4 6-5 6-5 6-7 6-7 6-14 6-14 6-15 6-18 Exploring Charts with Stateflow Explorer . . . Overview of Explorer . . . . . . . . . . . . . . Opening Stateflow Explorer . . . . . . . . . . . Explorer Main Window . . . . . . . . . . . . . Object Icons in the Explorer . . . . . . . . . . . Objects and Properties in the Explorer Contents Pane Targets in Explorer . . . . . . . . . . . . . . . Explorer Operations . . . . . . . . . . . . . . Searching (Only) in Charts Opening Stateflow Finder . . Using Stateflow Finder . . . Finder Display Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Searching and Replacing in Charts . . . . . Using Different Search Types . . . . . . . . . Specify the Search Scope . . . . . . . . . . . Using the Search Button and View Area . . . . . Specifying the Replacement Text . . . . . . . . Using the Replace Buttons . . . . . . . . . . . Search and Replace Messages . . . . . . . . . The Search & Replace Tool Is a Product of Stateflow
Overview
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.
You can use the Stateflow Explorer and Simulinks Find dialog box together to browse and make changes to data dictionary objects.
6-2
or
2 Right-click on empty space in an existing Stateflow chart. 3 In the resulting menu, select Explore.
6-3
Message area
The Explorer main window has two panes: an Object Hierarchy pane on the left and a Contents pane on the right. The purpose of the Explorer tool is to display the data, event, and target objects parented (contained by) each graphical element in a Stateflow chart. The Object Hierarchy pane displays the graphical elements of a Stateflow chart (machines, charts, states, boxes, and graphical functions) in the left-hand pane. A preceding plus (+) character indicates that the hierarchy can be expanded by double-clicking on that entry (or by clicking on the plus (+) character). A preceding minus (-) character indicates there is nothing to expand. Clicking on an entry in the Object Hierarchy pane selects that entry. The Contents pane displays the data, event, and target objects parented by the currently selected object in the Object Hierarchy pane. Data and event objects are described in Chapter 4, Defining Events and Data. See the section Targets in Explorer on page 6-7 for a quick introduction to target objects. For a more detailed description of target objects, see Chapter 9, Building Targets.
6-4
6-5
Can be parented by... Object Event Data Target Machine? Chart? State? Box? Graphic Function?
yes yes no
yes yes no
yes yes no
yes yes no
For convenience, a hypertext link to the parent of the currently selected object in the Object Hierarchy is included following the Contents of: label at the top of the Contents pane. Click on this link to display that object in the Stateflow diagram editor. Properties for each of the objects in the Contents pane are displayed in column entries as follows.
Property Name Scope Trigger Type Size Min Max InitVal Description Property of...
Name of property Scope of property Trigger of event Data type Size of data array Minimum value of data limit range Maximum value of data limit range Initial value of data when initialized from data dictionary Initialize data from MATLAB Workspace
Data, Event, Target Data, Event Event Data Data Data Data Data Data
FrWS
6-6
Description
Property of...
Data Data
The above properties are identified in the following sections for each objects Properties dialog: Data Dialog Box on page 4-17 Event Dialog Box on page 4-5 Starting the Target Builder Dialog on page 9-9 You can access the Properties dialog of each of the above objects to change or add properties. You can also change these properties directly from the Explorer window. See the section Setting Properties for Objects on page 6-10.
Targets in Explorer
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 simulation target (sfun) is automatically defined for every machine. If you have a Real-Time Workshop license, a Real-Time Workshop target (rtw) is also automatically added when you do the following: Select Open RTW Target from the graphics editor Tools menu Build a target that includes a Stateflow machine using Real-Time Workshop See Configuring a Target on page 9-7 for information on configuring and customizing a target. See Adding a Target to a State Machines Target List on page 9-7 for information on creating targets to generate code using the Stateflow Coder product.
Explorer Operations
The following sections describe operations to event, data, and target objects in the Stateflow Explorer.
6-7
Simulink opens a new model with a default Stateflow block which is displayed in the Explorer.
1 From the File menu select Open Model....
Simulink opens an existing model. If it has Stateflow blocks included, they are displayed in the Explorer.
You can move event, data, or target objects to another parent by doing the following:
1 Select the events, data, and targets to move in the Contents pane of the
Explorer. You can select a contiguous block of items by highlighting the first (or last) item in the block and then using Shift+Click for highlighting the last (or first) item.
2 Click and drag an object from the Contents pane to a new location in the
A shadow copy of the selected objects accompany the mouse cursor during dragging. If no parent is chosen or the parent chosen is the current parent, the mouse cursor changes to an X enclosed in a circle indicating an invalid choice.
6-8
You can accomplish the same outcome by cutting or copying the selected events, data, and targets as follows:
1 Select the event, data, and targets to move in the Contents pane of the
Explorer.
2 From the Edit menu of the Explorer, select Edit > Cut or Copy.
If you select Cut, the selected items are deleted and are copied to the clipboard for copying elsewhere. If you select Copy, the selected items are left unchanged. You can also right-click the mouse on a single selection and select Cut or Copy from the resulting menu. Explorer also uses the keyboard equivalents of Ctrl+X (Cut) and Ctrl+V (Paste).
3 Select a new parent machine, chart, or state in the Object Hierarchy pane
of the Explorer.
4 From the Edit menu of the Explorer, select Edit > Paste and the cut items
appear in the Contents pane of the Explorer. You can also paste the cut items by right-clicking the mouse on an empty part of the Contents pane of the Explorer and selecting Paste from the resulting menu.
Changing the Index Order of Event and Data Input and Output Objects
You can change the order of indexed Scope Input(1,2,...,m) or Output(1,2,...,n) event and/or data objects to Simulink in the Contents pane of Explorer as follows:
1 Select one of the input or output items. 2 Drag the item to a new location within its respective list.
Separate lists can appear for Data Input, Event Input, Data Output, or Event Output. You must keep the dragged item within its list. Valid new locations appear with an arrow and attached text "insert here".
6-9
You may also select Cut from the Edit menu or Ctrl+X from the keyboard to delete an object.
Stateflow displays the selected object highlighted in the Stateflow editor in the context of its parent.
changes. You can also change properties in the Explorer directly by first clicking on the objects row to highlight it and then doing the following: To change the Name property, double-click on it and edit it in the resulting overlay edit field. Press the Return key or click anywhere outside the edit field to apply the changes.
6-10
To change the Scope, Trigger, or Type properties, click on the item and select from the resulting submenu. To change all other properties but the checked ones, click on the property and edit in the resulting overlay edit field. When finished, press the Return key or click anywhere outside the edit field to apply the changes. To change a checked property, click on the check to uncheck it. You can also click on an empty unchecked property to check it.
Transferring Properties
The Explorer allows you to transfer the properties of one object to another object or set of objects with the following procedure:
1 Right-click the object in the Contents pane of the Explorer.
6-11
As an alternative to steps 1 and 2, you can also highlight the object and select Pickup Properties from the Edit menu.
3 Select the object or objects to which you want to transfer the properties.
As an alternative to steps 3 and 4, if only one object is selected to receive properties, you can right-click on it and select Apply Properties from the resulting menu. Stateflow applies the copied properties to the selected object(s) as shown in the Type, Min, Max, InitVal, and Watch columns of the example below.
6-12
6-13
Note See the Simulink section in the Release Notes in the online documentation for a list of platforms on which the Simulink Find tool is not available.
6-14
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 Look in: list box to choose one of these options: 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 for the string specified in the Look for: field. 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. Document Link Search the document link fields of the specified object types for the string specified in the Look for: field.
6-15
Custom Code Search custom code for the string specified in the Look for: field.
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 Finder.
Character Description
^ $ . \ * + []
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: States Transitions Junctions
6-16
Find Button
Click on the Find button to initiate the search operation. The data 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(&) 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 to the 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 the Stateflow online help in an HTML browser window.
6-17
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). The string label of the object is listed in this field. The title of the Stateflow diagram (Stateflow block) is listed in this field. This objects parent in the hierarchy. Source object of a transition. 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
6-18
the hierarchy is readable. The entire field 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 Properties dialog box for that object. Right-click the entry to display a menu that allows you to explore, edit, or display the properties of that entry.
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 by a period (.) character. The Source and Destination fields use the combination of the tilde (~) and the period (.) characters to denote that the state listed is relative to the Parent hierarchy.
6-19
what are the values for the Parent, Source, and Destination fields for the transition from A2a to A2b? The transition is within state A2. State A2s parent is state A and state As parent is the Stateflow diagram itself. /A.A2 is the notation for state A2as parent. State A2a is the transition source and state A2b is the destination. These states are at the same level 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.
6-20
6-21
The window name for the Search & Replace dialog box contains a full path expression for the current Stateflow chart or machine in the following form.
(object) Machine/Subsystem/Chart
The Search & Replace dialog box contains the following fields: Search for Enter search pattern text in the Search for text box. Interpretation of the search pattern is selected with the Match case check box (below) and the Match Options field (below). Match case If this check box is checked, the search is case-sensitive and the Search & Replace tool finds only text matching the search pattern exactly. See the section Match case (Case Sensitive) on page 6-23. Replace with Specify the text to replace the text found when you select any of the Replace buttons (Replace, Replace All, Replace All in This Object). See the section Using the Replace Buttons on page 6-31. Preserve case This option modifies replacement text. For an understanding of this option, see the section Replacing with Case Preservation on page 6-30. Search in By default, the Search & Replace tool searches and replaces text only within the current Stateflow chart that you are editing in the Stateflow chart editor. You can select to search the Machine owning the current Stateflow chart or any other loaded Machine or chart by accessing this selection box. Match options This field is unlabeled and just to the right of the Search in field. You can modify the meaning of your search text by entering one of the selectable search options. See the section Using Different Search Types on page 6-23. Object types and Field types Under the Search in field are the selection boxes for Object types and Field types. These selections further refine your search and are described below.
6-22
By default, these boxes are hidden; only current selections are displayed next to their titles. Select the right-facing arrow button selection box and make changes. in front of the title to expand a
Select the same button (this time with a left-facing arrow) to compress the selection box to display the settings only, or, if you want, just leave the box expanded. Search and Replace buttons These are described in the sections Using the Search Button and View Area on page 6-27 and Using the Replace Buttons on page 6-31. View Area The bottom half of the Search & Replace dialog box displays the result of a search. This area is described in the section A Breakdown of the View Area on page 6-28.
Contains word
Select this option to specify that the search pattern text is a whole word expression used in a Stateflow chart with no specific beginning and end delimiters. In other words, find the specified text in any setting. Thus, searching for the string fail with the Contains word option set finds both occurrences of the string fail in the example above.
6-23
If Match whole word is selected, searching for the string fail finds no text within the above state. However, searching for the string "fail_state" does find the text "fail_state" as part of the second line since it is delimited as a word by a space on the front and a left square bracket ("[") on the back.
Regular expression
Set the Match options field to Regular expression to search for text that varies from character to character within defined limits. A regular expression is a string composed of letters, numbers, and special symbols that defines one or more string candidates. 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 backslash ("\") character precedes it. If the Match options field is set to Regular expression in the example above, searching for the string "fail_" matches the "fail_" string that is part of the second line, character for character. Searching with the regular expression "\w*_" also finds the string "fail_" as well. In this case, the search string uses the regular expression shorthand "\w" which represents any part-of-word character, an asterisk ("*"), which represents any number of any characters, and an underscore ("_"), which represents itself. For a list of regular expression metacharacters, see the section Regular Expression Syntax on page D-3 of Appendix C, Regular Expressions.
6-24
Preserve case
This option actually modifies replacement text and not search text. For an understanding of this option, see the section Replacing with Case Preservation on page 6-30
A list of the currently loaded machines appears with the current machine expanded to reveal its underlying Stateflow charts.
2 Select a machine.
6-25
This time the displayed list contains the previously selected machine expanded to reveal its Stateflow charts.
2 Select a chart from the expanded machine.
This limits your search to text matches in the selected object types only.
This limits your search to text matches for the specified fields only. Selectable field types are as follows: Names Machines, charts, data, and events have valid Name fields. In the Search & Replace tool, states have a Name defined as the top line of its Label field. You can search and replace text belonging to the Name field of a state in this sense. However, if the Search & Replace tool finds matching text in a states Name field, the remainder of the label is subject to succeeding searches for the specified text whether or not the Label field is chosen as a search target. Note The Name field of machines and charts is an invalid target for the Search & Replace tool. Use Simulink to change the name of machines and charts.
6-26
Labels Only states and transitions have labels. Descriptions All objects have searchable Description fields. Document links All objects have searchable Link fields. Custom code Only target objects contain custom code.
Name/Path
6-27
where p1 through pn denote the objects parent states. To display the object, click the mouse once on the full path name of the object. If the object is a graphical member of a Stateflow chart, it is displayed in the Stateflow chart editor. Otherwise, it is displayed as a member of its Stateflow chart in the Stateflow Explorer. Viewer This area displays the found text as a highlighted part of all search-qualified text fields for the owner object. If other occurrences exist in these fields, they too are highlighted, but in lighter shades. To invoke the Properties dialog box for the owner object, double-click anywhere in the View Area. Portal This area contains a graphic display of the object containing the matching text. The object containing the found text is highlighted in blue (default). To display the highlighted object in the Stateflow chart editor window, double-click anywhere in the Portal.
6-28
when you begin your search. After searching the first chart, the Search & Replace tool continues searching each chart in model order until all charts for the model have been searched. If you specify a Stateflow chart as your search scope, the Search & Replace tool begins searching at the beginning of the chart. The Search & Replace tool continues searching the chart until all of the charts objects have been searched. The search order taken in searching an individual chart for matching text is equivalent to a depth-first search of the Stateflow Explorer. Starting at the highest level of the chart, Explorer hierarchy is traversed downward from parent to child until an object with no child is encountered. At this point, the hierarchy is traversed upward through objects already searched until an unsearched sibling is found and the process is repeated.
A toggle switch that hides or displays the Portal. Displays the object with the matching text in the Stateflow chart editor; applies to States, Junctions, Transitions, and Charts Displays the object with the matching text in the Stateflow Explorer. Applies to States, Data, Events, Machines, Charts, and Targets. Displays the Properties dialog box for the object with the matching text.
Explore
Properties
Note The Edit, Explore, and Properties selections are enabled only after a successful search.
6-29
If the Portal is not visible, you can select the Show Portal option to display it. You can also simply click-drag the border between the Viewer and the Portal (cursor turns to vertical double arrow), which resides just above the bottom boundary of the Search & Replace dialog. Moving this border allows you to exchange area between the Portal and the Viewer. If you click-drag the border with the left mouse button, the graphic display resizes after you reposition the border. If you click-drag the border with the right mouse button, the graphic display continuously resizes as you move the border.
6-30
Sentence In this case, the found text contains an upper case character in the first character position of a sentence with all remaining sentence characters in lower case. Found text is replaced in like manner, with the first character of the sentence given an upper case equivalent and all remaining sentence characters set to lower case. For example, if the replacement text is "andrew is tall.", the found text "Bill is tall." is replaced by "Andrew is tall.".
Replace
When you select the Replace button, the current instance of text matching the text string in the Search for field is replaced by the text string entered in the Replace with field. The Search & Replace tool then automatically searches for the next occurrence of the Search for text string.
6-31
Replace All
When you select the Replace All button, all instances of text matching the Search for field are replaced by the text string entered in the Replace with field. Replacement starts at the point of invocation to the end of the current Stateflow chart. This means that if you initially skip through some search matches with the Search button, they will be skipped when you select the Replace All button. If the search scope is set to Search Whole Machine, then after finishing the current Stateflow chart, replacement continues to the completion of all remaining charts in your Simulink model.
6-32
The following messages are warnings that refer to invalid conditions for searching or replacing: Invalid option set The set of object types and field types that you have selected are incompatible. For example, a search on Custom Code fields without selecting target objects is invalid. Match object not currently editable The found object is not editable by replacement because of one of the following.
Problem Solution
A simulation is running. You are editing a locked library block. The current object or its parent has been manually locked.
Stop the simulation. Unlock the library. Unlock the object or its parent.
The following messages are warnings owing to the fact that when the Search & Replace tool performs a search or replacement immediately after finding an object, it must first refind the object and its matching text field. If that original found object is deleted or changed before an ensuing search or replacement, the Search & Replace tool cannot continue: Search object not found If you search for text, find it, and then delete the containing object, this warning results if you continue to search. Match object not found If you search for text, find it, and then delete the containing object, this warning results if you perform a replace. Match not found If you search for text, find it, and then change the object containing the text, this warning results if you perform a replace.
6-33
Search string changed If you search for text, find it, and then change the Search For field, this warning results if you perform a replace.
6-34
7
Notations
Overview . . . . . . . . . . . . . . . . . . . . . 7-2 States . . . . . . . . . . . . . . . . . . . . . . . 7-7 Transitions . . . . . . . . . . . . . . . . . . . . 7-14
Notations
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 communicate the design information conveyed by a Stateflow diagram. Stateflow notation consists of: A set of graphical objects A set of nongraphical text-based objects Defined relationships between those objects Action language
7-2
Overview
Data range violations Cyclic behavior You can modify the notation to resolve run-time errors. See Chapter 10, Debugging and Testing, for more information on debugging run-time errors.
Graphical Objects
These are the graphical objects in the notation that are on the toolbar.
Name Notation Toolbar Icon
State
Box
Graphical Function
Connective junction
A transition is a curved line with an arrowhead that links one graphical object to another. Either end of a transition can be attached to a source and a destination object. The source is where the transition begins and the destination is where the transition ends.
7-3
Notations
Event and data objects do not have graphical representations. These objects are defined using the Stateflow Explorer. See Chapter 4, Defining Events and Data.
7-4
Overview
The Stateflow diagram is the parent of Car_done. Car_done is the parent state of the Car_made and Car_shipped states. Car_made is also a parent to the Parts_assembled and Car_painted states. Parts_assembled and Car_painted are children of the Car_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 separated by the . character. The full hierarchy representation of the state names in this example is: /Car_done /Car_done.Car_made /Car_done.Car_shipped /Car_done.Car_made.Parts_assembled /Car_done.Car_made.Painted
7-5
Notations
A transitions hierarchy is described in terms of the transitions 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 . (period) character. The three transitions in the example are represented in the following table.
Transition Label switch_off switch_high switch_cold Parent Source Destination
/ /Power_on /Power_on.Low
7-6
States
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 states 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 executed in a sequence based upon action type. The action types are: entry, during, exit, or on event_name actions. This table shows the button icon and a short description of a state.
Name Button Icon Description
State
Superstate
A state is a superstate if it contains other states called substates.
Substate
A state is a substate if it exists in another state.
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 type.
7-7
Notations
7-8
States
An active state with parallel (AND) decomposition and an active state with exclusive (OR) decomposition In this example, state B, state C, and C.C2 or state B, state C, and C.C1 are active at the same time.
One active state with exclusive (OR) decomposition In this example, state B or state A.A1 or state A.A2 is active at any one time.
When a given state is active, all of its ancestor states are also active. See Semantics of Active and Inactive States on page 8-5 for more information.
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 (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.
7-9
Notations
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: Carriage return Semicolon Comma Specify multiple on 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. You 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 the entry keyword), the action(s) is interpreted as entry action(s). This shorthand is useful if you are only specifying entry actions. See What Is an Action Language? on page 7-37 for more information on the action language.
7-10
States
Name. The name of 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 or Green_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 Example: Unique State Names on page 7-12 for an example of uniquely named states. In this example, the state names are On and Off.
Entry Action. In the example, state On has entry action on_count=0. The value of on_count is reset to 0 whenever state Ons entry action is executed.
See Semantics of State Actions on page 8-7 for information on how and when entry actions are executed.
7-11
Notations
During Action. In the example, state On has two during actions light_on() and on_count++. These actions are executed whenever state Ons during action is
executed. See Semantics of State Actions on page 8-7 for information on how and when during actions are executed.
Exit Action. In the example, state Off has exit action light_off(). This action is executed whenever state Offs exit action is executed.
See Semantics of State Actions on page 8-7 for information on how and when exit actions are taken.
On Event_Name Action. In the example, state Off has the on event_name, power_outage. When the event power_outage occurs, the action handle_outage() is executed.
See Semantics of State Actions on page 8-7 for information on how and when on event_name actions are taken.
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 dictionary, the result is unique. The full names for the states as seen in the data dictionary are: Ride1.On Ride1.Off
7-12
States
Ride2.On Ride2.Off Although the names On and Off are duplicated, the full names are unique because of the hierarchy of the Stateflow diagram. The example intentionally contains only states for simplification purposes.
7-13
Notations
Transitions
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, On, to a destination state, Off.
Junctions divide a transition into segments. Each segment is evaluated in the process of determining the validity of the transition from a source to a destination. This is an example of a transition with segments.
A default transition is one special type of transition that has no source object.
7-14
Transitions
Labeling a Transition
A transition is characterized by its label. 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.
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 the OR logical operator (|). In this example, the broadcast of event E, triggers the transition from On to Off, provided the condition, [off_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 Conditions on page 7-63 for information on the condition notation.
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.
7-15
Notations
specified, is evaluated as true and before the transition destination has been determined to be valid. The condition action is executed as soon as the condition, if specified, is evaluated as true and before the entire transition is determined as valid. Enclose the condition action in curly brackets. See Action Language on page 7-37 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 [off_count==0] is true, the condition action, off_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 entire transition path to the final destination is determined as valid. Precede the transition action with a backslash. See Action Language on page 7-37 for more information on the action language.
In this example, if the condition [off_count==0] is true, and the destination state Off is valid, the transition action Light_off is executed.
Valid Transitions
In most cases, a transition is valid when the source state of the transition is active and the transition label is valid. Default transitions are slightly different because there is no source state. Validity of a default transition to a substate is evaluated when there is a transition to its superstate assuming the superstate is active. This labeling criterion applies to both default transitions and general case transitions. These are possible combinations of valid transition labels.
Transition Label Is Valid If:
That event occurs That event occurs and the condition is true Any event occurs and the condition is true
7-16
Transitions
Transition Label
Is Valid If:
Types of Transitions
The notation supports these transition types: Transitions to and from exclusive (OR) states See Example: Transitions to and from Exclusive (OR) States on page 7-18 for an example of this type of transition. Transitions to and from junctions See Example: Transitions to and from Junctions on page 7-18 for an example of this type of transition. Transitions to and from exclusive (OR) superstates See Example: Transitions to and from Exclusive OR Superstates on page 7-19 for an example of this type of transition. Transitions from no source to an exclusive (OR) state (default transitions) See Default Transitions on page 7-21 for examples of this type of transition. Inner state transitions See What Is an Inner Transition? on page 7-24 for examples of this type of transition. Self-loop transitions See What Is a Self-Loop Transition? on page 7-26 for examples of this type of transition.
7-17
Notations
The transition OnOff is valid when state On is active and the event Switch_off occurs. The transition OffOn is valid when state Off is active and event Switch_on occurs. See Transitions to and from Exclusive (OR) States on page 8-8 for more information on the semantics of this notation.
This is a Stateflow diagram of a soda machine. The Stateflow diagram is called when the external event Selection_made occurs. The Stateflow diagram
7-18
Transitions
awakens with the Waiting state active. The Waiting state is a common source state. When the event Selection_made occurs, the Stateflow diagram transitions from the Waiting state to one of the other states based on the value of the variable select. One transition is drawn from the Waiting state to the connective junction. Four additional transitions are drawn from the connective junction to the four possible destination states. See Example: Transitions from a Common Source to Multiple Destinations on page 8-37 for more information on the semantics of this notation.
This is an expansion of the soda machine Stateflow diagram that includes the initial example of the On and Off exclusive (OR) states. On is now a superstate containing the Waiting and soda choices states. The transition OffOn is valid when state Off is active and event Switch_on occurs. Now that On is a superstate, this is an explicit transition to the On superstate. To be a valid transition to a superstate, the destination substate must be implicitly defined. By defining that the Waiting substate has a default transition, the destination substate is implicitly defined. This notation defines that the resultant transition is Off On.Waiting.
7-19
Notations
The transition OnOff is valid when state On is active and event Switch_off occurs. When the Switch_off event occurs, no matter which of the substates of On is active, we want to transition to the Off 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 Default Transitions on page 8-18 for more information on the semantics of this notation.
Two of the substates of the On superstate are further defined to be superstates of their own. The Stateflow diagram shows a transition from one OR substate to another OR substate. The transition Waiting.ReadyOrange.In_motion is valid when state Waiting.Ready is active and event Selection_made occurs, providing that the select variable equals one. This transition defines an explicit exit from the Waiting.Ready state and an implicit exit from the Waiting superstate. On the destination side, this transition defines an implicit entry into the Orange superstate and an explicit entry into the Orange.In_motion substate. See Example: Transition from a Substate to a Substate on page 8-10 for more information on the semantics of this notation.
7-20
Transitions
Default Transitions
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 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 the toolbar, 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. One of the most common Stateflow programming mistakes is to create multiple exclusive (OR) states without a default transition. In the absence of the default transition, there is no indication 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 transition
Use a default transition to indicate, when entering this level in the hierarchy, which object becomes active by default.
7-21
Notations
Note When labeling default transitions, take care to ensure that there will always be at least one valid default transition. Otherwise, the state machine can transition into an inconsistent state.
When the Stateflow diagram is first awakened, the default transition to superstate S defines that of states S and B; the transition to state S is valid. State S has two substates, A and D. Which substate does the system transfer to? It cannot transfer to both of them since A 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 state B is active. The transition BS is valid. When the system enters state S, it enters substate D because the default transition is defined. See Default Transitions on page 8-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 run-time by checking for state inconsistencies. See Animation Controls on page 10-8 for more information.
7-22
Transitions
In this example, the default transition to the connective junction defines that upon entering the Counting state, the destination is determined by the condition on each transition segment. See Example: Default Transition to a Junction on page 8-19 for more information on the semantics of this notation.
7-23
Notations
If state A 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 the transition. If event e1 occurs, the transition AB1 is valid. If event e2 occurs, the transition AB2 is valid. See Example: Labeled Default Transitions on page 8-21 for more information on the semantics of this notation.
7-24
Transitions
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] is true, the transition to A1 is true. If [C_two] is true, the transition to A2 is valid. If neither [C_one] nor [C_two] is true, the transition to A3 is valid. The transitions among A1, A2, and A3 are determined by E_one, [C_one], and [C_two].
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] is true, the transition to A1 is valid. If [C_two] is true, the transition to A2 is valid. If neither [C_one] nor [C_two] is true, the transition to A3 is valid. This solution is much simpler than the previous one. See Example: Processing One Event with an Inner Transition to a Connective Junction on page 8-26 for more information on the semantics of this notation.
7-25
Notations
State Power_on.High is initially active. When event Reset occurs, the inner transition to the 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.High, 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 Example: Use of History Junctions on page 7-35 for another example using a history junction. See Example: Inner Transition to a History Junction on page 8-29 for more information on the semantics of this notation.
7-26
Transitions
See these sections for examples of self-loop transitions: Example: Connective Junction Special Case - Self-Loop on page 7-30 See the section Example: Self-Loop Transition on page 8-32 for information on the semantics of this notation. Example: Connective Junction and For Loops on page 7-31 See Example: For Loop Construct on page 8-33 for information on the semantics of this notation.
7-27
Notations
Connective Junctions
What Is a Connective Junction?
A connective junction is used to represent a decision point in the Stateflow diagram. The connective junction enables representation of different transition paths. Connective junctions are used to help represent: Variations of an if-then-else decision construct by specifying conditions on some or all of the outgoing transitions from the connective junction. A self-loop transition back to the source state if none of the outgoing transitions is valid. Variations of a for loop construct by having a self-loop transition from the connective junction back to itself. Transitions from a common source to multiple destinations. Transitions from multiple sources to a common destination. Transitions from a source to a destination based on common events
See Connective Junctions on page 8-31 for a summary of the semantics of connective junctions.
7-28
Connective Junctions
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.
See Example: If-Then-Else Decision Construct on page 8-31 for information on the semantics of this notation.
7-29
Notations
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 Example: If-Then-Else Decision Construct on page 8-31 for information on the semantics of this notation.
7-30
Connective Junctions
See Example: Self-Loop Transition on page 8-32 for information on the semantics of this notation.
7-31
Notations
is evaluated. Since there are no conditions, the transition completes at the destination, state B.
See Example: For Loop Construct on page 8-33 for information on the semantics of this notation.
7-32
Connective Junctions
[sensorValue >200] is true, the state Sensor.High is the destination. Otherwise, state Sensor.Normal is the destination state.
See Example: Flow Diagram Notation on page 8-35 for information on the semantics of this notation.
See Example: Transitions from a Common Source to Multiple Destinations on page 8-37 for information on the semantics of this notation.
7-33
Notations
See Example: Transitions from a Source to a Destination Based on a Common Event on page 8-39 for information on the semantics of this notation.
7-34
History Junctions
History Junctions
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 active. The history junction applies only to the level of the hierarchy in which it appears.
Superstate Power_on has a history junction and contains two substates. If state Power_off is active and event switch_on occurs, the system could enter either Power_on.Low or Power_on.High. The first time superstate Power_on is entered, substate Power_on.Low will be entered because it has a default transition. At some point afterwards, if state Power_on.High is active and event switch_off occurs, superstate Power_on is exited and state Power_off becomes active. Then event switch_on occurs. Since Power_on.High was the last active state, it becomes active again. After the first time Power_on becomes active, the choice between entering Power_on.Low or Power_on.High is determined by the history junction. See Example: Default Transition and a History Junction on page 8-19 for more information on the semantics of this notation.
7-35
Notations
See Example: Inner Transition to a History Junction on page 7-26 for an example of this notation. See Example: Inner Transition to a History Junction on page 8-29 for more information on the semantics of this notation.
7-36
Action Language
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 have entry, during, exit, and, onevent_name actions. An action can be a 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.
Condition action
7-37
Notations
Transitions to States
The general label format for a transition entering a state is shown below.
condition_action is executed.
4 If the destination state is determined to be a valid destination, the transition
is taken.
5 State S1 is exited. 6 The transition action transition_action is executed when the transition is
taken.
7 State S2 is entered.
7-38
Action Language
is executed.
4 The outgoing transitions from the junction are checked for a valid transition.
7-39
Notations
The / (forward slash) following the state name is optional. See Semantics of State Actions on page 8-7 for information on the semantics of state actions. See the examples of the semantics of state actions in Chapter 8, Semantics.
7-40
Action Language
Keywords
These Stateflow keywords have special meaning in the notation.
Keyword change(data_name) Shorthand chg(data_name) Meaning
Generates a local event when the value of data_name changes. Actions that follow are executed as part of a states during action. Actions that follow are executed as part of a states entry action. Generates a local event when the specified state_name is entered. Actions that follow are executed as part of a states exit action. Generates a local event when the specified state_name is exited. A condition function that is evaluated as true when the state_name specified as the argument is active. Actions that follow are executed when the event_name specified as an argument to the on keyword is broadcast.
during
du
entry
en
entry(state_name)
en(state_name)
exit
ex
exit(state_name)
ex(state_name)
in(state_name)
none
on event_name
none
7-41
Notations
Keyword send(event_name,state_name)
Shorthand
Meaning
none
Send the event_name specified to the state_name specified (directed event broadcasting). Action specifies a call using MATLAB function notation. Action specifies a call using the ml name space notation.
matlab(evalString,arg1,arg2,...)
ml()
matlab.MATLAB_workspace_data
ml.
Note Use of these keywords in any way other than their intended meaning within the rules of the notation will cause unpredictable results.
7-42
Action Language
Event Broadcasting on page 7-59 Directed Event Broadcasting on page 7-61 Conditions on page 7-63 Time Symbol on page 7-64 Literals on page 7-64 Continuation Symbols on page 7-65 Comments on page 7-65 Use of the Semicolon on page 7-65 Temporal Logic Operators on page 7-65 Temporal Logic Events on page 7-71
Bit Operations
To enable support for bit operations, check the Enable C-like bit operations check box in the properties dialog for the chart. See the section Specifying Chart Properties on page 3-46. If you have C-like bit operations enabled, some of the logical binary operators and unary operators are interpreted as bitwise operators. See individual operators in sections Binary Operations on page 7-44 and Unary Operations on page 7-46 for specific interpretations.
7-43
Notations
Binary Operations
Binary operators differ in interpretation depending on whether you check or uncheck the Enable C-like bit operations field in the properties dialog for the chart. See the section Specifying Chart Properties on page 3-46. The following table summarizes the interpretation of all binary operators in Stateflow action language. Table order gives relative operator precedence (column Prec in table); highest precedence (10) is at the top of the table. Binary operators are evaluated left to right (left associative).
Example a * b Prec 10 C-Like Bit Ops Enabled C-Like Bit Ops Disabled
Multiplication of two operands Division of one operand by the other Modulus Addition of two operands Subtraction of one operand from the other Shift operand a right by b bits. (See * note below.) Shift operand a left by b bits. (See * note below.) Comparison of the first operand greater than the second operand Comparison of the first operand less than the second operand
a / b
10
a %% b a + b a - b
10 9 9
a >> b
a << b
Same
a > b
Same
a < b
Same
7-44
Action Language
Example a >= b
Prec 7
Comparison of the first operand greater than or equal to the second operand Comparison of the first operand less than or equal to the second operand Comparison of equality of two operands Comparison of inequality of two operands Comparison of inequality of two operands Comparison of inequality of two operands Bitwise AND of two operands Bitwise XOR of two operands
Same
a <= b
Same
a == b
Same Same Same Same Logical AND of two operands Operand a raised to power b. (See ** note below table.) Logical OR of two operands Same Same
a ~= b
a != b
a <> b
a & b
a ^ b
a | b
Bitwise OR of two operands Logical AND of two operands Logical OR of two operands
a && b
a || b
7-45
Notations
Note * Noninteger operands for the >> and << bit shift operators are first cast to integers before the bits are shifted.
Note ** Use parentheses around power expressions with the ^ operator when used in conjunction with other arithmetic operators. This avoids problems with operator precedence. For example, the action z=x^2+y^2 should be rewritten as z=(x^2)+(y^2).
Unary Operations
The following unary operators are supported in Stateflow action language. Unary operators have higher precedence than binary operators and are evaluated right to left (right associative).
Example ~a Description
!a -a
Unary Actions
The following unary actions are supported in Stateflow action language.
Example a++ a-Description
Increment a Decrement a
7-46
Action Language
Assignment Operations
The following assignment operations are supported in Stateflow action language.
Example a = expression a += expression a -= expression a *= expression a /= expression Description
Simple assignment Equivalent to a = a + expression Equivalent to a = a - expression Equivalent to a = a * expression Equivalent to a = a / expression
The following assignment operations are supported in Stateflow action language when the Enable C-like bit operations check box is checked in the properties dialog for the chart. See section Specifying Chart Properties on page 3-46.
Example a |= expression a &= expression a ^= expression Description
Equivalent to a = a | expression (bit operation) Equivalent to a = a & expression (bit operation) Equivalent to a = a ^ expression (bit operation)
7-47
Notations
You can call the above C Math Library functions without doing anything special as long as you are careful to call them with the right data types. If you call other C library functions not specified above, be sure to include the appropriate #include... directive in the Custom code included at the top of generated code field of the Target Options dialog. See the section Specifying Custom Code Options on page 9-25.
To allow compatibility with user graphical functions named min() or max(), Stateflow generates code for them with a mangled name of the following form: <prefix>_min. However, if you export min() or max() graphical functions to other Stateflow charts in the Stateflow machine, the name of these functions can no longer be emitted with mangled names in generated code and conflict occurs. To avoid this conflict, rename the min() and max() graphical functions.
Include a header file containing the declarations of your C code functions in the Custom code included at the top of generated code field. Specify the source file name containing your C code functions in the Custom source files field. See section Specifying Custom Code Options on page 9-25 To use your own C code functions in Stateflow action language, follow these guidelines:
7-48
Action Language
Define a function by its name, any arguments in parenthesis, and an optional semicolon. String parameters to user-written functions are passed between single quotes. For example, func( string ). An action can nest function calls. An action can invoke functions that return a scalar value (of type double in the case of MATLAB functions and of any type in the case of C user-written functions).
If S1 is active, event e occurs, c is true, and the transition destination is determined, then a function call is made to function_name with arg1, arg2, and arg3. The transition action in the transition from S2 to S3 shows a function call nested within another function call.
7-49
Notations
When the default transition into S1 occurs, S1 is marked active and then its entry action, a function call to function_name1 with the specified arguments, is executed and completed. If S2 is active and an event occurs, the during action, a function call to function_name3 with the specified arguments, executes and completes.
where f is a custom-code C function that expects a pointer to x as an argument. If x is the name of a data item defined in the Stateflow data dictionary, the following rules apply. Do not use pointers to pass data items input from Simulink. If you need to pass an input item by reference, for example, an array, assign the item to a local data item and pass the local item by reference. If x is a Simulink output data item having a data type other than double, the chart property Use strong data typing with Simulink IO must be on (see Specifying Chart Properties on page 3-46).
7-50
Action Language
If the data type of x is boolean, the coder option Use bitsets to store state-configuration must be turned off (see Use bitsets for storing state configuration on page 9-13). If x is an array with its first index property set to zero (see Array on page 4-19), then the function must be called as follows.
f(&(x[0]));
This will pass a pointer to the first element of x to the function. If x is an array with its first index property set to a non-zero number (for example, 1), the function must be called in the following way.
f(&(x[1]));
ml() Functions
You can specify calls to MATLAB functions that return scalars (of type double) in the action language.
where the return value is scalar (of type double). If the result returned is: A vector, then the first element is returned. A void, then an appropriate format must be used (an assignment statement cannot be used). A string, a structure, or a cell array, then the behavior is undefined.
evalString is a string that is evaluated in the MATLAB workspace with formatted substitutions of arg1, arg2, arg3, etc.
7-51
Notations
If S1 is active, an event occurs, and if [c_one] is true, the expression sin(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 run-time error is generated.
These data objects are defined: d1 and a are Local data objects of type double in the Stateflow diagram
7-52
Action Language
d2 is an Output to Simulink data object of type integer in the Stateflow diagram 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 run-time error is generated. These three values are passed as arguments to a user-written function. The %g and %d characters are format specifiers that print the current values of d1 and d2 into evalString 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.
These data objects are defined in the Stateflow diagram: d1 is a Local data object of type double 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 d1 and d2 into evalString at appropriate locations. Notice that the string is enclosed in two single quotes.
Use Guidelines
These guidelines apply to ml() functions: The first argument must be a string.
7-53
Notations
If there are multiple arguments, ensure that the number and types of format specifiers (%g, %d, etc.) match the actual number and types of the arguments. These format specifiers are the same as those used in the C function printf. A scalar (of type double) is returned. ml() function calls can be nested. Calls to ml() functions should be avoided if you plan to build an RTW target that includes code from Stateflow Coder.
These data objects are defined in the Stateflow diagram: d1 and d2 are Local data objects
7-54
Action Language
a, x, and y must be defined in the MATLAB workspace prior to starting the simulation; otherwise a run-time error is generated at the execution time of the transition The values of a and y 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 variable x. If x does not exist, it is automatically created in the MATLAB workspace.
These data objects are defined: d1 and d2 are Local data objects defined in the Stateflow diagram. x is assumed to be a two dimensional array in the MATLAB workspace. y is assumed to be a MATLAB workspace vector. z is assumed to be a MATLAB workspace scalar variable.
x, y, and z must be defined in the MATLAB workspace prior to starting the simulation; otherwise a run-time error is generated at the execution time of the transition.
7-55
Notations
5 d2 6 string 'abcdefgh'
The result of my_func() (if it is a scalar) is assigned to element (5, 6, 7) of a multidimensional matrix v in the MATLAB workspace. If v does not exist prior to the execution of this statement, then it is automatically created by MATLAB workspace. If my_func() returns a vector, the first element is assigned to v(5,6,7). If it is a structure, a cell array, or a string, the result is undefined.
Arrays
You can use arrays in the action language.
7-56
Action Language
As an exception to this style, scalar expansion is available within the action language. This statement assigns a value of 10 to all of the elements of the array local_array.
local_array = 10;
Scalar expansion is available for performing general operations. This statement is valid if the arrays array_1, array_2 and array_3 have the same value for the Sizes property.
array_1 = (3*array_2) + array_3;
Syntax Examples
These examples show syntax that is valid for use with custom code variables only.
varStruct.field = <expression>; (*varPtr) = <expression>;
7-57
Notations
varPtr->field = <expression>; myVar = varPtr->field; varPtrArray[index]->field = <expression>; varPtrArray[expression]->field = <expression>; myVar = varPtrArray[expression]->field;
These examples show syntax that is valid for use with both custom code variables and Stateflow variables.
varPtr = &var; ptr = &varArray[<expression>]; *(&var) = <expression>; function(&varA, &varB, &varC); function(&sf.varArray[<expr>]);
Hexadecimal Notation
The action language supports C style hexadecimal notation (for example, 0xFF). You can use hexadecimal values wherever you can use decimal values.
7-58
Action Language
Typecast Operators
A typecast operator converts a value to a specified data type. Stateflow typecast operators have the same notation as MATLAB typecast operators
op(v)
where op is the typecast operator (e.g, int8, int16, int32, single, double) and v is the value to be converted. Normally you do not need to use typecast operators in actions. This is because Stateflow checks whether the types involved in a variable assignment differ and, if so, inserts a typecast operator in the generated code. (Stateflow uses the typecast operator of the language in which the target is generated, typically C.) However, if external code defines either or both types, Stateflow cannot determine which typecast, if any, is required. If a type conversion is necessary, you must use a Stateflow action language typecast operator to tell Stateflow which target language typecast operator to generate. For example, suppose varA is a data dictionary value of type double and y is an external variable of type 32-bit integer. The following notation
y = int32(varA)
tells Stateflow to generate a typecast operator that converts the value of varA to a 32-bit integer before the value is assigned to y.
Event Broadcasting
You can specify an event to 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 events parent that determines who can trigger on the event (has receive rights). See Name on page 4-5 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.
7-59
Notations
See Example: Event Broadcast State Action on page 8-44 for information on the semantics of this notation.
7-60
Action Language
See Example: Event Broadcast Transition Action (Nested Event Broadcast) on page 8-48 for information on the semantics of this notation.
Note An action in one chart cannot broadcast events to states defined in another chart.
where event_name is broadcast to state_name (and any offspring of that state in the hierarchy). The state_name argument can include a full hierarchy path. For example,
send(event_name, chart_name.state_name1.state_name2)
The state_name specified must be active at the time the send is executed for the state_name to receive and potentially act on the directed event broadcast.
7-61
Notations
In this example, event E_one must be visible in both A and B. See Example: Directed Event Broadcasting Using Qualified Event Names on page 8-58 for information on the semantics of this notation.
7-62
Action Language
See Example: Directed Event Broadcasting Using Qualified Event Names on page 8-58 for information on the semantics of this notation.
Conditions
You sometimes want transitions or actions associated with transitions to take place only if a certain condition is true. Conditions are placed within [ ]. These are some guidelines for defining conditions: The expression must be a Boolean expression of some kind. The condition must evaluate to either true (1) or false (0). The expression can consist of: - Boolean operators that make comparisons between data and numeric values
7-63
Notations
- Any function that returns a Boolean value - The In(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.
Note A chart cannot use the In condition function to trigger actions based on the activity of states in other charts.
- Temporal conditions (see Temporal Logic Operators on page 7-65) The condition expression should not call a function that causes the Stateflow diagram to change state or modify any variables. Boolean expressions can be grouped using & for expressions with AND relationships and | for expressions with OR relationships. Assignment statements are not valid condition expressions. 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 > Duration] specifies that the condition is true if the value of On_time subtracted from the simulation time t, 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 target hardware.
Literals
Place action language you want the parser to ignore but you want to appear as entered in the generated code within $ characters. For example,
$ ptr -> field = 1.0; $
The parser is completely disabled during the processing of anything between the $ characters. Frequent use of literals is discouraged.
7-64
Action Language
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: % MATLAB comment line // C++ comment line /* C comment line */
Usage Rules
The following rules apply generally to use of temporal logic operators: The recurring event on which a temporal operator operates is called the base event. Any Stateflow event can serve as a base event for a temporal operator. Note that temporal logic operators can also operate on recurrences of implicit events, such as state entry or exit events. For a chart with no Simulink input events, you can use the wakeup (or tick) event to denote the implicit event of a chart waking up.
7-65
Notations
Temporal logic operators can appear only in conditions on transitions originating from states and in state actions. Note that this means you cannot use temporal logic operators as conditions on default transitions or flow graph transitions. The state on which the temporally conditioned transition originates or in whose during action the condition appears is called the temporal operators associated state. You must use event notation (see Temporal Logic Events on page 7-71) to express temporal logic conditions on events in state during actions. The following diagram illustrates the usage and terminology that apply to temporal logic operators.
Event Notation
Base Event
Conditional Notation
Associated State
After Operator
Syntax
after(n, E)
where E is the base event for the operator and n is one of the following: A constant integer greater than 0
7-66
Action Language
Semantics
The after operator is true if the base event E has occurred n times since the operators associated state was activated. Otherwise, it is false. In a chart with no input events, after(n,wakeup) (or after(n,tick)) evaluates to true after the chart has woken up n times.
Note The after operator resets its counter for E to 0 each time the associated state is activated.
Usage
The following example illustrate use of the after operator in a transition expression.
CLK[after(10, CLK) && temp == COLD]
This example permits a transition out of the associated state only if there have been 10 occurrences of the CLK event since the state was activated and the temp data item has the value COLD. The next example illustrates usage of event notation for temporal logic conditions in transition expressions.
after(10, CLK)[temp == COLD]
This example is semantically equivalent to the first example. The next example illustrates setting a transition condition for any event visible in the associated state while it is activated.
[after(10, CLK)]
This example permits a transition out of the associated state on any event after 10 occurrences of the CLK event since activation of the state. The next two examples underscore the semantic distinction between an after condition on its own base event and an after condition on a nonbase event.
CLK[after(10,CLK)] ROTATE[after(10,CLK]
7-67
Notations
The first expression says that the transition must occur as soon as 10 CLK events have occurred after activation of the associated state. The second expression says that the transition may occur no sooner than 10 CLK events after activation of the state, but possibly later, depending on when the ROTATION event occurs. The next example illustrates usage of an after event in a states during action.
Heater_on on after(5*BASE_DELAY, CLK): status('heater on');
This example causes the Heater_on state to display a status message each CLK cycle, starting 5*BASE_DELAY clock cycles after activation of the state. Note the use of event notation to express the after condition in this example. Use of conditional notation is not allowed in state during actions.
Before Operator
Syntax
before(n, E)
where E is the base event for the operator and n is one of the following: A constant integer greater than 0 An expression that evaluates to an integer value greater than or equal to 0
Semantics
The before operator is true if the base event E has occurred less than n times since the operators associated state was activated. Otherwise, it is false. In a chart with no input events, before(n,wakeup) or (before(n,tick)) evaluates to true before the chart has woken up n times.
Note The before operator resets its counter for E to 0 each time the associated state is activated.
Usage
The following example illustrate use of the before operator in a transition expression.
7-68
Action Language
ROTATION[before(10, CLK)]
This expression permits a transition out of the associated state only on occurrence of a ROTATION event but no later than 10 CLK cycles after activation of the state. The next example illustrates usage of a before event in a states during action.
Heater_on on before(MAX_ON_TIME, CLK): temp++;
This example causes the Heater_on state to increment the temp variable once per CLK cycle until the MAX_ON_TIME limit is reached.
At Operator
Syntax
at(n, E)
where E is the base event for the at operator and n is one of the following: A constant integer greater than 0 An expression that evaluates to an integer value greater than or equal to 0
Semantics
The at operator is true only at the nth occurrence of the base event E since activation of the associated state. Otherwise, it is false. In a chart with no input events, at(n,wakeup) (or at(n,tick)) evaluates to true when the chart wakes up for the nth time.
Note The at operator resets its counter for E to 0 each time the associated state is activated.
Usage
The following example illustrate use of the at operator in a transition expression.
ROTATION[at(10, CLK)]
7-69
Notations
This expression permits a transition out of the associated state only if a ROTATION event occurs exactly 10 CLK cycles after activation of the state. The next example illustrates usage of a before event in a states during action.
Heater_on on at(10, CLK): status( heater on );
This example causes the Heater_on state to display a status message 10 CLK cycles after activation of the associated state.
Every Operator
Syntax
every(n, E)
where E is the base event for the at operator and n is one of the following: A constant integer greater than0 An expression that evaluates to an integer value greater than or equal to 0
Semantics
The every operator is true at every nth occurrence of the base event E since activation of the associated state. Otherwise, it is false. In a chart with no input events, every(n,wakeup) (or every(n,tick)) evaluates to true whenever the chart wakes up an integer multiple n times.
Note The every operator resets its counter for E to 0 each time the associated state is activated. As a result, this operator is useful only in state during actions.
Usage
The following example illustrates the use of the at operator in a state.
Heater_on on every(10, CLK): status( heater on ;
7-70
Action Language
This example causes the Heater_on state to display a status message every 10 CLK cycles after activation of the associated state.
where to is a temporal operator (after, before, at, every), E is the operators base event, n is the operators occurrence count, and C is any conditional expression. For example, the following expressions are functionally equivalent in Stateflow.
CLK[after(10, CLK) && temp == COLD] after(10, CLK)[temp == COLD]
The first notation is referred to as the conditional notation for temporal logic operators and the second notation as the event notation.
Note You can use conditional and event notation interchangeably in transition expressions. However, you must use the event notation in state during actions.
Although temporal logic does not introduce any new events into a Stateflow model, it is useful to think of the change of value of a temporal logic condition as an event. For example, suppose that you want a transition to occur from state A exactly 10 clock cycles after activation of the state. One way to achieve this would be to define an event called ALARM and to broadcast this event 10 CLK events after state A is entered. You would then use ALARM as the event that triggers the transition out of state A. An easier way to achieve the same behavior is to set a temporal logic condition on the CLK event that triggers the transition out of state A.
CLK[after(10, CLK)]
Note that this approach does not require creation of any new events. Nevertheless, conceptually it is useful to think of this expression as equivalent
7-71
Notations
to creation of an implicit event that triggers the transition. Hence, Stateflows support for the equivalent event notation.
after(10, CLK)
Note that the event notation allows you to set additional constraints on the implicit temporal logic event, for example,
after(10, CLK)[temp == COLD]
This expression says, Exit state A if the temperature is cold but no sooner than 10 clock cycles.
7-72
8
Semantics
Overview . . . . . . . . . . . . . . . . . . . . . 8-2 Event-Driven Effects on Semantics . . . . . . . . . . 8-5 Transitions to and from Exclusive (OR) States Condition Actions . . . . 8-8
. . . . . . . . . . . . . . . . . 8-13
Semantics
Overview
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 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. Stateflow semantics consist of rules for: Event broadcasting Processing states Processing transitions 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 8-64 for a summary of the semantics.
Condition Actions
Example: Actions Specified as Condition Actions on page 8-13
8-2
Overview
Example: Actions Specified as Condition and Transition Actions on page 8-14 Example: Using Condition Actions in For Loop Construct on page 8-15 Example: Using Condition Actions to Broadcast Events to Parallel (AND) States on page 8-16 Example: Cyclic Behavior to Avoid When Using Condition Actions on page 8-17
Default Transitions
Example: Default Transition in an Exclusive (OR) Decomposition on page 8-18 Example: Default Transition to a Junction on page 8-19 Example: Default Transition and a History Junction on page 8-19 Example: Labeled Default Transitions on page 8-21
Inner Transitions
Example: Processing One Event Within an Exclusive (OR) State on page 8-23 Example: Processing a Second Event Within an Exclusive (OR) State on page 8-24 Example: Processing a Third Event Within an Exclusive (OR) State on page 8-25 Example: Processing One Event with an Inner Transition to a Connective Junction on page 8-26 Example: Processing a Second Event with an Inner Transition to a Connective Junction on page 8-28 Example: Inner Transition to a History Junction on page 8-29
Connective Junctions
Example: If-Then-Else Decision Construct on page 8-31 Example: Self-Loop Transition on page 8-32 Example: For Loop Construct on page 8-33 Example: Flow Diagram Notation on page 8-35
8-3
Semantics
Example: Transitions from a Common Source to Multiple Destinations on page 8-37 Example: Transitions from Multiple Sources to a Common Destination on page 8-38 Example: Transitions from a Source to a Destination Based on a Common Event on page 8-39
Event Actions
Example: Event Actions and Superstates on page 8-42
8-4
Initially the Stateflow diagram is asleep and both states are inactive. 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
8-5
Semantics
2 State A is marked active. 3 State A entry actions execute and complete (entA()). 4 The Stateflow diagram goes back to sleep waiting to be awakened 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
8-6
Semantics of Transitions
Transitions play a large role in 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.
8-7
Semantics
Initially the Stateflow diagram is asleep. State On and state Off are OR states. State On 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
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 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 State Off entry actions execute and complete (entOff()).
8-8
event. This sequence completes the execution of the Stateflow diagram associated with event E_one when state On was active.
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 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
event.
8-9
Semantics
This sequence completes the execution of the Stateflow diagram associated with the second event E_one when state Off was active.
Again, initially the Stateflow diagram is asleep. State On is active. Event E_two occurs and awakens the Stateflow diagram. Event E_two 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
event. This sequence completes the execution of the Stateflow diagram associated with event E_two when State On was active.
8-10
State A1 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 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. There is a valid transition from state A.A1 to state B.B1. (Condition C_one is true.)
2 State A executes and completes during actions (durA()). 3 State A.A1 executes and completes exit actions (exitA1()). 4 State A.A1 is marked inactive. 5 State A executes and completes exit actions (exitA()). 6 State A is marked inactive. 7 The transition action, A, is executed and completed. 8 State B is marked active. 9 State B executes and completes entry actions (entB()). 10 State B.B1 is marked active.
8-11
Semantics
1 State B.B1 executes and completes entry actions (entB1()). 1 1 The Stateflow diagram goes back to sleep waiting to be awakened by another 2
event. This sequence completes the execution of this Stateflow diagram associated with event E_one.
8-12
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.
State A is active.
Initially the Stateflow diagram is asleep. State A is active. Event E_one occurs and awakens the Stateflow diagram. Conditions C_one and C_two are false. 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 segment from state A to a connective junction is detected. The condition action, A_one, is detected on the valid transition segment and is immediately executed and completed. State A is still active.
2 Since the conditions on the transition segments to possible destinations are
(durA()).
8-13
Semantics
event. This sequence completes the execution of the Stateflow diagram associated with event E_one when state A was active.
Initially the Stateflow diagram is asleep. State A is 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 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 A to state B is detected. The condition, C_one is true. The condition action, A_one, is detected on the valid transition and is immediately executed and completed. State A is still active.
2 State A exit actions execute and complete (ExitA()). 3 State A is marked inactive. 4 The transition action, A_two, is executed and completed. 5 State B is marked active.
8-14
Condition Actions
6 State B entry actions execute and complete (entB()). 7 The Stateflow 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_one when state A was active.
See Example: For Loop Construct on page 8-33 to see the semantics of this example.
8-15
Semantics
State A1a
is active.
See Example: Event Broadcast Condition Action on page 8-52 to see the semantics of this example.
8-16
Condition Actions
Initially the Stateflow diagram is asleep. State On 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. A valid transition from state On to state Off is detected. A condition action, broadcast of event E_one, is detected on the valid transition and is immediately executed. State On is still active. 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 transition as a result of E_one. The transition from state On to state Off is still valid. The condition action, broadcast of event E_one, is immediately executed again.
2 Step 1 continues to execute in a cyclical manner. The transition label
indicating 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 On is active.
8-17
Semantics
Default Transitions
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.
State A is active.
Initially the Stateflow diagram is asleep. State 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 as a
8-18
Default Transitions
event. This sequence completes the execution of this Stateflow diagram associated with event E_one.
State B1 is active.
Initially the Stateflow diagram is asleep. State B.B1 is active. An event occurs and awakens the Stateflow diagram. Condition [C_two] is true. The event is processed from the root of the Stateflow diagram down through the hierarchy of the Stateflow diagram:
1 State B checks to see if there is a valid transition as a result of any event.
There is none.
2 State B1 during actions execute and complete (durB1()).
This sequence completes the execution of this Stateflow diagram associated with the occurrence of any event.
8-19
Semantics
State A is active.
Initially the Stateflow diagram is asleep. State A is active. There is a history junction and state B4 was the last active substate of superstate B. 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
the destination of the transition into the superstate. The history junction indicates substate B.B4 was the last active substate, and thus the destination of the transition.
7 State B.B4 is marked active.
8-20
Default Transitions
8 State B.B4 entry actions execute and complete (entB4()). 9 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.
Initially the Stateflow diagram is asleep. State A is active. Event E_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:
8-21
Semantics
result of E_one. There is 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 State A exit actions execute and complete (exitA()). 3 State A is marked inactive. 4 State B is marked active. 5 State B entry actions execute and complete (entB()). 6 State B detects a valid default transition to state B.B1. The default transition
event. This sequence completes the execution of this Stateflow diagram associated with event E_one.
8-22
Inner Transitions
Inner Transitions
Example: Processing One Event Within an Exclusive (OR) State
This example shows the semantics of an inner transition.
State A is active.
Initially the Stateflow diagram is asleep. State A is active. Event E_one occurs and awakens the Stateflow diagram. Condition [C_one] is false. 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 potentially valid transition from state A to state B is detected. However the transition is not valid because [C_one] is false.
2 State A during actions execute and complete (durA()). 3 State A checks its children for a valid transition and detects a valid inner
transition.
4 State A remains active. The inner transition action, A_two, is executed and
completed. Because it is an inner transition, state As exit and entry actions are not executed.
5 The Stateflow diagram goes back to sleep waiting to be awakened by another
event.
8-23
Semantics
This sequence completes the execution of this Stateflow diagram associated with event E_one.
Initially the Stateflow diagram is asleep. State A 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 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. The transition from state A to state B is now valid because [C_one] is true.
2 State A exit actions execute and complete (exitA()). 3 State A is marked inactive. 4 The transition action A_one is executed and completed. 5 State B is marked active. 6 State B entry actions execute and complete (entB()). 7 The Stateflow diagram goes back to sleep waiting to be awakened by another
event.
8-24
Inner Transitions
This sequence completes the execution of this Stateflow diagram associated with event E_one.
Initially the Stateflow diagram is asleep. State B is now active. Event E_two occurs and awakens the Stateflow diagram. Condition [C_two] is false. Event E_two 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_two. A potentially valid transition from state B to state A is detected. The transition is not valid because [C_two] is false. However, active state B has a valid self-loop transition.
2 State B exit actions execute and complete (exitB()). 3 State B is marked inactive. 4 The self-loop transition action, A_four, executes and completes. 5 State B is marked active. 6 State B entry actions execute and complete (entB()).
8-25
Semantics
event. This sequence completes the execution of this Stateflow diagram associated with event E_two. This example shows the difference in semantics between inner transitions and self-loop transitions.
Initially the Stateflow diagram is asleep. State A1 is active. Event E_one occurs and awakens the Stateflow diagram. Condition [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
8-26
Inner Transitions
3 State A checks itself for valid transitions and detects there is a valid inner
transition to a connective junction. The conditions are evaluated to determine if one of the transitions is valid. The segments labeled with a condition are evaluated before the unlabeled segment. The evaluation starts from a twelve oclock position on the junction and progresses in a clockwise manner. Since [C_two] is true, the inner transition to the junction and then to state A.A2 is valid.
4 State A.A1 exit actions execute and complete (exitA1()). 5 State A.A1 is marked inactive. 6 State A.A2 is marked active. 7 State A.A2 entry actions execute and complete (entA2()). 8 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 condition C_two is true.
8-27
Semantics
State A2 is active.
Initially the Stateflow diagram is asleep. State A2 is active. Event E_one occurs and awakens the Stateflow 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
to a connective junction. The segments labeled with a condition are evaluated before the unlabeled segment. The evaluation starts from a twelve oclock 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.
4 State A.A2 exit actions execute and complete (exitA2()).
8-28
Inner Transitions
5 State A.A2 is marked inactive. 6 State A.A3 is marked active. 7 State A.A3 entry actions execute and complete (entA3()). 8 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.
State A1 is active.
Initially the Stateflow diagram is asleep. State A.A1 is active. There is 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 as a
8-29
Semantics
3 State A checks itself for valid transitions and detects there is a valid inner
transition to a history junction. According to the semantics of history junctions, the last active state, A.A1, is the destination state.
4 State A.A1 exit actions execute and complete (exitA1()). 5 State A.A1 is marked inactive. 6 State A.A1 is marked active. 7 State A.A1 entry actions execute and complete (entA1()). 8 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 there is an inner transition to a history junction and state A.A1 is active.
8-30
Connective Junctions
Connective Junctions
Example: If-Then-Else Decision Construct
This example shows the semantics of an if-then-else decision construct.
State A is active.
Initially the Stateflow diagram is asleep. State A is active. Event E_one occurs and awakens the Stateflow diagram. Condition [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 as a
result of E_one. There is a valid transition segment from state A to the connective junction. The transition segments beginning from a twelve oclock position on the connective junction are evaluated for validity. The first transition segment labeled with condition [C_one] is not valid. The next transition segment labeled with the condition [C_two] is valid. The complete transition from state A to state C is valid.
2 State A executes and completes exit actions (exitA()). 3 State A is marked inactive.
8-31
Semantics
4 State C is marked active. 5 State C executes and completes entry actions (entC()). 6 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.
Initially the Stateflow diagram is asleep. State A is active. Event E_one occurs and awakens the Stateflow diagram. Condition [C_one] is false. 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. There is 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 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 State A executes and completes exit actions (exitA()). 3 State A is marked inactive.
8-32
Connective Junctions
4 The transition action A_two is executed and completed. 5 State A is marked active. 6 State A executes and completes entry actions (entA()). 7 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.
Initially the Stateflow diagram is asleep. State 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 as a
result of E_one. There is a valid transition segment from state A to the connective junction. The transition segment condition action, i = 0, is 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.
8-33
Semantics
2 The condition [i < 10 ] is evaluated as true. The condition actions, i++, and
a call to func1 are executed and completed until the condition becomes false. A connective junction is not a final destination; thus the transition destination remains to be determined.
3 The unconditional segment to state B is now valid. The complete transition
event. This sequence completes the execution of this Stateflow diagram associated with event E_one.
8-34
Connective Junctions
Initially the Stateflow diagram is asleep. State A.A1 is active. The condition [C_one()] is initially true. 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
to a connective junction.
3 The next possible segments of the transition are evaluated. There is 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
transitions; one is a conditional self-loop transition and the other is an unconditional transition segment. The conditional transition segment takes precedence. The condition [C_one()] is tested and is true; the self-loop transition is taken. Since a final transition destination has not been
8-35
Semantics
reached, this self-loop continues until [C_one()] is false. Assume that after five loops [C_one()] is false.
5 The next possible transition segment (to the next connective junction) is
evaluated. It is an unconditional transition segment with a condition action. The transition segment is taken and the condition action, {d=my_func()}, is executed and completed. The returned value of d is 84.
6 The next possible transition segment is evaluated. There are three possible
outgoing transition segments to consider. Two are conditional; one is unconditional. The segment labeled with the condition [d<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<100] is true and this transition (to the destination state A.A1) is valid.
7 State A.A1 exit actions execute and complete (exitA1()). 8 State A.A1 is marked inactive. 9 State A.A1 is marked active. 1 State A.A1 entry actions execute and complete (entA1()). 0 1 The Stateflow diagram goes back to sleep waiting to be awakened by another 1
event. This sequence completes the execution of this Stateflow diagram associated with event E_one.
8-36
Connective Junctions
State A is active.
Initially the Stateflow diagram is asleep. State A is active. Event E_two occurs and awakens the Stateflow diagram. Event E_two 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_two. There is a valid transition segment from state A to the connective junction. Given that the transition segments are equivalently labeled, evaluation begins from a twelve oclock 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 State A executes and completes exit actions (exitA()). 3 State A is marked inactive. 4 State C is marked active. 5 State C executes and completes entry actions (entC()). 6 The Stateflow diagram goes back to sleep waiting to be awakened by another
event.
8-37
Semantics
This sequence completes the execution of this Stateflow diagram associated with event E_two.
Initially the Stateflow diagram is asleep. State 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 as a
result of E_one. There is a valid transition segment from state A to the connective junction and from the junction to state C.
2 State A executes and completes exit actions (exitA()). 3 State A is marked inactive. 4 State C is marked active. 5 State C executes and completes entry actions (entC()). 6 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.
8-38
Connective Junctions
State B is active.
Initially the Stateflow diagram is asleep. State B 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. There is a valid transition segment from state B to the connective junction and from the junction to state C.
2 State B executes and completes exit actions (exitB()). 3 State B is marked inactive. 4 State C is marked active. 5 State C executes and completes entry actions (entC()). 6 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.
8-39
Semantics
Initially, state A is active and conditions c1, c2, and c3 are true:
1 The Stateflow diagram root checks to see if there is a valid transition from
state A. There is a valid transition segment from state A to a connective junction marked with the condition c1.
2 Condition c1 is true, therefore action a1 is executed. 3 Condition c3 is true, therefore action a3 is executed. 4 Condition c4 is not true, therefore control flow is back-tracked to state A. 5 The Stateflow diagram root checks to see if there is another valid transition
from state A. There is a valid transition segment from state A to a connective junction marked with the condition c2.
6 Condition c2 is true, therefore action a2 is executed. 7 Condition c3 is true, therefore action a3 is executed. 8 Condition c4 is not true, therefore control flow is back-tracked to state A. 9 The Stateflow chart goes to sleep.
The above example shows the unanticipated behavior of executing both actions
a1 and a2 and action a3 twice. To resolve this problem, consider the following.
8-40
Connective Junctions
State A is active.
In this example, the previous example is amended with two terminating junctions that allow flow to terminate if either c3 or c4 are not true. This leaves state A active without taking any unnecessary actions.
8-41
Semantics
Event Actions
Example: Event Actions and Superstates
This example shows the semantics of event actions within superstates.
State A1 is active.
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
transitions.
5 State A1 executes and completes during actions (durA1()).
8-42
Event Actions
event. This sequence completes the execution of this Stateflow diagram associated with event E_three.
8-43
Semantics
Initially the Stateflow diagram is asleep. Parallel substates A.A1.A1a 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 at the
executed from left to right and top to bottom. State A.A1 is evaluated first.
8-44
State A.A1 executes and completes during actions (durA1()). State A.A1 executes and completes the on 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_two awakens the Stateflow diagram a second
time. The Stateflow diagram root checks to see if there is a valid transition as a result of E_two. There is 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 transitions. executes and completes during actions (durA1()). State A.A1 is evaluated for valid transitions. There are no valid transitions as a result of E_two within state A1.
d State A s children are evaluated starting with state A.A1. State A.A1
State A.A2 is evaluated. State A.A2 executes and completes during actions (durA2()). State A.A2 checks for valid transitions. State A.A2 has a valid transition as a result of E_two from state A.A2.A2a to state A.A2.A2b. State A.A2.A2a exit actions execute and complete (exitA2a()).
State A.A2.A2b entry actions execute and complete (entA2b()). The Stateflow diagram activity now looks like this.
8-45
Semantics
4 State A.A1.A1a executes and completes exit actions (exitA1a). 5 The processing of E_one continues once the on event broadcast of E_two has
been processed. State A.A1 checks for any valid transitions as a result of event E_one. There is a valid transition from state A.A1.A1a to state A.A1.A1b.
6 State A.A1.A1a is marked inactive. 7 State A.A1.A1b executes and completes entry actions (entA1b()). 8 State A.A1.A1b is marked active. 9 Parallel state A.A2 is evaluated next. State A.A2 during actions execute and
8-46
event. This sequence completes the execution of this Stateflow diagram associated with event E_one and the on event broadcast to a parallel state of event E_two. The final Stateflow diagram activity looks like this.
8-47
Semantics
8-48
3 State As children are parallel (AND) states. They are evaluated and
executed from left to right and top to bottom. State A.A1 is evaluated first. State A.A1 executes and completes during actions (durA1()).
4 State A.A1 checks for any valid transitions as a result of event E_one. There
time. The Stateflow diagram root checks to see if there is a valid transition as a result of E_two. There is no valid transition.
c
State A executes and completes during actions (durA()). executes and completes during actions (durA1()). State A.A1 is evaluated for valid transitions. There are no valid transitions as a result of E_two within state A1.
d State A s children are evaluated starting with state A.A1. State A.A1
State A.A2 is evaluated. State A.A2 executes and completes during actions (durA2()). State A.A2 checks for valid transitions. State A.A2 has a valid transition as a result of E_two from state A.A2.A2a to state A.A2.A2b. State A.A2.A2a exit actions execute and complete (exitA2a()).
8-49
Semantics
action event broadcast of E_two, executes and completes during actions (durA2b()).
8-50
event. This sequence completes the execution of this Stateflow diagram associated with event E_one and the transition action event broadcast to a parallel state of event E_two. The final Stateflow diagram activity now looks like this.
8-51
Semantics
Initially the Stateflow diagram is asleep. Parallel substates A.A1.A1a 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
and executed from top to bottom. In the case of a tie, they are evaluated from
8-52
left to right. State A.A1 is evaluated first. State A.A1 executes and completes during actions (durA1()).
4 State A.A1 checks for any valid transitions as a result of event E_one. There
is a valid transition from state A.A1.A1a to state A.A1.A1b. There is also a valid condition action. The condition action event broadcast of E_two is executed and completed. State A.A1.A1a is still active:
a The broadcast of event E_two awakens the Stateflow diagram a second
time. The Stateflow diagram root checks to see if there is a valid transition as a result of E_two. There is no valid transition.
b State A executes and completes during actions (durA()). c
State A s children are evaluated starting with state A.A1. State A.A1 executes and completes during actions (durA1()). State A.A1 is evaluated for valid transitions. There are no valid transitions as a result of E_two within state A1. (durA2()). State A.A2 checks for valid transitions. State A.A2 has a valid transition as a result of E_two from state A.A2.A2a to state A.A2.A2b.
d State A.A2 is evaluated. State A.A2 executes and completes during actions
e f
State A.A2.A2a exit actions execute and complete (exitA2a()). State A.A2.A2a is marked inactive.
g State A.A2.A2b is marked active. h State A.A2.A2b entry actions execute and complete (entA2b()).
8-53
Semantics
5 State A.A1.A1a executes and completes exit actions (exitA1a). 6 State A.A1.A1a is marked inactive. 7 State A.A1.A1b executes and completes entry actions (entA1b()). 8 State A.A1.A1b is marked active. 9 Parallel state A.A2 is evaluated next. State A.A2 during actions execute and
event.
8-54
This sequence completes the execution of this Stateflow diagram associated with event E_one and the condition action event broadcast to a parallel state of event E_two. The final Stateflow diagram activity now looks like this.
8-55
Semantics
State A1 is active.
State B1 is active.
Initially the Stateflow diagram is asleep. Parallel substates A.A1 and B.B1 are active. By definition, this implies parallel (AND) superstates A and B are active. An event occurs and awakens the Stateflow diagram. The condition [data1==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
8-56
2 State A checks for any valid transitions as a result of the event. Since the
condition [data1==1] is true, there is a valid transition from state A.A1 to state A.A2.
3 State A.A1 exit actions execute and complete (exitA1()).
broadcast.) Since state B is active, the directed broadcast is received and state B checks to see if there is a valid transition. There is a valid transition from B.B1 to B.B2.
b State B.B1 executes and completes exit actions (exitB1()). c
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.
8-57
Semantics
State A1 is active.
State B1 is active.
Initially the Stateflow diagram is asleep. Parallel substates A.A1 and B.B1 are active. By definition, this implies parallel (AND) superstates A and B are active. An event occurs and awakens the Stateflow diagram. The condition [data1==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
condition [data1==1] is true, there is a valid transition from state A.A1 to state A.A2.
8-58
3 State A.A1 exit actions execute and complete (exitA1()). 4 State A.A1 is marked inactive. 5 The transition action, a qualified event broadcast of event E_one to state B
broadcast.) Since state B is active, the directed broadcast is received and state B checks to see if there is a valid transition. There is a valid transition from B.B1 to B.B2.
b State B.B1 executes and completes exit actions (exitB1()). c
6 State A.A2 is marked active. 7 State A.A2 entry actions execute and complete (entA2()).
This sequence completes the execution of this Stateflow diagram associated with an event broadcast using a qualified event name to a parallel state.
8-59
Semantics
Execution Order
Overview
In a single processor environment, 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. Knowing the order of execution for Stateflow diagrams with more than one parallel (AND) state may be important. Do not design your Stateflow diagram based on an expected execution order.
this example, when an event occurs and state A.A1 is active, the transition from state A.A1 to state B is valid and takes precedence over the transition from state A.A1 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
8-60
Execution Order
d No label 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.
Junctions
Multiple outgoing transitions from junctions that are of equivalent label priority are evaluated in a clockwise progression starting from a twelve oclock position on the junction.
In this example, the transitions are of equivalent label priority. The conditions [C_three == 3]and [C_four == 4] are both true. Given that, the outgoing transitions from the junction are evaluated in this order:
1 A > B
8-61
Semantics
3 A > D
Since the condition [C_three == 3] is true, this transition is valid and is taken.
4 A > E
This transition, even though it too is valid, is not evaluated since the previous transition evaluated was valid.
States
Multiple outgoing transitions from states that are of equivalent label priority are evaluated in a clockwise progression starting at the upper, left corner of the state.
In this example, the transitions are of equivalent label priority. The conditions [C_two == 2] and [C_three == 3] are both true and [C_one = = 1] is false. Given that, the outgoing transitions from the state are evaluated in this order:
1 A > B
Since the condition [C_two == 2] is true, this transition is valid and is taken.
8-62
Execution Order
3 A > D
This transition, even though it too is valid, is not evaluated since the previous transition evaluated was valid.
8-63
Semantics
Entering a State
1 If the parent of the state is not active, perform steps 1-4 for the parent. 2 If this is a parallel state, check that all siblings with a higher (i.e., earlier)
entry order are active. If not, perform all entry steps for these states first.
3 Mark the state active. 4 Perform any entry actions. 5 Enter children, if needed: a If the state contains a history junction and there was an active child of
this state at some point after the most recent chart initialization, perform the entry actions for that child. Otherwise, execute the default flow paths for the state.
b If this state has parallel decomposition, i.e., has children that are parallel
states, perform entry steps 1-5 for each state according to its entry order.
6 If this is a parallel state, perform all entry actions for the sibling state next
8-64
7 If the transition path parent is not the same as the parent of the current
state, perform entry steps 6 and 7 for the immediate parent of this state.
Graphs). If this causes a state transition, execution stops. (Note that this step is never required for parallel states)
2 During actions and valid on-event actions are preformed. 3 The set of inner flow graphs is executed. If this does not cause a state
transition, the active children are executed, starting at step 1. Parallel states are executed in the same order that they are entered.
after this state have already been exited. Otherwise, perform all exiting steps on those sibling states.
2 If there are any active children perform the exit steps on these states in the
8-65
Semantics
2 While there are remaining segments to test, a segment is tested for validity.
If the segment is invalid, move to the next segment in order. If the segment is valid, execution depends on the destination:
States
a No more transition segments are tested and a transition path is formed
by backing up and including the transition segment from each preceding junction until the respective starting transition.
b The states that are the immediate children of the parent of the transition
Step 1 is repeated with the set of outgoing segments from the junction.
3 After testing all outgoing transition segments at a junction, back up the
incoming transition segment that brought you to the junction and continue at step 2, starting with the next transition segment after the back up segment. The set of flow graphs is done executing when all starting transitions have been tested.
Active Charton page 8-62 and Executing an Active State on page 8-63). (The event receiver is the parent of the event unless the event was explicitly directed to a receiver using the send() function.) If the receiver of the event is not active, nothing happens.
8-66
2 After broadcasting the event, the broadcaster performs early return logic
State Entry
If the state is no longer active at the end of the event broadcast, any remaining steps in entering a state are not performed. If the state is no longer active at the end of the event broadcast, any remaining exit actions and steps in state transitioning are not performed. If the state is no longer active at the end of the event broadcast, any remaining steps in executing an active state are not performed. If the origin state of the inner or outer flow graph or parent state of the default flow graph is no longer active at the end of the event broadcast, the remaining steps in the execution of the set of flow graphs are not performed. If the parent of the transition path is not active or if that parent has an active child, the remaining transition actions and state entry are not performed.
State Exit
State During
Condition
Transition
8-67
Semantics
8-68
9
Building Targets
Overview . . . . . . . . . . . . . . . . . . . . . 9-2 Setting Up Target Build Tools . . . . . . . . . . . . 9-5 Configuring a Target . . . . . . . . . . . . . . . . 9-7 Starting the Build . . . . . . . . . . . . . . . . . 9-14
Building Targets
Overview
A target is a program that executes a Stateflow model or a Simulink model containing a Stateflow state machine. Stateflow and companion tools can build targets for virtually any computer.
Target Types
Simulink and its companion tools can build the following types of targets: Simulation target A simulation target is a compiled Simulink S-function (MEX file) that enables Simulink to simulate a Stateflow model. See Parsing on page 9-16 for more information. Real-Time Workshop (RTW) target An RTW target is an executable program that implements a Simulink model. The model represented by an RTW target can include non-Stateflow as well as Stateflow blocks. An RTW target can also run on computers that do not have a floating-point instruction set. Building an RTW target requires the Real-Time Workshop and Stateflow Coder.
Building a Target
Building a target involves the following steps:
1 Configure the target.
See Configuring a Target on page 9-7 for more information. You need to perform this step only if you are building a stand-alone or RTW target or are including custom code in the target. See Building Custom Code into the Target on page 9-3.
2 Start the build process.
Stateflow automatically builds or rebuilds simulation targets, when you initiate simulation of a state machine. You must explicitly initiate the build process for other types of targets. See Configuring a Target on page 9-7 for more information.
9-2
Overview
Configuring and building a target requires a basic understanding of how Stateflow builds targets, in the case of simulation and stand-alone targets, and how Real-Time Workshop builds targets, in the case of RTW targets. See How Stateflow Builds Targets on page 9-3 for information on how Stateflow builds targets. Real-Time Workshop uses basically the same process for building targets that contain state machines as it uses for building targets that do not. See the Real-Time Workshop Users Guide for information on how Real-Time Workshop builds targets.
Rebuilding a Target
You can rebuild a target at any time by repeating step 2. When rebuilding a target, Stateflow rebuilds only those parts corresponding to charts that have changed logically since the last build. When rebuilding a target, you need to perform step 1 only if you want to change the targets custom code or configuration.
9-3
Building Targets
The code generator also generates a makefile to build the generated source code into an executable program. The generated makefile can optionally build custom code that you specify into the target (see Specifying Custom Code Options on page 9-25). Finally Stateflow builds the target, using a C compiler and make utility that you specify (see Setting Up Target Build Tools on page 9-5 for more information).
9-4
system. You can use any compiler supported by MATLAB for building MATLAB extension (MEX) files. See the MATLAB External Interfaces guide for information on C compilers supported by MATLAB. To access the online version of this guide, choose Help Desk from the MATLAB Help window.
Note Stateflow supports building targets with Microsoft Visual C/C++ 5.0 only if you have installed the Service Pack 3 updates for that product.
2 Set up MATLAB to build MEX files, using the compiler installed in step 1.
See System Setup in the MATLAB External Interfaces guide for information on setting up MATLAB to build MEX files. Stateflow uses the compiler that you specify to build MEX files to build Stateflow targets.
9-5
Building Targets
You can use any compiler supported by MATLAB for building MATLAB extension (MEX) files. See the External Interfaces/API Reference section of the online MATLAB documentation for more information for information on C compilers supported by MATLAB.
2 Set up MATLAB to build MEX files, using the compiler installed in step 1.
See Building MEX Files in the External Interfaces/API Reference section of the online MATLAB documentation. Stateflow uses the compiler that you specify to build MEX files to build Stateflow targets. If you want to use a compiler that you supply to build some targets and lcc to build other targets, first set up MATLAB to use the compiler you supply. Then, check the Use lcc compiler option on the Coder dialog box (see Simulation Target on page 9-11) for each target that you want to be built with lcc.
9-6
Configuring a Target
Configuring a Target
Configuring a target entails some or all of the following steps:
1 Add the target, if necessary, to the state machines target list.
See Adding a Target to a State Machines Target List on page 9-7 for instructions on how to add targets to a state machines target list.
2 Start the target builder dialog box.
See Specifying Code Generation Options on page 9-11 for more information.
5 Specify custom code options.
See Specifying Custom Code Options on page 9-25 for more information.
6 Check Apply to all Libraries on the Target Builder dialog box if you want
the selected options to apply to the code generated for charts imported from chart libraries. Note Configuring an RTW target may require additional steps. See the Real-Time Workshop Users Guide for more information.
9-7
Building Targets
To add a target:
1 Select Explore from the Stateflow editors Tools menu.
The Explorer object hierarchy shows the state machines currently loaded in memory. In the above example, the state machine fuelsys is just above the chart fuel rate controller (shown as fuel rate...) which is highlighted by default.
2 Select the state machine to which you want to add the RTW target.
The Explorer displays the selected state machines data, events, and targets in the contents pane.
3 Select Target from the Explorers Add menu to add a target with the default
Follow the steps in the next topic to rename the target to rtw.
9-8
Configuring a Target
- Open Simulation Target to build a simulation target. - Open RTW Target to build an RTW target.
9-9
Building Targets
The dialog boxes for each build are shown below. They are identical in appearance but differ in Target Name and in the options that each presents. Explanations for their fields appear in the sections that follow.
9-10
Configuring a Target
Real-Time Workshop User Interface in the Real-Time Workshop Users Guide. Stateflow Target to build only Stateflow code to the RTW target.
Simulation Target
To specify code generation options for a simulation target, do the following:
1 From the Stateflow Simulation Target Builder dialog (see section
Starting the Target Builder Dialog on page 9-9) select Coder Options.... The Simulation Coder Options dialog box appears.
Stateflow enables debugging code generation when you use the debugger to start a model simulation. You can enable or disable chart animation separately in the debugger. (The Stateflow debugger does not work with stand-alone and RTW targets. Therefore, Stateflow and Real-Time Workshop do not generate debugging/animation code for these targets, even if this option is enabled.)
9-11
Building Targets
Echo expressions without semicolons. Display run-time output in the MATLAB command window, specifically actions that are not terminated by a semicolon.
3 Select Apply to apply the selected options or OK to apply the options and
Note Use the Chart Properties dialog to tell the simulation target builder to recognize C bit-wise operators (~, &, |, ^, >>, etc.) in action language statements and encode these operators as C bit-wise operations.
RTW Target
To specify code generation options for an RTW target:
1 From the Stateflow RTW Target Builder dialog (see section Starting the
Target Builder Dialog on page 9-9) select Coder Options.... The RTW Coder Options dialog box appears (see ).
The RTW Coder Options dialog box provides the following options.
Comments in generated code. Include comments in the generated code. Preserve symbol names. Preserve symbol names (names of states and data) when generating code. This is useful when the target contains custom code
9-12
Configuring a Target
that accesses state machine data. Note that this option can generate duplicate C symbols if the source chart contains duplicate symbols, for example, two substates with identical names. Enable the next option to avoid duplicate substate names.
Append symbol names with parent names. Generates a state or data name by appending the name of the items parent to the items name. Use chart names with no mangling. Exports the names of generated functions so that they can be invoked by user-written C code. Use bitsets for storing state configuration. Use bitsets for storing state configuration variables. This can significantly reduce the amount of memory required to store the variables. However, it can increase the amount of memory required to store target code if the target processor does not include instructions for manipulating bitsets. Use bitsets for storing boolean data. Use bitsets for storing Boolean data. This can significantly reduce the amount of memory required to store boolean variables. However, it can increase the amount of memory required to store target code if the target processor does not include instructions for manipulating bitsets.
3 Select Apply to apply the selected options or OK to apply the options and
Note Use the Chart Properties dialog to tell the simulation target builder to recognize C bit-wise operators (~, &, |, ^, >>, etc.) in action language statements and encode these operators as C bit-wise operations.
9-13
Building Targets
9-14
By selecting the Build button on the RTW panel of Simulinks Simulation Parameters dialog box. Select Real-Time Workshop options on the RTW Target Builder dialog box to access the Simulation Parameters dialog box of Simulink. See Select a Build Option on page 9-10 for more information.
9-15
Building Targets
Parsing
Parser
The parser evaluates the graphical and nongraphical objects in each Stateflow machine against the supported Stateflow notation and the action language syntax.
9-16
Parsing
Choose Parse Diagram from the graphics editor Tools menu to parse the Stateflow diagram. State A in the upper left-hand corner is selected and this message is displayed in the pop-up window and the MATLAB command window.
In this example, there are two states with the name A. Edit the Stateflow diagram and label the duplicate state with the text B. The Stateflow diagram should look similar to this.
9-17
Building Targets
3 Reparse.
Choose Parse Diagram from the graphics editor Tools menu. This message is displayed in the pop-up menu and the MATLAB command window.
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.
9-18
Parsing
5 Reparse.
Choose Parse Diagram from the graphics editor Tools menu. This message is displayed in the pop-up window and the MATLAB command window.
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 is E_one [C_one].
7 Reparse.
Choose Parse Diagram from the graphics editor Tools menu. This message is displayed in the pop-up window and the MATLAB command window.
9-19
Building Targets
Error Messages
When building a target, you may see error messages from any of the following sources: the parser, the code generator, or from external build tools (make utility, C compiler, linker). Stateflow displays errors in a dialog box and in the MATLAB command window. Double-clicking on a message in the error dialog zooms the Stateflow diagram to the object that caused the error.
9-20
Error Messages
9-21
Building Targets
Generated Files
All generated files are placed in a subdirectory of the sfprj subdirectory of the MATLAB current directory. The MATLAB current directory is set in the Start in field for the properties of the MATLAB program icon that you used to start MATLAB. You can change it in MATLAB with a cd command as you would in DOS or UNIX.
Note Do not confuse the sfprj subdirectory for generated files with the sfprj subdirectory of the project directory (the directory where the project file resides). The latter is used for project data only.
DLL Files
If you have a Simulink model named mymodel.mdl which contains two Stateflow blocks named chart1 and chart2, this means that you have a machine named mymodel that parents two charts named chart1 and chart2. When you simulate the Stateflow chart for mymodel.mdl, you actually generate code for mymodel.mdl that is compiled into an S-function dll file known as a simulation target. On Windows PC platforms this file is named mymodel_sfun.dll. On UNIX platforms the dll file is named mymodel_sfun.$mexext$ where $mexext$ is sol2 on Solaris, mexsg on SGI, mexlx on linux, and so on.
Code Files
Code files for the Simulation target (sfun) are generated for each model and placed in the subdirectory sfprj/build/<model>/sfun/src of the current directory where <model> represents the name of the model.
Note Do not keep any of your custom source files in the sfprj subdirectory of your model directory.
The code generated for the simulation target "sfun" is organized into the following files:
9-22
Generated Files
<model>_sfun.h is the machine header file. It contains the following: - All the defined global variables needed for the generated code - Type definition of the state machine-specific data structure that holds machine parented local data - External declarations of any state machine-specific global variables and functions - Custom code strings specified via the Target Options dialog box <model>_sfun.c is the machine source file. It #includes the machine header file and all the chart header files (described below) and contains the following: - all the machine parented event broadcast functions - Simulink interface code <model>_sfun_registry.c is a machine registry file that contains Simulink interface code. <model>_sfun_cn.h is the chart header file for the chart chartn, where n = 1, 2, 3, etc. depending on how many charts your model has (see note below). This file contains type definitions of the chart specific data structures that hold chart parented local data and states. <model>_sfun_cn.c is the chart source file for chartn, where n = 1, 2, 3, etc. depending on how many charts your model has (see note below). This chart
source file #includes the machine header file and the corresponding chart header file. It contains the following:
- chart parented data initialization code - chart execution code (state entry, during exit etc.) - chart-specific Simulink interface code. Note Every chart is assigned a unique number at creation time by Stateflow. This number is used as a suffix for the chart source and chart header file names for every chart ( where n = 1, 2, 3, etc. depending on how many charts your model has).
9-23
Building Targets
Make Files
Makefiles generated for your model are platform and compiler specific.
On UNIX platforms, Stateflow generates a gmake compatible makefile named mymodel_sfun.mku that is used to compile all the generated code into an executable.
On PC platforms, an ANSI C compiler-specific makefile is generated based on your C-MEX setup. If your installed compiler is Microsoft Visual C++ 4.2, 5.0, or 6.0, we generate the following: - an MSVC compatible makefile named mymodel_sfun.mak - a symbol definition file named mymodel_sfun.def (required for building S-function DLLs) If your installed compiler is Watcom 10.6 or 11.0, we generate the following: - a Watcom compatible makefile named mymodel_sfun.wmk If your installed compiler is Borland 5.0, we generate the following files: - A Borland compatible makefile named mymodel_sfun.bmk - A symbol definition file named mymodel_sfun.def (required for building S-function DLLs) If you have chosen lcc-win32, a bundled ANSI-C compiler shipped with Stateflow, we generate the following file: - an lcc compatible makefile named mymodel_sfun.lmk
Stateflow Coder also generates another support file needed for the make process named <model>_sfun.mol.
9-24
target), select the Target Options button. The Target Options dialog appears as one of the following:
The dialog box contains a drop-down list of various options for specifying what code to include in the target and where the code is located. The edit box below the list displays the setting for the current option.
9-25
Building Targets
3 Select the options required to specify your code and enter the specifications
in the edit box. See the section Custom Code Options on page 9-26 for information on how to use these options to specify your custom code.
4 Select Apply to apply the specification to the target or OK to apply the
specifications and close the dialog. Note If you make a change in one of your custom code options, to force the rebuild of the S-function to incorporate your changes you must either change one of the charts slightly (this forces a rebuild when you simulate again) or go to the Simulation Target properties dialog box and choose the Rebuild All option
Since the code specified in the Custom code included at the top of the generated code is included in multiple source files that get linked into a single binary, there are some limitations on what can and cannot include. For example, you should not include global variable definitions or function bodies through this property such as int x; or void myfun(void) {...}. This would cause linking errors since these symbols get defined multiple times in the source files of the generated code. You can, however, include extern declarations of variables or functions such as extern int x; or extern void
myfun(void);. Custom include directory paths. Space-separated list of paths of directories containing custom header files to be included either directly (see first option above) or indirectly in the compiled target.
9-26
See the section Specifying Path Names in Custom Code Options on page 9-28.
Custom source files. List of source files to be compiled and linked into the target. You can separate source files with either commas, spaces, or new lines.
See the section Specifying Path Names in Custom Code Options on page 9-28.
Custom libraries. Space-separated list of libraries containing custom object code
to be linked into the target. See the section Specifying Path Names in Custom Code Options on page 9-28.
Custom make files. Space-separated list of custom makefiles. The Stateflow code generator includes these makefiles at the head of the makefile it generates to build the simulation target. You can use this option to include makefiles for building custom code required by the target.
See the section Specifying Path Names in Custom Code Options on page 9-28.
Build command. The MATLAB command used to build the target. Code command. The MATLAB command used to invoke the code generator (sfc, by default). You can add command-line arguments for sfc options not reflected on the Coder Options dialog box for the target. Custom initialization code. Code statements that are executed once at the start of simulation. You can use this initialization code to invoke functions that allocate memory or perform other initializations of your custom code. Custom termination code. Code statements that are executed at the end of simulation. You can use this code to invoke functions that free memory allocated by custom code or perform other cleanup tasks.
For additional information of specifying custom code for your target, see the following online articles: Integrating Custom C Code Using Stateflow 2.0 by V. Raghavan Automatic Code Generation from Stateflow for Palm OS Handhelds: a Tutorial by D. Maclay
9-27
Building Targets
9-28
Graphical Functions on page 3-55). This option implicitly forces the chart and function names to be preserved.
3 Include the generated header file chart_name.h at the top of your custom
code, where chart_name is the name of the chart that contains the graphical function. The chart header file contains the prototypes for the graphical functions that the chart defines.
9-29
Building Targets
9-30
10
Debugging and Testing
Overview . . . . . . . . . . . . . . . . . . . . . 10-2 Stateflow Debugger User Interface . . . . . . . . . . 10-5 Debugging Run-Time Errors . . . . . . . . . . . 10-10
Debugging State Inconsistencies . . . . . . . . . . 10-14 Debugging Conflicting Transitions . . . . . . . . . 10-16 Debugging Data Range Violations . . . . . . . . . 10-18 Debugging Cyclic Behavior . . . . . . . . . . . . 10-19 Stateflow Chart Model Coverage . . . . . . . . . . 10-22
10
Overview
Use the Stateflow Debugger to debug and animate the Stateflow diagrams in a particular machine. It is a good idea to include debugging 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 Real-Time Workshop and stand-alone targets. The Debugger does not interact with Real-Time Workshop or stand-alone targets and the overhead incurred from the added instrumented code is undesirable.
10-2
Overview
Data range violations See the section Debugging Data Range Violations on page 10-18. Cyclic Behavior See the section Debugging Cyclic Behavior on page 10-19. To include the supporting code for these debugging options, check the Enable debugging/animation checkbox in the Coder Options dialog (see the section Specifying Code Generation Options on page 9-11). You access the Coder Options dialog through the Target Builder properties dialog box. See the section Configuring a Target on page 9-7 for more information.
Note You must rebuild the target for any changes to any of the settings referred to above to take effect.
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 breakpoint. Local breakpoints halt execution on a specific object instance. When simulation execution is halted at a breakpoint, you can: Examine the current status of the Stateflow diagram Step through the execution of the Stateflow diagram Specify display of one of the following: - Call stack - Code coverage - Data values - Active states The breakpoints can be changed during run-time and are immediately 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.
10-3
10
Run-Time Debugging
Once the target is built with the debugging code, you can enable or disable the associated run-time options in the Debugger window which affects the Debugger output display results. Enabling/disabling the options in the Debugger window affects the target code and can cause the target to be rebuilt when you start the simulation from the debugger. There are also some run-time debugging options that do not require supporting code in the target. These options can be dynamically set: Enable/disable cycle detection in the Debugger window Set any of the following global breakpoints through the Breakpoint controls section of the main Debugger window (see the section Breakpoint Controls on page 10-7): - Any chart entry - Any event broadcast - Any state entry Enable/disable local Debugger breakpoints at specific chart or state action execution points in these appropriate property dialog boxes: - Chart (see Specifying Chart Properties on page 3-46) - State (see Changing Event Properties on page 4-4) Enable/disable local Debugger breakpoints at a specific transition (either when the transition is tested or when it is determined to be valid) in the Transition property dialog box (see Changing Transition Properties on page 3-31) Enable/disable local Debugger breakpoints based on a specific event broadcast (see Event Dialog Box on page 4-5)
10-4
10-5
10
After you select the Start button to start a debugging simulation session and a breakpoint that you set is encountered, the Debugger main window appears like the following:
10-6
Breakpoint Controls
Use the Breakpoint controls to specify global breakpoints. When a global breakpoint is encountered normal simulation execution stops and the Debugger takes control on any: Chart entry Click on the Chart Entry check box (check is displayed when enabled) to enable this type of breakpoint. Event broadcast Click on the Event Broadcast check box (check is displayed when enabled) to enable this type of breakpoint. State entry Click on the State Entry check box (check is displayed when enabled) to enable this type of breakpoint. The breakpoints can be changed during run-time and are immediately enforced. When you save the Stateflow diagram, the breakpoint settings are saved.
10-7
10
Stop Simulation Click on the Stop Simulation button to stop the simulation execution and relinquish debugging control. 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.
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) second.
Display Controls
Use these buttons to control the output display: 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 The Coverage button displays the current percentage of unprocessed transitions, states, etc. at that point in the simulation. Click on the buttons drop down list icon to display a list of coverage options: coverage for the current chart only, for all loaded charts, or for all charts in the model. Browse Data Click on the Browse Data button to display the current value of any defined data objects. Active States The Active States button displays a list of active states in the display area. Double-clicking on any state causes the graphics editor to display that state. The drop-down list button on the Active States button lets you specify the extent of the display: active states in the current chart only, in all loaded charts, or for all charts in the model.
10-8
Breakpoints Click on the Breakpoints button to display a list of the set breakpoints. The drop-down list button on the Breakpoints button lets you specify the extent of the display: breakpoints in the current chart only or in all loaded charts. Once you have selected an output display button, that type of output is displayed until you choose a different display type. You can clear the display by selecting Clear Display from the Debuggers File menu.
10-9
10
10-10
The Stateflow diagram has two states at the highest level in the hierarchy, Power_off and Power_on. By default Power_off is active. The event Switch toggles the system between being in Power_off and Power_on. Switch is defined as an Input from Simulink event. Power_on has three substates, First, Second, and Third. By default, when Power_on becomes active, First also becomes active. Shift is defined as an Input from Simulink data object. When Shift equals 1, the system transitions from First to Second, Second to Third, Third to First, 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 Switch. The Step block is used to generate a repeating pattern of 1 and 0 that corresponds with the Stateflow data object Shift. Ideally, the Switch event occurs in a frequency that allows at least one cycle through First, Second, and Third.
10-11
10
10-12
10-13
10
10-14
In the absence of a default transition indicating which substate is to become active, the simulation encounters a run-time state inconsistency error. Adding a default transition to one of the substates resolves the state inconsistency.
10-15
10
The default transition to state A assigns data a equal to 1 and data b equal to 10. State As during action increments a and decrements b. The transition from state A to state B is valid if the condition [a > 4] is true. The transition from state A to state C is valid if the condition [b < 7] is true. As the simulation
10-16
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 twelve oclock position on the state. In this example, the transition from state A to state B 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-17
10
The data a is defined to have an Initial and Minimal value of 0 and a Maximum value of 2. Each time an event awakens this Stateflow diagram and state A is active, a is incremented. The value of a quickly becomes a data range violation.
10-18
When state C during action executes event E1 is broadcast. The transition from state A.A1 to state A.A2 becomes valid when event E1 is broadcast. Event E2 is
10-19
10
broadcast as a condition action of that transition. The transition from state B.B1 to state B.B2 becomes valid when event E2 is broadcast. Event E1 is broadcast as a condition action of the transition from state B.B1 to state B.B2. Because these event broadcasts of E1 and E2 are in condition actions, a recursive event broadcast situation occurs. Neither transition can complete.
The data object i is set to zero in 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 < 0] is true. This condition will never be true in 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-20
State A becomes active and i is initialized to zero. When the transition is tested, the condition [i < 5] is true. The condition actions, increment i 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-21
10
Note You must have the Simulink Performance Tools option installed on your system to use the Model Coverage Tool.
10-22
Decision Coverage
Decision Coverage interprets a model execution in terms of underlying decisions where behavior or execution must take one outcome from a set of mutually exclusive outcomes. Note Full coverage for an object of decision means that every decision has had at least one occurrence of each of its possible outcomes.
The following sections detail how Decision Coverage outcomes vary between different decision objects.
Note Decision Coverage for superstates applies to exclusive (OR) substates only. A superstate makes no decisions for its parallel (AND) substates.
Since a superstate must decide which of its exclusive (OR) substates to process, the number of decision outcomes for the superstate is equal to the number of
10-23
10
exclusive (OR) substates that it contains. In the examples below, the choice of which substate to process is made in one of three possible contexts.
Note Implicit transitions are shown as dashed lines in the examples below.
1 Active Call
This gives rise to the following superstate/substate decisions: The parent of states A and B must decide which of these states to process. This decision belongs to the parent. Since A is active, it is processed. State A, the parent of states A1 and A2, must decide which of these states to process. This decision belongs to state A. Since A1 is active, it is processed. During processing of state A1, all of its outgoing transitions are tested. This decision belongs to the transition and not to its parent state A. In this case, the transition marked by condition C2 is tested and a decision is made whether to take the transition to A2 or not. See the section Conditional Transition on page 10-26.
10-24
In the following example, a transition takes place whose source is superstate A and whose destination is state B. If the superstate has two exclusive (OR) substates, it is the decision of superstate A as to which of these substates will perform the implicit transition from substate to superstate.
A history junction, similar to the one shown in the example below, provides a superstate with the means of recording which of its substates was last active before the superstate was exited. If that superstate now becomes the destination of one or more transitions, then the history junction provides it the means of deciding which previously active substate to enter.
10-25
10
Conditional Transition
A conditional transition is a transition with a triggering event and/or a guarding condition (see the section Labeling a Transition on page 7-15). In a conditional transition from one state to another, the decision to exit one state and enter another is credited to the transition itself. See the report section Transition on page 10-32
Note Only conditional transitions receive decision coverage. Transitions without decisions are not applicable (NA) to Decision Coverage.
Condition Coverage
Condition Coverage reports on the extent to which all possible outcomes are achieved for individual subconditions composing a transition decision.
Note Full Condition Coverage means that all possible outcomes occurred for each subcondition in the test of a decision.
For example, for the decision [A & B & C] on a transition, Condition Coverage reports on the True and False occurrences of each of the subconditions A, B, and C. This results in six possible outcomes: True and False for each of three subconditions. See the report section Transition on page 10-32.
MCDC Coverage
The Modified Condition Decision Coverage (MCDC) option reports a tests coverage of occurrences in which changing an individual subcondition within a transition results in changing the entire transition from valid to invalid.
10-26
Note If matching True and False outcomes occur for each subcondition, coverage is 100%.
For example, if a transition executes on the condition [C1 & C2 & C3 | C4 & C5], then the MCDC report for that transition shows actual occurrences for each of the five subconditions (C1, C2, C3, C4, C5) in which changing its result from True to False is able to change the result of the entire condition from True to False. See the report section Transition on page 10-32.
10-27
10
The Summary section shows coverage results for the entire test. It appears at the beginning of the Model Coverage report after the listing of the Start and End execution times for the test (simulation). The example above excerpts the states of the Stateflow chart control logic from the Model Coverage Tool report for the Fuel System Simulink model. The above hierarchy presents all superstates within the Stateflow chart control logic in order of hierarchical containment. All but the very top level, which represents the charts Simulink block, uses an SF:prefix. Each line in the hierarchy summarizes the coverage results at its level of hierarchy and the levels below it and includes a hyperlink to a later section in the report detailing that coverage. Notice that control logic appears twice as an element. The first time it is seen as a top-level block in a Simulink model. The second time, it appears as the top-level superstate. This distinction will become more apparent in the sections below.
Details
The Details heading appears directly under the Summary Report Section depicted in the example above. It precedes sections summarizing the coverage
10-28
you choose to report for each object of decision in the Stateflow chart. These include the charts Simulink block, the chart itself, the charts states, and its guarded transitions. An example coverage section for each of these object types appears in the sections below and contains the following information: A title containing a hyperlink to its resident diagram The chart Simulink block (Chart as Subsystem) appears in its resident Simulink model. The remaining objects appear in the charts Stateflow diagram. A hyperlink to the objects parent A hyperlink to the objects child object(s) A table summarizing Decision Coverage, Condition Coverage, and MCDC, for the object The first column displays coverages for the object itself. The second column displays coverages for the object including sums of coverages for objects it parents (states, transitions). These coverages also appear in the Summary section. Results are read as a ratio of observed outcomes taken to all possible outcomes for the object. For example, if a state has four exclusive OR substates, that means that there are four possible outcomes since only one exclusive OR state can be active at a time. If only three substates are observed to execute during testing, Decision Coverage is reported as 75% (3/ 4). Additional tables detailing outcomes observed for Decision Coverage, Condition Coverage, and MCDC Coverage for the object
Chart as Subsystem
10-29
10
The Subsystem report sees the chart as a block in a Simulink model, instead of a chart with states and transitions. This is confirmed by the hyperlinked subsystem name in the title, which takes you to a highlighted control logic block in its resident block diagram. Since this block is not a triggered Simulink block, no Decision Coverage data appears for it as a block object. Condition Coverage and MCDC are always not applicable (NA) to a chart block. In spite of this, there is plenty of coverage for decision objects that the chart contains. This appears in the Coverage column, which includes descendant coverage.
Chart as Superstate
The Chart report sees a Stateflow chart as the superstate container of all of its states and transitions. This is confirmed by the hyperlinked chart name, which takes you to a display of the control logic chart in the Stateflow chart diagram editor. Since the control logic chart for the Fuel System model contains only parallel (AND) states, no Decision Coverage is shown for the chart as an object. Only if the chart contained exclusive OR states would decision data be present.
10-30
State
Note State reports are numbered according to their appearance in the Model Hierarchy of the Summary report.
The state Fueling_Mode is a superstate containing the two states Running and Fuel_Disabled. Therefore, Decision Coverage tests the decision of which of these states to execute. The Decision Coverage Details table shows that the state Fuel_Disabled was active 26,960 times during simulation and the state Running 22,968 times. Since both states were executed during simulation, coverage is full (100% = 2/2) as reported in the Metric table. Condition Coverage and MCDC are both not applicable (NA) coverages for a state.
10-31
10
Transition
Note Reports for transitions appear under the report section of their owning state. While state reports are numbered according to their appearance in the the Model Hierarchy of the Summary report. Since transitions do not appear in this Model Hierarchy, transition reports are not numbered.
The decision for this transition contains two conditions throt > max_throt and throt < min_throt. If both conditions are True, the decision is True. If
10-32
either condition is True, the decision is True. If both conditions are False, the decision is False. For Decision Coverage, both the True and False evaluations for the decision occurred. This means that coverage was full, 100%, in which two of two decision outcomes occurred. For Condition Coverage, condition 2 received both a True and a False outcome. However, condition 1 received only a False outcome. This means that coverage was incomplete for condition 1 and is indicated by red color for the table line report of condition 2s Condition Coverage. Overall, however, three of four condition outcomes occurred during testing, yielding a rating of 75%. For the MCDC report, all sets of occurrences of the transition conditions are scanned for a particular pair of decisions for each condition in which the following are true: The condition varies from True to False. All other conditions contributing to the decision outcome remain constant. The outcome of the decision varies from True to False, or vice versa. For two conditions related by an OR operator (e.g., A|B), these criteria can be satisfied by the occurrence of the following conditions.
Condition Tested True Outcome False Outcome
1 2
T|F F|T
F|F F|F
Notice that in each line, the condition tested changes from True to False while the other condition remains constant. If both sets occur during testing, coverage is complete (100%). The transition report example above shows coverage only for condition 2. The True outcome required for condition 1 did not occur, and is indicated by the parentheses. Therefore the table line for condition 1 is colored red. Thus, while condition 2 has been tested, condition 1 has not and MCDC Coverage is 50%. For some decisions, the values of some conditions are irrelevant under certain circumstances. For example, in the decision [C1 & C2 & C3 | C4 & C5] the left side of the | will be False if any one of the conditions C1, C2, or C3 is False.
10-33
10
The same applies to the right side result if either C4 or C5 is False. Thus, when searching for matching pairs that change the outcome of the decision by changing one condition, holding some of the remaining conditions constant is irrelevant. In these cases, the MCDC report marks these conditions with an x to indicate their irrelevance as a contributor to the result. This is shown in the following example.
Consider the very first matched pair. Since condition 1 is True in the True outcome, it must be False in the matching False outcome. This makes the conditions C2 and C3 irrelevant for the False outcome since C1 & C2 & C3 is always False if C1 is False. Also, since the False outcome is required to evaluate to False, the evaluation of C4 & C5 must also be False. In this case, a match was found with C4 = F, making condition C5 irrelevant.
10-34
11
The Stateflow API
Overview of the Stateflow API . . . . . . . . . . . . 11-2 Quick Start with the Stateflow API . . . . . . . . . 11-5
Creating, Connecting to, and Destroying Objects . . 11-18 Accessing Existing Objects . . . . . . . . . . . . 11-21
Copying Objects . . . . . . . . . . . . . . . . . 11-24 Using the Editor Object . . . . . . . . . . . . . . 11-28 Entering Multiline Labels . . . . . . . . . . . . . 11-29
11
11-2
Stateflow API containment hierarchy consists of the following layers of containment: Root The Root object (there is only one) serves as the parent of all Stateflow objects. It is a placeholder at the top of the Stateflow hierarchy to distinguish Stateflow tool objects from the objects of other tools such as Simulink and Handle Graphics. Machine Within Stateflows Root object, there are objects of type Machine. Machine objects are equivalent to Simulink models from a Stateflow perspective. They can hold objects of type Chart, Data, Event, and Target. Chart Within any Machine object (model) there can be any number of Chart (Stateflow diagram) objects. State/Function/Box Within each Chart object, there can be objects of type State, Function, Box, Note, Data, Event, Transition, and Junction, the components of a Stateflow chart. Nested within State objects there can be further objects of type State, Function, Box, Note, Junction, Transition, Data, and Event. Levels of nesting can continue indefinitely. The above figure also shows two object types that exist outside of Stateflow containment hierarchy and are as follows: Editor Though not a part of the Stateflow containment hierarchy, the Editor object provides access to the purely graphical aspects of Chart objects. For each Chart object there is an Editor object that provides API access to the Chart objects diagram editor. Clipboard The Clipboard object (there is only one) has two methods, copy and pasteTo, which use the clipboard as a convenient staging area to implement the operation of copy and paste functionality in the Stateflow API.
11-3
11
creating, finding, changing, or deleting objects normally provided by the Stateflow diagram editor. Stateflow objects of all types have some common (or shared) properties and methods. For example, all objects have an Id and a Description property. All objects have a get and a set method for viewing or changing the properties of an object. Most objects also have a delete method. Methods held in common among all Stateflow objects are listed in the reference section Methods that Apply to All Objects on page B-5. Each object also has properties and methods unique to its type. For example, a State object has a Position property containing the spatial coordinates for the state it represents in the chart editor. A Data object, however, has no Position property. And the same applies to methods.
11-4
The sfnew method creates a new Simulink model with a new Stateflow chart in it. Do not open the Stateflow chart.
Note At this point you should have only one Simulink model in memory.
11-5
11
rt = sfroot
The workspace variable rt now becomes a handle to the Root object which allows you access to any Stateflow objects. There is only one Root object in Stateflow. It does not come into existence until you load a model containing a Stateflow chart or call the method sfnew to create a new model with a Stateflow chart.
handle, m, as follows:
m = rt.find('-isa','Stateflow.Machine')
If, instead of one model, MATLAB contained several Simulink models, m would be returned as an array of different machine objects, each representing a model (m(1), m(2),..., m(n)). In this case you can differentiate between machine objects using the properties of each machine, particularly the Name property, which is the name of the model. For example, you can use the Name property to find a machine with the name myModel with the following command:
m = rt.find('-isa', Stateflow.Machine', '-and', 'Name','myModel')
However, since you now have only one model loaded, the object handle m in the previous command represents the machine that you just created.
as follows:
11-6
chart = m.findDeep('Chart')
In this command, the findDeep method of the machine object returns an array of all charts belonging to that machine. Because you created only one chart, the result of this command is the chart you created. If you had created several charts, the findDeep method would have returned an array of charts which you could access through indexing (chart(1), chart(2), etc.). In the above command you can also use standard function notation instead of dot notation. In this case, the first argument is the machine object handle:
chart = findDeep(m, 'Chart')
chart.view
The above command calls the view method of the Chart object chart which displays the specified chart in the Stateflow diagram editor. You should now have an empty Stateflow chart in front of you. Other Stateflow API objects have view methods as well.
The above command is a Stateflow API constructor for a state in which Stateflow.State is the object type for a state, chart is a workspace variable handle to the chart parent to contain the new state and sA is a workspace variable to receive the returned handle to the newly created State object. See also Creating, Connecting to, and Destroying Objects on page 11-18. An empty state now appears in the upper left hand corner of the diagram editor. To view the diagram editor after each command or set of commands,
11-7
11
continue to use the chart.view command which brings the chart diagram editor to the foreground.
2 Assign values to the new state by using the workspace handle sA as follows:
The above commands create and use the workspace variables sA, sA1 and sA2 as handles to the new states which now have the following appearance:
11-8
tA1A2.DestinationOClock = 9.
5 Finish off the Stateflow diagram by drawing state A11 inside of A1 and draw
an inner transition from the 1 OClock position of state A1 to the 1 OClock position of state A11 with the following commands:
sA11 = Stateflow.State(chart) sA11.Name = 'A11' sA11.Position = [90 130 35 35] tA1A11 = Stateflow.Transition(chart) tA1A11.Source = sA1 tA1A11.Destination = sA11 tA1A11.SourceOClock = 1. tA1A11.DestinationOClock = 1.
11-9
11
6 Add the labels 'E1' and 'E2' to the transitions A1 to A2 and A1 to A11,
Both the state and transition labels in our example are simple one line labels. To enter more complex multiline labels, see Entering Multiline Labels on page 11-29. Labels for transitions also have a LabelPosition
11-10
property which you can use to move the labels to better locations. For example, you can use the following commands to move the label for the transition from A1 to A2 to the right by 15 pixels:
pos = tA1A2.LabelPosition pos(1) = pos(1)+15 tA1A2.LabelPosition = pos
Notice that the above command uses the Id property of the Machine object m for saving the model under a new name.
11-11
11
sA2.Position = [220 80 90 80]; tA1A2 = Stateflow.Transition(chart); tA1A2.Source = sA1; tA1A2.Destination = sA2; tA1A2.SourceOClock = 3.; tA1A2.DestinationOClock = 9.; sA11 = Stateflow.State(chart); sA11.Name = 'A11'; sA11.Position = [110 110 35 35]; tA1A11 = Stateflow.Transition(chart); tA1A11.Source = sA1; tA1A11.Destination = sA11; tA1A11.SourceOClock = 1.; tA1A11.DestinationOClock = 1.; tA1A2.LabelString = 'E1'; tA1A11.LabelString = 'E2'; pos = tA1A2.LabelPosition; pos(1) = pos(1)+15; tA1A2.LabelPosition = pos;
11-12
The following command uses the dialog method of State objects to open the properties dialog for the state s:
s.dialog
You can also nest smaller dot expressions in larger dot expressions of properties that return intermediate results. For example, the Chart property of a State object returns the Chart object of the containing chart. Therefore, the expression s.Chart.Name returns the name of the chart containing the State whose object is s.
11-13
11
Methods can also be nested in dot expressions. For example, if the State object sA1 represents state A1 in the final Stateflow chart at the end of section Create New Objects in the Chart on page 11-7, the following command returns the string label for state A1s inner transition to its state A11.
label = sA1.innerTransitionsOf.LabelString
The above command uses the LabelString property of a Transition object and the innerTransitions method for a State object. It works as shown only because state A1 has one inner transition. If state A1 has more than one transition, you must first find all of the inner transitions and then use an array index to access each one, as shown below:
innerTransitions = sA1.innerTransitionsOf label1 = innerTransitions(1).LabelString label2 = innerTransitions(2).LabelString etc.
Use only function notation if you have array arguments. The following example returns a vector of Strings with the names of each chart in the array of Chart objects, charray:
names = get(charray, 'Name')
If you attempt to use the command names = charray.get('Name') instead, an error is displayed.
11-14
To get a quick description for each property, use the help method. For example, if s is a State object, the following command returns a list of each State property with a small accompanying description:
s.help
Note Some properties do not have a description, because their names are considered descriptive enough.
Use the methods method to list the methods for any object. For example, if the object t is a handle to a Transition object, use the following command to list the methods for any Transition object:
t.methods
11-15
11
Use a combination of the get method and the classhandle method to list only the names of the properties and methods. List just the names of the properties for the state object s with the following command:
get(s.classhandle.Properties, 'Name')
Similarly, list just the names of each method for the transition object t with the following command:
get(t.classhandle.Methods, 'Name')
The above value indicates that the StateFont property of a state has subproperties. To view the subproperties of StateFont, issue the command ch.StateFont.get to receive something like the following:
xxName: xxSize: Weight: xAngle: Helvetica' 12 'NORMAL' 'NORMAL'
From this list it is clearly seen that Name, Size, Weight, and Angle, are subproperties of the property StateFont. In the property references in this chapter, these properties appear under their full property name: StateFont.
11-16
You display a list of acceptable strings for a property requiring enumerated values using the set method. For example, if ch is a handle to a Chart object, you can display the allowed enumerated values for the Decomposition property of a Chart object with the following command:
set (ch,'Decomposition')
11-17
11
The newly created state from the above command shows up in the upper left hand corner of the Stateflow chart (x-y coordinates 0,0). You can now set its name (Name property), its position (Position property), and connect it to other objects (Source and Destination properties). All Stateflow objects are created using the general form shown above. The section Create New Objects in the Chart on page 11-7 gives examples for creating states and transitions. Objects of other types are created just as easily.
11-18
Note Currently, there is no constructor for a Stateflow Chart. To create a chart with the Stateflow API you must use the sfnew global method.
For more information on using the Editor object, see the section Using the Editor Object on page 11-28. The Clipboard object (there is only one) provides an interface to the Clipboard used in copying Stateflow objects. You create a handle to the Clipboard object using the sfclipboard method as follows:
cb = sfclipboard
For more information on using the Clipboard object to copy objects, see the section Copying Objects on page 11-24.
11-19
11
The above command is equivalent to performing a mouse select and keyboard delete operation in the Stateflow diagram editor. Upon deletion, graphical Stateflow objects are sent to the Clipboard; non-graphical objects, such as data and events, are completely deleted. The workspace variable s still exists but is no longer a handle to the deleted state.
11-20
If a find command finds more than one object that meets its specifications, it returns an array of qualifying objects. In the following example, a find command returns an array of all charts in your model:
chartArray = m.find('-isa','Stateflow.Chart')
Use array indexing to access individual properties and methods for a chart. For example, if the above command returned three Stateflow charts, the following command returns the Name property of the second chart found:
name2 = chartArray(2).Name
The find method finds objects at the depth of containment within an object that you specify. By default, the find command finds objects at all depths of containment within an object. This includes the zeroth level of containment, which is the searched object itself. For example, if state A, which is represented
11-21
11
by State object sA, contains two states, A1 and A2 and you specify a find command that finds all the states in A as follows:
states= sA.find( '-isa','Stateflow.State')
then the above command finds three states: A, A1, and A2. You can refine your search by specifying an indefinite number of property and value pairs. If you want to limit search depth with find command, use the depth switch. See the method reference on the find method for a full description of this method and its parameters.
The following command returns an array of all transitions inside of state A (again, represented by State object sA) at all levels of containment:
transArray = sA.findDeep('Transition')
You must always specify an object type when you use the findShallow and findDeep methods. To find an array of all objects, deep or shallow, within an object, use the find command along with a depth specifier. For example, to find all the objects in State object sA at the first level of containment, use the following command:
objArray = sA.find('-depth', 1)
Dont forget, however, that the find command always includes the zeroth level of containment, the containing object itself. So, the above command also includes state A in the list of objects found.
11-22
11-23
11
Copying Objects
Copying in the Stateflow API is performed using the clipboard which is accessed as a Clipboard object. The Clipboard object and its two methods, copy and pasteTo are described in the following section: Clipboard Object and Methods on page 11-24 The copy method has features and limitations that are described in the following section: copy Method Features and Limitations on page 11-24 The features and limitation of the copy method allow you to copy objects grouped into a state or separately. These techniques are described in the following sections: Copying by Grouping (Recommended) on page 11-25 Copying Objects Individually on page 11-26 Copying Data, Event, and Target Objects on page 11-27
Clipboard objects have two methods, copy and pasteTo, which together provide the functionality to copy objects from one object to another. The copy method copies the specified objects to the Clipboard object, and the pasteTo method pastes the contents of the Clipboard to a new container.
11-24
Copying Objects
Copying graphical objects also copies the Data, Event, and Target objects that the graphical objects contain. To maintain the transition connections and containment relationships between copied objects you must copy the entire array of related objects. All related objects must be part of the array of objects copied to the Clipboard. For example, if you attempt to copy two states connected by a transition to another container, you can only accomplish this by copying both the states and the transition at the same time. That is, you must do a single copy of a single array containing both the states and the transition that connects them. If you copy a grouped state to the Clipboard, not only are all of the objects contained in the state copied, but all the relations among the objects in the grouped state are copied as well. Thus, copying by grouping is a recommended procedure. See the Copying by Grouping (Recommended) on page 11-25. If all copied objects are graphical, they must all be seen in the same subviewer. This means that all graphical objects copied in a single copy command must reside in the same chart or subchart.
11-25
11
6 If the source state was already grouped, youre finished. 7 Ungroup the copied object in its new container by setting its IsGrouped
property for that object to false (=0). Using the example at the end of the section Create New Objects in the Chart on page 11-7, you can copy state A and its contents from one chart to another with the API commands shown below. Assume that sA is a workspace handle to state A, and ch2 is a handle to chart2, where you want to copy state A.
sA.IsGrouped = 1 cb = sfclipboard cb.copy(sA)
Because state A was grouped only for the purpose of copying, you must now find the copied state A and ungroup it by setting its IsGrouped property to zero.
Note Copying objects with grouping is the preferred means for copying objects. The task of copying objects individually, object-by-object, is more formidable but discussed in detail in the following sections.
11-26
Copying Objects
You can also accomplish the job of constructing the copy array through a complex find command. This may be adequate in certain situations. However, this approach may require you to formulate a very complex command. By contrast, the technique of appending found objects to an array relies on simpler find commands.
11-27
11
Now use the workspace variable ed to access Editor object properties and methods. For example, the following command calls the zoomIn method to zoom in the chart by a factor of 20%:
ed.zoomIn
Or, you can simply set the ZoomFactor property of this charts editor to an absolute zoom factor of 150%:
ed.ZoomFactor = 1.5
Use a charts Editor object to also change the window position of the diagram editor. For a reference to all of the Editor objects properties and methods, see the sections Editor Properties on page B-6 and Editor Methods on page B-7.
11-28
There are two ways to enter the multiline labels for both states and transitions alike which are shown as examples below. In the examples, sA is a workspace variable handle to the State object in the Stateflow API for state A. Using the MATLAB function sprintf:
str = sprintf('A\nen: entrA()\ndu: duriA()\nex: exitA()') sA.LabelString = str
In this example carriage returns are seamlessly inserted into a string expression with the escape sequence '\n'. Using a concatenated string expression:
str = ['A',10,'entr: entrA()',10,'du: duriA()',10,'ex: exitA()'] sA.LabelString = str
In this example the carriage returns are inserted into a concatenated string expression with the ASCII equivalent to a carriage return, the integer 10.
11-29
11
11-30
A
API Properties and Methods by Use
API Reference by Use . . . . . . . . . . . . . . . . A-2 Reference Table Columns . . . . . . . . . . . . . . A-4
Structural
These properties and methods directly or indirectly affect the hierarchical structure of Stateflow objects within their charts. See sections Structural Properties on page A-6 and Structural Methods on page A-13. These properties and methods affect the behavioral aspects of the Stateflow chart. They change how the chart behaves in the execution of its diagram. See sections Behavioral Properties on page A-14 and Behavioral Methods on page A-20. These properties and methods affect how code is generated and deployed from a Stateflow chart. See sections Deployment Properties on page A-21 and Deployment Methods on page A-25. These properties and methods provide extra utility and convenience in manipulating Stateflow objects. See sections Utility and Convenience Properties on page A-26 and Utility and Convenience Methods on page A-28. These properties and methods are purely graphical in nature and affect only the appearance of Stateflow charts leaving the underlying hierarchy of objects unaffected. See sections Graphical Properties on page A-30 and Graphical Methods on page A-36.
Behavioral
Deployment
Graphical
Note Properties and methods listed in one use category may overlap into other use categories.
A-2
API properties and methods are also listed by their Stateflow objects. See API Properties and Methods by Object Type on page B-1.
A-3
R M C S B
T J E D X
A-4
Object
Abbreviation
Object
Abbreviation
Function Note
F N
Editor Clipboard
Editor Clipboard
A-5
Structural Properties
AStructural Properties
Structural properties directly or indirectly affect the hierarchical structure of Stateflow objects within their charts. See also Structural Methods on page A-13. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Property BadIntersection Type Acc Description Objects
Boolean
RO
If true, this object graphically intersects another state, box, or function in an invalid way. Chart object containing this object. Set this property to 'EXCLUSIVE_OR' to specify exclusive (OR) decomposition for the states at the first level of containment in this chart or state. Set to 'PARALLEL_AND' to specify parallel (AND) decomposition for these states. Equivalent to the Decomposition selection in the context menu for this chart or state. Destination state or junction of this transition. Assign Destination the destination object for this transition. You can also use the property Destination to detach the destination end of a transition through the command t.Destination = [] where t is the Transition object. Location of transition destination connection on state. Varies from 0 to 12 for full clock cycle location. Value taken as modulus 12 of entered value.
SBF
Chart
Chart Enum
RO RW
SBFN TJ CS
Decomposition
Destination
State or Junction
RW
DestinationOClock
Double
RW
A-6
Structural Properties
Property Iced
Type
Acc
Description
Objects
Boolean
RO
Equivalent to property Locked except that this property is used internally to lock this object from change during activities such as simulation. If set to true, group this state. Nothing is allowed to change inside of a grouped state. This property is also useful for copying states to a new location. See the section Copying by Grouping (Recommended) on page 11-25. If set to true, subcharts this state, box, or function. Label for this object. Equivalent to typing the label for this object in its label text field in the diagram editor. If set to true, prevents user from changing any Stateflow chart in this machine or chart. Machine that contains this object.
MC
IsGrouped
Boolean
RW
SBF
IsSubchart
Boolean String
RW RW
SBF SBFT
LabelString
Locked
Boolean Machine
RW RO
MC CSBF NTJD EX T
Machine
MidPoint
Rect
RW
Position of the midpoint of this transition relative to the upper left corner of the Stateflow diagram editor workspace in a 1-by-2 (x,y) point array. Name of this object. *This property is RW except for the name of machine object, which is RO.
Name
String
RW
MCSB FDEX
Integer
RO
A-7
Structural Properties
Property ParsedInfo. Array. FirstIndex ParsedInfo. InitialValue ParsedInfo. Range. Maximum ParsedInfo. Range. Minimum Position
Type
Acc
Description
Objects
Integer
RO
Numeric equivalent of Data property Props.Range.FirstIndex,a String. Numeric equivalent of Data property
Props.InitialValue, a String.
Double Double
RO RO
D D
Double
RO
Rect
RW
Position and size of this objects box in the Stateflow chart given in the form of a 1-by-4 array consisting of the following: 2-dim coordinate for the boxs left upper vertex (x,y) relative to the upper left vertex of the Stateflow diagram editor workspace. Width and height of the box.
SBFN
Position. Center
Rect
RW
Position of junction relative to the upper left vertex of the parent chart or state as x,y point array. Radius of this junction. Specifying a positive value for this property specifies that this data is an array of specified size. Equivalent to entering a positive value in the Size column for this data in the Explorer or in the Sizes field of the Properties dialog for this data.
Double String
RW RW
J D
A-8
Structural Properties
Type
Acc
Description
Objects
String
RW
Index of the first element of this data if it is an array (Props.Array.Size >= 1). Equivalent to entering a value of zero or greater in the First Index field of the Properties dialog for this data. If the source of the initial value for this data is the Stateflow data dictionary, this is the value used. Equivalent to entering this value in the InitVal column for this data in the Explorer or similar field in the Properties dialog for this data. Maximum value that this data can have during execution or simulation of the state machine. Equivalent to entering value in Max column for this data in Explorer or the Max field in the Properties dialog for this data. Minimum value that this data can have during execution or simulation of the state machine. Equivalent to entering value in Min column for this data in Explorer or the Min field in the Properties dialog for this data.
Props. InitialValue
String
RW
String
RW
String
RW
A-9
Structural Properties
Property Scope
Type
Acc
Description
Objects
Enum
RW
Scope of this data or event. Allowed values vary with the object containing this data or event and are as follows: The following apply to any data object: 'LOCAL_DATA' (Local) 'CONSTANT_DATA' (Constant) 'OUTPUT_DATA' (Output to Simulink) The following apply to data for machines only: 'IMPORTED_DATA' (Exported) 'EXPORTED_DATA' (Imported) The following apply to data for charts only: 'INPUT_DATA' (Input to Simulink) The following apply to data for charts and functions only: 'TEMPORARY_DATA' (Temporary) The following apply to data for functions only: 'FUNCTION_INPUT_DATA' (Input Data) 'FUNCTION_OUTPUT_DATA' (Output Data) The following apply to any event: 'LOCAL_EVENT' (Local) The following apply to events for charts only: 'INPUT_EVENT' (Input from Simulink) 'OUTPUT_EVENT' (Output to Simulink) The following apply to events for machines only: 'IMPORTED_EVENT' (Imported) 'EXPORTED_EVENT' (Exported)
DE
A-10
Structural Properties
Property Source
Type
Acc
Description
Objects
State or Junction
RW
Source state or junction of this transition. Assign Source the source object for this transition. You can also use the property Source to detach the source end of a transition with the command t.Source = [] where t is the Transition object. x,y spatial coordinates for the end point of a transition. *This property can be changed only for default transitions. For all other transitions it is RO (read only). Location of transition source connection on state. Varies from 0 to 12 for full clock cycle location. Value taken as modulus 12 of entered value. Label for this note. The text content for this note that you enter directly into the note in the diagram editor or in the Label field of the Properties dialog for this note.
SourceEndPoint
Rect
RO*
SourceOClock
Double
RW
Text
String
RW
A-11
Structural Properties
Property Trigger
Type
Acc
Description
Objects
Enum
RW
Type of signal that triggers this Input to Simulink or Output to Simulink event associated with its chart. Can be one of the following: 'EITHER_EDGE_EVENT' (Either Edge) 'RISING_EDGE_EVENT' (Rising Edge) 'FALLING_EDGE_EVENT' (Falling Edge) 'FUNCTION_CALL_EVENT' (Function Call) Equivalent to specifying the indicated parenthetical expression for the Trigger field of the Properties dialog for this event.
Type
Enum
RO
Type of this object. For states can be one of the following: 'OR' (inclusive) 'AND' (parallel) The type of a state is determined by the parents Decomposition property. For junctions can be one of the following: 'CONNECTIVE' 'HISTORY'
SJ
A-12
Structural Methods
AStructural Methods
Structural methods directly or indirectly affect the hierarchical structure of Stateflow objects within their charts. See also Structural Properties on page A-6. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Method copy Description Objects
Copy the specified array of objects to the clipboard. See also pasteTo method. Delete this object.
delete
pasteTo
Paste the objects in the Clipboard to the specified container object. See also copy method. Set the specified property of this object with a specified value. Used with all objects except the Root object.
set
All
A-13
Behavioral Properties
ABehavioral Properties
Behavioral properties affect the behavioral aspects of the Stateflow chart. They change how the chart behaves in the execution of its diagram. See also Behavioral Methods on page A-20. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Property Debug. Animation. Delay Debug. Animation. Enabled Type Acc Description Objects
Double
RW
Specify a value delay (slow down) animation. Equivalent to the Delay (sec) field in the Animation section of the Debugger window. If set to true, animation (simulation) is enabled If false (=0), disabled. Equivalent to the Enabled or Disabled radio button of the Animation section of the Debugger window. If set to true, set the chart entry breakpoint for all charts in this machine. Equivalent to the Chart Entry check box on the Debugger window. If set to true, set the event broadcast breakpoint for all charts in this machine. Equivalent to the Event Broadcast check box on the Debugger window. If set to true, set the chart entry breakpoint for all charts in this machine. Equivalent to the State Entry check box on the Debugger window. If set to true, set a debugger breakpoint for the end of the broadcase of this event. Equivalent to selecting the End of broadcast check box in the Properties dialog for this event.
Boolean
RW
Boolean
RW
Boolean
RW
Boolean
RW
Boolean
RW
A-14
Behavioral Properties
Type
Acc
Description
Objects
Boolean
RW
If set to true, set a debugger breakpoint for the start of the broadcast of this event. Equivalent to selecting the Start of broadcast check box in the Properties dialog for this event. If set to true, set the state entry breakpoint for this chart. Equivalent to checking the <object> During check box in the Properties dialog for this object. If set to true, set the entry breakpoint for this object. Equivalent to checking the <object> Entry check box in the Properties dialog for this object. If set to true, set the state entry breakpoint for this object. Equivalent to checking the <object> Exit check box in the Properties dialog for this object. If set to true, set a debugging breakpoint to occur when this transition is tested to see if it is a valid transition. Equivalent to checking When Tested check box in the Properties dialog of this transition. If set to true, set a debugging breakpoint to occur when this transition has tested valid. Equivalent to checking When Valid check box in the Properties dialog of this transition. If set to true, disables the use of all breakpoints in this machine. Equivalent to the Disable all check box in the Debugger window.
Boolean
RW
Boolean
RW
CS
Boolean
RW
Boolean
RW
Boolean
RW
Boolean
RW
A-15
Behavioral Properties
Type
Acc
Description
Objects
Boolean
RW
If set to true, check for state inconsistencies during a debug session. Equivalent to the State Inconsistency check box in the Debugger window. If set to true, check for transition conflicts during a debug session. Equivalent to the Transition Conflict check box in the Debugger window. If set to true, check for cyclical behavior errors during a debug session. Equivalent to the Detect Cycles check box in the Debugger window. If set to true, check for data range violations during a debug session. Equivalent to the Data Range check box in the Debugger window. If set to true, cause the debugger to halt execution if this data is modified. Setting this property to true is equivalent to checking the Watch column entry for this data in the Explorer or checking the Watch in debug check box in the Properties dialog for this data. Set this property to 'EXCLUSIVE_OR' to specify exclusive (OR) decomposition for the states at the first level of containment in this chart or state. Set to 'PARALLEL_AND' to specify parallel (AND) decomposition for these states. Equivalent to the Decomposition selection in the context menu for the chart or state.
Boolean
RW
Boolean
RW
Boolean
RW
Debug. Watch
Boolean
RW
Decomposition
Enum
RW
CS
A-16
Behavioral Properties
Property EnableBitOps
Type
Acc
Description
Objects
Boolean
RW
If set to true, enable C-like bit operations in generated code for this chart. Equivalent to Enable C-like bit operations check box in the chart Properties dialog. If set to true, this charts state configuration is initialized at time zero instead of first input event. Equivalent to Execute (enter) Chart at Initialization check box in chart Properties dialog Label for this object. Equivalent to typing the label for this object in its label text field in the diagram editor. Sample time for activating this chart. Applies only when the UpdateMethod property for this chart is set to 'DISCRETE' ( = Sampled in the Update method field in the Properties dialog for this chart).
ExecuteAt Initialization
Boolean
RW
LabelString
String
RW
SBFT
SampleTime
String
RW
A-17
Behavioral Properties
Property Scope
Type
Acc
Description
Objects
Enum
RW
Scope of this data or event. Allowed values vary with the object containing data or event. The following apply to any data object: 'LOCAL_DATA' (Local) 'CONSTANT_DATA' (Constant) 'OUTPUT_DATA' (Output to Simulink) The following apply to data for machines: 'IMPORTED_DATA' (Exported) 'EXPORTED_DATA' (Imported) The following apply to data for charts: 'INPUT_DATA' (Input to Simulink) The following apply to data for charts and functions: 'TEMPORARY_DATA' (Temporary) The following apply to data for functions: 'FUNCTION_INPUT_DATA' (Input Data) 'FUNCTION_OUTPUT_DATA' (Output Data) The following apply to any event: 'LOCAL_EVENT' (Local) The following apply to events for charts: 'INPUT_EVENT' (Input from Simulink) 'OUTPUT_EVENT' (Output to Simulink) The following apply to events for machines: 'IMPORTED_EVENT' (Imported) 'EXPORTED_EVENT' (Exported) Above values are equivalent to entering the value shown in parentheses in the Scope field of the Properties dialog or the Explorer for this data.
DE
A-18
Behavioral Properties
Property Trigger
Type
Acc
Description
Objects
Enum
RW
Type of signal that triggers this Input to Simulink or Output to Simulink event associated with its chart. Can be 'EITHER_EDGE_EVENT', or 'FUNCTION_CALL_EVENT'. Equivalent to specifying Either Edge or Function Call, respectively, in the Trigger field of the Properties dialog for this event. Activation method of this chart. Can be 'INHERITED', 'DISCRETE' or 'CONTINUOUS'. Equivalent to Update method field in the Properties dialog for this chart which takes one of the following corresponding selections: Triggered or Inherited, Sampled, Continuous.
UpdateMethod
Enum
RW
A-19
Behavioral Methods
ABehavioral Methods
Behavioral methods affect the behavioral aspects of the Stateflow chart. They change how the chart behaves in the execution of its diagram. See Behavioral Properties on page A-14. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Method outputData Description Objects
Output the activity status of this state to Simulink via a data output port on the chart block of this state. Parses all the charts in this machine (model) or just this chart.
S MC
parse
A-20
Deployment Properties
ADeployment Properties
Deployment properties affect how code is generated and deployed from a Stateflow chart. See Deployment Methods on page A-25. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Property ApplyToAllLibs Type Acc Description Objects
Boolean
RW
If set to true, use settings in this target for all libraries. Equivalent to checking the Use settings for all libraries check box in this targets Target Builder dialog. A MATLAB vector of structures containing information on n code flag settings for this target. Each element in the vector is a MATLAB structure with information about a particular code flag. Each flag corresponds to a selection in the Coder Options dialog for this target. If you want to see information about the first flag for a Target object t, use the following commands:
cfi = t.CodeFlagsInfo disp(cfi(1))
CodeFlagsInfo
Array
RO
If you want to quickly see the names of all the flags, do the following:
cfi.name
Name member of the CodeFlagsInfo structure is shorthand for a longer expression in the Coder Options dialog. For example, the name 'comments' actually refers to the dialog setting Comments in generated code. You use the name of a code flag to get and set the code flag value with the methods getCodeFlag and setCodeFlag. Changing the vector returned by CodeFlagsInfo does not change an actual flag.
A-21
Deployment Properties
Property CodegenDirectory
Type
Acc
Description
Objects
String String
RW RW
Directory to receive generated code. Applies only to targets other than sfun and rtw targets. Custom code included at the top of the generated code. Equivalent to the setting the Custom code included at the top of generated code selection of the Target Options dialog for this target. Custom initialization code. Equivalent to the setting the Custom initialization code (called from mdlInitialize) selection of the Target Options dialog for this target. Applies only to sfun and rtw targets. Custom termination code. Equivalent to the setting the Custom termination code (called from mdlTerminate) selection of the Target Options dialog for this target. Applies only to sfun and rtw targets. Data type of this data. Can have one of the following possible values: 'boolean', 'uint8',
X X
CustomCode
CustomInitializer
String
RW
CustomTerminator
String
RW
DataType
Enum
RW
entry in the Type column for this data in Explorer or the Type field in the Properties dialog for this data.
EnableBitOps
Boolean
RW
If set to true, enable C-like bit operations in generated code for this chart. Equivalent to Enable C-like bit operations check box in chart Properties dialog.
A-22
Deployment Properties
Type
Acc
Description
Objects
Boolean
RW
If set to true, initialize this charts state configuration at time zero instead of first input event. Equivalent to Execute (enter) Chart at Initialization check box in chart Properties dialog If set to true, graphical functions at chart level are made global. Equivalent to Export Chart Level Graphical Functions (Make Global) check box in chart Properties dialog. If set to true,initialize this data from the MATLAB workspace. Setting this property to true is equivalent to checking the FrWS column entry for this data in the Explorer or setting the Initialize from field to workspace in the Properties dialog for this data. If true, specifies that the current model builds a library and not an application. If set to true, no code is generated for this chart for custom targets (only for the simulation target, sfun). Equivalent to the No Code Generation for Custom Targets check box in the Properties dialog for this chart. State that this data belongs to If set to true, this data is saved to the MATLAB workspace. Setting this property to true is equivalent to checking the ToWS column entry for this data in the Explorer or checking the Save final value to base workspace field in the Properties dialog for this data.
ExportChart Functions
Boolean
RW
InitFromWorkspace
Boolean
RW
IsLibrary
Boolean Boolean
RO RW
M C
NoCodegenFor CustomTargets
OutputState SaveToWorkspace
State Boolean
RO RW
D D
A-23
Deployment Properties
Type
Acc
Description
Objects
Boolean
RW
If set to true, set strong data typing with Simulink I/O. Equivalent to the Use Strong Data Typing with Simulink I/O check box in the chart Properties dialog. Custom include directory paths. Equivalent to the setting of the Custom include directory paths selection of the Target Options dialog for this target. Custom libraries Equivalent to the setting of the Custom libraries selection of the Target Options dialog for this target. Custom source files. Equivalent to the setting of the Custom source files selection of the Target Options dialog for this target.
UserIncludeDirs
Boolean
RW
UserLibraries
String
RW
UserSources
String
RW
A-24
Deployment Methods
ADeployment Methods
Deployment methods affect how code is generated and deployed from a Stateflow chart. See also Deployment Properties on page A-21. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Method build Description Objects
Build this target only those portions of the targets charts that have changed since the last build (i.e., incrementally). See also the methods rebuildAll, generate, rebuildAll, and make. Generate code for this target only for those portions of this targets charts that have changed since the last code generation (i.e., incrementally). See also the methods build, rebuildAll, regenerateAll, and make. Return the value of the specified code flag for this target. Compile this target for only those portions of this targets charts that have changed since the last compile (i.e., incrementally). For a simulation target (sfun), a dynamic link library (sfun.dll) is compiled from the generated code. See also the methods build, rebuildAll, generate, and regenerateAll. Completely rebuild this target. See also the methods build, generate, regenerateAll, and make. Completely regenerate code for this target. See also the methods build, rebuildAll, generate, and make. Set the value of the specified code flag for this target.
generate
getCodeFlag make
X X
rebuildAll
X X X
regenerateAll
setCodeFlag
A-25
Utility and convenience properties maintain the infrastructure of the Stateflow API and also provide useful intermediate services for using the Stateflow API. See Utility and Convenience Methods on page A-28. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Property Created Creator Description Type Acc Description Objects
RO RW RW
Date of creation of this machine. Creator of this machine. Description of this object. Equivalent to entering a description in the Description field of the Properties dialog for this object. If true, this object has changed since it was opened or saved. Document link to this note. Equivalent to entering the Document Link field of the Properties dialog for this object. Unique identifier assigned to this object to distinguish it from other objects loaded in memory. Comment area for entering date and name of modification to this machine (model). Full version number for current Stateflow. For example, the string '41112101' appears for Stateflow version 4.1.1 and MATLAB version 12.1. The remaining '01' is for internal use. A field you can use to hold data of any type for this object.
Dirty
Boolean String
RO RW
Document
Id
Integer
RO
Modified
String Double
RW RO
SfVersion
Tag
Any Type
RW
MCSB FTJD EX
A-26
Property Units
Type
Acc
Description
Objects
String String
RW RW
Physical units corresponding to the value of this data object. Comment string for recording version of this model.
D M
Version
A-27
Utility and convenience properties maintain the infrastructure of the Stateflow API and also provide useful intermediate services for using the Stateflow API. See also Utility and Convenience Properties on page A-26. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Method classhandle Description Objects
Return a read-only handle to the class (object type) used to define this object. Return the default transitions in this chart at the top level of containment. Display the Properties dialog of this object.
defaultTransitions
dialog
find
Return objects of this object that meet the criteria specified by the arguments. Return all objects of specified type in this object at all levels of containment (i.e., infinite depth). Return all objects of specified type in this object at only the first level of containment (i.e., first depth). Display the property settings of this object. Display a list of properties for this object with short descriptions. Used with all objects except the Root and Machine object. Return the inner transitions that originate with this object and terminate on a contained object. Return the methods of this object.
findDeep
findShallow
get help
innerTransitions
SBF All
methods
A-28
Method outerTransitions
Description
Objects
Return an array of transitions that exit the outer edge of this object and terminate on an object outside the containment of this object. Return a handle to the Clipboard object Close all Stateflow diagrams and Simulink models containing Stateflow diagrams, and exit the Stateflow environment. Caution Executing the sfexit method causes all models in Simulink to close without a request to save.
SBF
sfclipboard sfexit
Global Global
sfhelp sfnew
Display Stateflow online help in the MATLAB Help browser. Create and display a new Simulink model containing an empty Stateflow block. Print the visible portion of a Stateflow diagram. Return a handle to the Root object Save the current machine and Simulink model. Open the current Stateflow model window. Return all inner and outer transitions whose source is this object. Return a MATLAB structure containing the property settings of this object. Display this object in a Stateflow diagram editor.
Global Global Global Global Global Global SBFJ CSBFN TJDEX CSBFN TJDEX
struct
view
A-29
Graphical Properties
AGraphical Properties
Graphical properties perform services that are presentational (graphic) only and do not affect the actual Stateflow structure of objects. Those graphical properties that do affect this underlying structure are included in the section Structural Properties on page A-6. See also Graphical Methods on page A-36. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Property Alignment Type Acc Description Objects
Enum Double
RW RW
N SBFT J C
ArrowSize
Size of transition arrows coming into this object. Equivalent to selecting Arrowhead Size from context menu for state. Background color of this chart in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Set the drawing style for this transition. Set to 'STATIC' for static transitions or 'SMART' for smart transitions. Equivalent to selecting Smart switch toggle from context menu for this transition. Set the RGB color for errors in the Stateflow Diagram Editor in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing Error color in the Colors & Fonts dialog under Edit > Style. Name of the font for the text in this note. This property is read only (RO) and set by the StateFont.Name property of the Chart object containing this note.
ChartColor
[R,G,B]
RW
DrawStyle
String
RW
ErrorColor
[R,G,B]
RW
Font.
String
RO
Name
A-30
Graphical Properties
Property Font.
Type
Acc
Description
Objects
Enum
RW
Angle
Style of the font for the text in this note. Can be 'ITALIC' or 'NORMAL'. This property overrides the default style for this note which is set by the StateFont.Angle property of the Chart object containing this note. Size of the font for the label text for this note. This property overrides the default size for this note which is set by the StateFont.Size property of the Chart object containing this note. Equivalent to selecting Font Size > ... in the context menu for this note. Weight of the font for the label text for this note. Can be 'BOLD' or 'NORMAL'. This property overrides the default weight for the text in this note which is set by the StateFont.Weight property of the Chart object containing this note. Size of the font for the label text for this object. This property overrides the default size for this object which is set by the StateFont.Size property (TransitionFont.Size for transitions) of the Chart object containing this object. Equivalent to selecting Font Size > ... in the context menu for this object. How the text in this note is interpreted for text processing. Can be 'NORMAL' or 'TEX'. Set the RGB color for junctions in the Stateflow Diagram Editor in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing Junction color in the Colors & Fonts dialog under Edit > Style.
Font.
Double
RW
Size
Font.
Enum
RW
Weight
FontSize
Double
RW
SBFT
Interpretation
Enum [R,G,B]
RW RW
N C
JunctionColor
A-31
Graphical Properties
Property LabelPosition
Type
Acc
Description
Objects
Rect
RW
Position and size of this transitions label in the Stateflow chart given in the form of a 1-by-4 array consisting of the following: 2-dim coordinate for the labels left upper vertex (x,y) relative to the upper left vertex of the Stateflow diagram editor workspace. Width and height of the label.
SelectionColor
[R,G,B]
RW
Color of selected items for this chart in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing Selection color in the Colors & Fonts dialog under Edit > Style. Color of the state box in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing State/Frame color in the Colors & Fonts dialog under Edit > Style. Font angle for the labels of State, Box, Function, and Note objects. Can be 'ITALIC' or 'NORMAL'. Equivalent to Italic and Regular settings when changing font style of StateLabel in the Colors & Fonts dialog under Edit > Style. Use with property StateFont.Weight to achieve Bold Italic style. You can individually override this property with the Font.Angle property for Note objects. Font style used for the labels of State, Box, Function, and Note objects. Enter a string for the font name no selectable values. Font remains set to previous font for unrecognized font strings. Equivalent to changing the font of StateLabel in the Colors & Fonts dialog under Edit > Style.
StateColor
[R,G,B]
RW
StateFont. Angle
Enum
RW
StateFont. Name
String
RW
A-32
Graphical Properties
Type
Acc
Description
Objects
Integer
RW
Font size for the labels of State, Box, Function, and Note objects. Equivalent to changing the font size of StateLabel in the Colors & Fonts dialog under Edit > Style. You can individually override this property with the FontSize property for State, Box, and Function objects and with the Font.Size property for Note objects. Font weight for state labels. Can be 'BOLD' or 'NORMAL'. Equivalent to Bold and Regular settings of StateLabel in the Colors & Fonts dialog under Edit > Style. Use with the property StateFont.Angle to achieve Bold Italic style. You can individually override this property with the Font.Weight property for Note objects.
StateFont. Weight
Enum
RW
StateLabelColor
[R,G,B]
RW
Color of the state labels for this chart in 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing label color of StateLabel in the Colors & Fonts dialog under Edit > Style. State or chart in which this object can be graphically viewed. Set the RGB color for transitions in the Stateflow Diagram Editor in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing Transition color in the Colors & Fonts dialog under Edit > Style.
Subviewer
RO RW
SBFN TJ C
TransitionColor
A-33
Graphical Properties
Type
Acc
Description
Objects
Enum
RW
(Enum, RW)
Font angle for state labels. Can be 'ITALIC' or 'NORMAL'. Equivalent to Italic and Regular settings when changing font style of TransitionLabel in the Colors & Fonts dialog under Edit > Style. Use with property StateFont.Weight to achieve Bold Italic style. Font used for transition labels. Enter string for font name - no selectable values. Font remains set to previous font for unrecognized font strings. Equivalent to changing font of TransitionLabel in the Colors & Fonts dialog under Edit > Style. Default font size for transition labels. Truncated to closest whole number less than or equal to entered value. Equivalent to changing font size of TransitionLabel in the Colors & Fonts dialog under Edit > Style. Font weight for transition labels. Can be
'BOLD' or 'NORMAL'. Equivalent to Bold and
TransitionFont. Name
String
RW
TransitionFont. Size
Integer
RW
TransitionFont. Weight
Enum
RW
Regular settings when changing font style of TransitionLabel in the Colors & Fonts dialog under Edit > Style. Use with property
StateFont.Angle to achieve Bold Italic style. Transition LabelColor
[R,G,B]
RW
Color of the transition labels for this chart in 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing label color of TransitionLabel in the Colors & Fonts dialog under Edit > Style. If true, indicates that this object is currently displayed in a Stateflow diagram editor window.
Visible
Boolean
RO
A-34
Graphical Properties
Property WindowPosition
Type
Acc
Description
Objects
Rect
RW
Position and size of this chart given in the form of a 1-by-4 array consisting of the following: 2-dim coordinate for the windows left bottom vertex (x,y) relative to the lower left corner of the screen. Width and height of the box.
Editor
ZoomFactor
Double
RW
View magnification level (zoom factor) of this chart in the chart diagram editor.
Editor
A-35
Graphical Methods
AGraphical Methods
Graphical methods perform services that are presentational (graphic) only and do not affect the actual Stateflow structure of objects. See also Graphical Properties on page A-30. For a key to the abbreviations for object types in the Object column, see the section Reference Table Columns on page A-4.
Method zoomIn and zoomOut Description Objects
Causes the Stateflow chart editor to zoom in or zoom out on this chart.
Editor
A-36
B
API Properties and Methods by Object Type
API Reference by Object Type . . . . . . . . . . . . B-2 Reference Table Columns . . . . . . . . . . . . . . B-3
Independent of object type All Editor Clipboard Root Machine Chart State Box Function Transition Junction Data Event Target
NA NA Editor Properties on page B-6 (no properties) (no properties) Machine Properties on page B-10 Chart Properties on page B-14 State Properties on page B-20 Box Properties on page B-24 Function Properties on page B-27 Transition Properties on page B-33 Junction Properties on page B-37 Data Properties on page B-39 Event Properties on page B-44 Target Properties on page B-47
Global Methods Methods that Apply to All Objects on page B-5 Editor Methods on page B-7 Clipboard Methods on page B-8 Root Methods on page B-9 Machine Methods on page B-13 Chart Methods on page B-19 State Methods on page B-23 Box Methods on page B-26 Function Methods on page B-29 Transition Methods on page B-36 Junction Methods on page B-38 Data Methods on page B-43 Event Methods on page B-46 Target Methods on page B-50
B-2
B-3
Global Methods
BGlobal Methods
The following methods do not belong to any API object, including Stateflow objects. See the section API Methods Reference on page C-1 for details on each method.
Method Name sfclipboard sfexit Description
Return a handle to the Clipboard object Close all Stateflow diagrams and Simulink models containing Stateflow diagrams, and exit the Stateflow environment. Caution Executing the sfexit() method causes all models in Simulink to close without a request to save.
sfhelp sfnew
Display Stateflow online help in the MATLAB Help browser. Create and display a new Simulink model containing an empty Stateflow block. Print the visible portion of a Stateflow diagram. Return a handle to the Root object Save the current machine and Simulink model. Open the current Stateflow model window.
B-4
The following methods apply to all API objects including those of Stateflow. They are not included in the method sections that follow which list only Stateflow object exclusive methods. Object exclusive methods appear when you use the method methods to display methods for an object. See the API Methods Reference for details on each method.
Method Name classhandle Description
Return a read-only handle to the class (object type) used to define this object. Delete this object. Used with all objects except the Root, Machine, Chart, Clipboard, and Editor objects. Find all objects of this object that meet the specified criteria. Display the specified property settings for this object. Display the methods of this object. Set the specified property of this object with a specified value. Return a MATLAB structure containing the property settings of this object.
delete
B-5
Editor Properties
BEditor Properties
The Editor object has the properties in the table below. See also Editor Methods on page B-7.
Property WindowPosition Type Acc Description
Rect
RW
Position and size of this chart given in the form of a 1-by-4 array consisting of the following: 2-dim coordinate for the windows left bottom vertex (x,y) relative to the lower left corner of the screen. Width and height of the box.
ZoomFactor
Double
RW
View magnification level (zoom factor) of this chart in the chart diagram editor.
B-6
Editor Methods
BEditor Methods
The Editor object has the methods in the table below. See the API Methods Reference for details on each method. See also Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Editor objects. Also see Editor Properties on page B-6.
Method Name zoomIn and zoomOut Description
Cause the Stateflow chart editor to zoom in or zoom out on this chart.
B-7
Clipboard Methods
BClipboard Methods
The Clipboard object has the methods listed in the table below. See the API Methods Reference for details on each method. See also Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Clipboard objects.
Method Name copy pasteTo Description
Copy the objects specified to this clipboard. Paste the contents of this clipboard to the specified container object.
B-8
Root Methods
BRoot Methods
Stateflow API objects of type Root have the methods listed in the table below. See the API Methods Reference on page C-1 for details on each method. See also Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Root objects.
Method findDeep Description
Return all objects of specified type in this object at all levels of containment (i.e., infinite depth). Return all objects of specified type in this object at only the first level of containment (i.e., first depth). Display a list of properties for the Root object with short descriptions.
findShallow
help
B-9
Machine Properties
BMachine Properties
Stateflow API objects of type Machine have the properties shown in the table below. See also Machine Methods on page B-13.
Property Created Creator Debug. Animation. Enabled Type Acc Description
RO RW RW
Date of creation of this machine. Creator of this machine. If set to true, animation (simulation) is enabled. If false (=0), disabled. Equivalent to the Enabled or Disabled radio button of the Animation section of the Debugger window. Specify a value to delay (slow down) animation. Equivalent to the Delay (sec) field in the Animation section of the Debugger window. If set to true, set the chart entry breakpoint for all charts in this machine. Equivalent to the Chart Entry check box in the Debugger window. If set to true, set the event broadcast breakpoint for all charts in this machine. Equivalent to the Event Broadcast check box in the Debugger window. If set to true, set the chart entry breakpoint for all charts in this machine. Equivalent to the State Entry check box in the Debugger window. If set to true, disable the use of all breakpoints in this machine. Equivalent to the Disable all check box in the Debugger window. If set to true, check for state inconsistencies during a debug session. Equivalent to the State Inconsistency check box in the Debugger window. If set to true, check for transition conflicts during a debug session. Equivalent to the Transition Conflict check box in the Debugger window.
Debug. Animation. Delay Debug. BreakOn. ChartEntry Debug. BreakOn. EventBroadcast Debug. BreakOn. StateEntry Debug. DisableAllBreakpoints
Double
RW
Boolean
RW
Boolean
RW
Boolean
RW
Boolean
RW
Boolean
RW
Boolean
RW
B-10
Machine Properties
Type
Acc
Description
Boolean
RW
If set to true, check for cyclical behavior errors during a debug session. Equivalent to the Detect Cycles check box in the Debugger window. If set to true, check for data range violations during a debug session. Equivalent to the Data Range check box in the Debugger window. Description of this state. Equivalent to entering a description in the Description field of the Properties dialog for this machine. If true, this model has changed since it was opened or saved. Document link to this machine. Equivalent to entering the Document Link field of the Properties dialog for this machine. Equivalent to property Locked except that this property is used internally to lock this model from change during activities such as simulation. Unique identifier assigned to this machine to distinguish it from other objects loaded in memory. If true, specifies that the current model builds a library and not an application. If set to true, prevents user from changing any Stateflow chart in this model. Comment area for entering date and name of modification to this model. Name of this model set when saved to disk.
Boolean
RW
String
RW
Dirty
Boolean String
RO RW
Document
Iced
Boolean
RO
Id
RO RO RW RW RO
isLibrary
Locked
Modified
Name
B-11
Machine Properties
Property SfVersion
Type
Acc
Description
Double
RO
Full version number for current Stateflow. For example, the string '41112101' appears for Stateflow version 4.1.1 and MATLAB version 12.1. The remaining '01' is for internal use. A field you can use to hold data of any type for this machine. Comment string for recording version of this model.
Tag
RW RW
Version
B-12
Machine Methods
BMachine Methods
Stateflow API objects of type Machine have the methods shown in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Machine objects. Also see Machine Properties on page B-10.
Method dialog findDeep Description
Display the Properties dialog of this machine. Return all objects of specified type in this machine at all levels of containment (i.e., infinite depth). Return all objects of specified type in this machine at only the first level of containment (i.e., first depth). Display a list of properties for this Machine object with short descriptions. Parse all the charts in this machine.
findShallow
help
parse
B-13
Chart Properties
BChart Properties
Stateflow API objects of type Chart have the properties shown below. See also Chart Methods on page B-19.
Property ChartColor Type Acc Description
[R,G,B] Boolean
RW RW
Background color of this chart in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. If set to true, set the chart entry breakpoint for this chart. Equivalent to the Chart Entry check box in the Properties dialog for this chart. Set this property to 'EXCLUSIVE_OR' to specify exclusive (OR) decomposition for the states at the first level of containment in this chart. Set to 'PARALLEL_AND' to specify parallel (AND) decomposition for these states. Equivalent to the Decomposition selection in the context menu for the Stateflow diagram editor. Description of this state. Equivalent to entering a description in the Description field of the Properties dialog for this chart. If true, this chart has been changed since being opened or saved. Document link to this chart. Equivalent to entering the
Document Link field of the Properties dialog for this
Enum
RW
Description
String
RW
Dirty
Boolean String
RW RW
Document
chart.
EnableBitOps
Boolean
RW
If set to true, enables C-like bit operations in generated code for this chart. Equivalent to Enable C-like bit operations check box in the chart Properties dialog. Set the RGB color for errors in the Stateflow Diagram Editor in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing Error color in the Colors & Fonts dialog under Edit > Style.
ErrorColor
[R,G,B]
RW
B-14
Chart Properties
Type
Acc
Description
Boolean
RW
If set to true, this charts state configuration is initialized at time zero instead of first input event. Equivalent to Execute (enter) Chart at Initialization check box in chart Properties dialog If set to true, graphical functions at chart level are made global. Equivalent to Export Chart Level Graphical Functions (Make Global) check box in chart Properties dialog. Equivalent to property Locked except that this property is used internally to lock this chart from change during activities such as simulation. Unique identifier assigned to this chart to distinguish it from other objects loaded in memory. Set the RGB color for junctions in the Stateflow Diagram Editor in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing Junction color in the Colors & Fonts dialog under Edit > Style. If set to true, mark this chart as read-only and prohibit any write operations on it. Equivalent to the Locked check box in the Editor section of the Properties dialog for this chart. Machine that contains this chart. Name of this chart. Equivalent to changing the name of this charts Stateflow block in Simulink. If set to true, no code is generated for this chart for custom targets (only for the simulation target, sfun). Equivalent to the No Code Generation for Custom Targets check box in the Properties dialog for this chart.
ExportChart Functions
Boolean
RW
Iced
Boolean
RO
Id
Integer [R,G,B]
RO RW
JunctionColor
Locked
Boolean
RW
Machine Name
RO RW RW
NoCodegenFor CustomTargets
B-15
Chart Properties
Property SampleTime
Type
Acc
Description
String
RW
Sample time for activating this chart. Applies only when the UpdateMethod property for this chart is set to 'DISCRETE' ( = Sampled in the Update method field in the Properties dialog for this chart). Color of selected items for this chart in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing Selection color in the Colors & Fonts dialog under Edit > Style. Color of the state box in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing State/Frame color in the Colors & Fonts dialog under Edit > Style. Font angle for the labels of State, Box, Function, and Note objects. Can be 'ITALIC' or 'NORMAL'. Equivalent to Italic and Regular settings when changing font style of StateLabel in the Colors & Fonts dialog under Edit > Style. Use with property StateFont.Weight to achieve Bold Italic style. You can individually override this property with the Font.Angle property for Note objects. Font style used for the labels of State, Box, Function, and Note objects. Enter a string for the font name no selectable values. Font remains set to previous font for unrecognized font strings. Equivalent to changing the font of StateLabel in the Colors & Fonts dialog under Edit > Style. Font size for the labels of State, Box, Function, and Note objects. Equivalent to changing the font size of StateLabel in the Colors & Fonts dialog under Edit > Style. You can individually override this property with the FontSize property for State, Box, and Function objects and with the Font.Size property for Note objects.
SelectionColor
[R,G,B]
RW
StateColor
[R,G,B]
RW
StateFont. Angle
Enum
RW
StateFont. Name
String
RW
StateFont. Size
Integer
RW
B-16
Chart Properties
Type
Acc
Description
Enum
RW
Font weight for state labels. Can be 'BOLD' or 'NORMAL'. Equivalent to Bold and Regular settings of
StateLabel in the Colors & Fonts dialog under Edit > Style. Use with the property StateFont.Angle to
achieve Bold Italic style. You can individually override this property with the Font.Weight property for Note objects.
StateLabelColor
[R,G,B]
RW
Color of the state labels for this chart in 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing label color of StateLabel in the Colors & Fonts dialog under Edit > Style. If set to true, set strong data typing with Simulink I/O. Equivalent to selecting the Use Strong Data Typing with Simulink I/O check box in the chart Properties dialog. A field you can use to hold data of any type for this chart. Set the RGB color for transitions in the Stateflow Diagram Editor in a 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing Transition color in the Colors & Fonts dialog under Edit > Style. Font angle for state labels. Can be 'ITALIC' or 'NORMAL'. Equivalent to Italic and Regular settings when changing font style of TransitionLabel in the Colors & Fonts dialog under Edit > Style. Use with property StateFont.Weight to achieve Bold Italic style.
StrongDataTyping WithSimulink
Boolean
RW
Tag
RW RW
TransitionColor
TransitionFont. Angle
Enum
RW
B-17
Chart Properties
Type
Acc
Description
String
RW
Font used for transition labels. Enter a string for font name - no selectable values. Font remains set to previous font for unrecognized font strings. Equivalent to changing the font of TransitionLabel in the Colors & Fonts dialog under Edit > Style. Default font size for transition labels. Truncated to closest whole number less than or equal to entered value. Equivalent to changing the font size of TransitionLabel in the Colors & Fonts dialog under Edit > Style. Font weight for transition labels. Can be 'BOLD' or 'NORMAL'. Equivalent to Bold and Regular settings when changing font style of TransitionLabel in the Colors & Fonts dialog under Edit > Style. Use with property StateFont.Angle to achieve Bold Italic style.
TransitionFont. Size
Integer
RW
TransitionFont. Weight
Enum
RW
TransitionLabel Color
[R,G,B]
RW
Color of the transition labels for this chart in 1-by-3 RGB array with each value normalized on a scale of 0 to 1. Equivalent to changing label color of TransitionLabel in the Colors & Fonts dialog under Edit > Style. Activation method of this chart. Can be 'INHERITED', 'DISCRETE' or 'CONTINUOUS'. Equivalent to Update method field in the Properties dialog for this chart which takes one of the following corresponding selections: Triggered or Inherited, Sampled, Continuous. If set to true, display this chart in the chart diagram editor.
UpdateMethod
Enum
RW
Visible
Boolean
RW
B-18
Chart Methods
BChart Methods
Stateflow API objects of type Chart have the methods shown in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Chart objects. Also see Chart Properties on page B-14
Method defaultTransitions Description
Return the default transitions in this chart at the top level of containment. Display the Properties dialog of this chart. Return all objects of specified type in this chart at all levels of containment (i.e., infinite depth). Return all objects of specified type in this chart at only the first level of containment (i.e., first depth). Display a list of properties for this Chart object with short descriptions. Parse this chart. Display this chart in a Stateflow diagram editor.
dialog findDeep
findShallow
help
parse view
B-19
State Properties
BState Properties
Stateflow API objects of type State have the properties listed in the table below. See also State Methods on page B-23
Property ArrowSize Type Acc Description
Double
RW
Size of transition arrows coming into this state. Equivalent to selecting Arrowhead Size from the context menu for this state. If true, this state graphically intersects a box, graphical function, or other state. Chart object containing this state. If set to true, set the state entry breakpoint for this chart. Equivalent to selecting the State During check box in the Properties dialog for this state. If set to true, set the state entry breakpoint for this chart. Equivalent to selecting the State Entry check box in the Properties dialog for this state. If set to true, set the state entry breakpoint for this chart. Equivalent to selecting the State Exit check box in the Properties dialog for this state. Set this property to 'EXCLUSIVE_OR' to specify exclusive (OR) decomposition for the states at the first level of containment in this state. Set to 'PARALLEL_AND' to specify parallel (AND) decomposition for these states. Equivalent to the Decomposition selection in the context menu for the state. Description of this state. Equivalent to entering a description in the Description field of the Properties dialog for this state. Document link to this state. Equivalent to entering the
Document Link field of the Properties dialog for this
BadIntersection
RO RO RW
Chart Debug. Breakpoints. onDuring Debug. Breakpoints. OnEntry Debug. Breakpoints. onExit Decomposition
Boolean
RW
Boolean
RW
Enum
RW
Description
String
RW
Document
String
RW
state.
B-20
State Properties
Property FontSize
Type
Acc
Description
Double
RW
Size of the font for the label text for this state. This property overrides the default size for this state which is set by the StateFont.Size property of the Chart object containing this state. Equivalent to selecting Font Size > ... in the context menu for this state. Unique identifier assigned to this state to distinguish it from other objects loaded in memory. If set to true, group this state. Nothing is allowed to change inside of a grouped state. This property is also useful for copying states to a new location. See the section Copying by Grouping (Recommended) on page 11-25. If set to true, subchart this state. Label for this state. Equivalent to typing the label for this state in its label text field in the diagram editor. Machine containing this state. Name of this state. Equivalent to typing this states name into the beginning of the label text field for this state in the diagram editor. Name is separated from the remainder of this states label text by a forward slash ( /) character. Position and size of this states box in the Stateflow chart given in the form of a 1-by-4 array consisting of the following: (x,y) coordinates for the boxs left upper vertex relative to the upper left vertex of the Stateflow diagram editor workspace. Width and height of the box.
Id
Integer Boolean
RO RW
IsGrouped
IsSubchart LabelString
RW RW RO RW
Machine Name
Position
Rect
RW
Subviewer
Chart or State
RO
B-21
State Properties
Property Tag
Type
Acc
Description
RW RO
A field you can use to hold data of any type for this state. Type of this state. Can be 'OR' (inclusive) or 'AND' (parallel). The type of this state is determined by the parents Decomposition property.
Type
B-22
State Methods
BState Methods
Stateflow API objects of type State have the methods listed in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including State objects. Also see State Properties on page B-20
Method defaultTransitions Description
Return the default transitions in this state at the top level of containment. Display the Properties dialog of this state. Return all objects of specified type in this state at all levels of containment (i.e., infinite depth). Return all objects of specified type in this state at only the first level of containment (i.e., first depth). Display a list of properties for this State object with short descriptions. Return the inner transitions that originate with this state and terminate on a contained object. Return an array of transitions that exit the outer edge of this state and terminate on an object outside the containment of this state. Output the activity status of this state to Simulink via a data output port on the chart block of this state. Return all inner and outer transitions whose source is this state. Display this states chart in a diagram editor with this state highlighted.
dialog findDeep
findShallow
help innerTransitions
outerTransitions
outputData
sourcedTransitions view
B-23
Box Properties
BBox Properties
The following are properties of Stateflow API objects of type Box. See also Box Methods on page B-26.
Property ArrowSize Type Acc Description
Double
RW
Size of transition arrows coming into this box. Equivalent to selecting Arrowhead Size from the context menu for this box. If true, this box graphically intersects a state, graphical function, or other box. Chart object containing this box. Description of this box. Equivalent to entering a description in the Description field of the Properties dialog for this box. Document link to this box. Equivalent to entering the Document Link field of the Properties dialog for this box. Size of the font for the label text for this box. This property overrides the default size for this box which is set by the StateFont.Size property of the Chart object containing this box. Equivalent to selecting Font Size > ... in the context menu for this box. Unique identifier assigned to this box to distinguish it from other objects loaded in memory. If set to true, group this box. If set to true, subchart this box. Label for this box. Equivalent to typing the label for this box in its label text field in the diagram editor. Machine that contains this box.
BadIntersection
RO RO RW
Chart Description
Document
String
RW
FontSize
Double
RW
Id
RW RW RW RW RO
Machine
B-24
Box Properties
Property Name
Type
Acc
Description
String
RW
Name of this box. Equivalent to typing this boxs name into the beginning of the label text field for this box in the diagram editor. Position and size of this boxs box in the Stateflow chart given in the form of a 1-by-4 array consisting of the following: (x,y) coordinate for the boxs left upper vertex relative to the upper left vertex of the Stateflow diagram editor workspace. Width and height of the box.
Position
Rect
RW
Subviewer
RO RW
State or chart in which this box can be graphically viewed. A field you can use to hold data of any type for this box.
Tag
B-25
Box Methods
BBox Methods
Stateflow API objects of type Box have the methods listed in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Box objects. Also see Box Properties on page B-24.
Method defaultTransitions Description
Return the default transitions in this box at the top level of containment. Display the Properties dialog of this box. Return all objects of specified type in this box at all levels of containment (i.e., infinite depth). Return all objects of specified type in this box at only the first level of containment (i.e., first depth). Display a list of properties for this Box object with short descriptions. Return the inner transitions that originate with this box and terminate on a contained object. Return an array of transitions that exit the outer edge of this box and terminate on an object outside the containment of this box. Return all inner and outer transitions whose source is this box. Display this boxs chart in a diagram editor with this box highlighted.
dialog findDeep
findShallow
help innerTransitions
outerTransitions
sourcedTransitions view
B-26
Function Properties
BFunction Properties
Stateflow API objects of type Function have the properties listed in the table below. See also Function Methods on page B-29.
Property ArrowSize Type Acc Description
Double
RW
Size of transition arrows coming into this function. Equivalent to selecting Arrowhead Size from the context menu for this function. If true, this state graphically intersects a state, box, or other graphical function. Chart object containing this function. Description of this function. Equivalent to entering a description in the Description field of the Properties dialog for this function. Document link to this function. Equivalent to entering the Document Link field of the Properties dialog for this function. Size of the font for the label text for this function. This property overrides the default size for this function which is set by the StateFont.Size property of the Chart object containing this function. Equivalent to selecting Font Size > ... in the context menu for this function. Unique identifier assigned to this function to distinguish it from other objects in the model. If set to true, group this function. If set to true, subchart this function. Label for this function. Equivalent to typing the label for this function in its label text field in the diagram editor. Machine that contains this function.
BadIntersection
RO RO RW
Chart Description
Document
String
RW
FontSize
Double
RW
Id
RO RW RW RW RO
Machine
B-27
Function Properties
Property Name
Type
Acc
Description
String
RW
Name of this function. Equivalent to typing this functions name into the beginning of the label text field after the word 'function' in the diagram editor. Position and size of this functions box in the Stateflow chart given in the form of a 1-by-4 array consisting of the following: (x,y) coordinate for the boxs left upper vertex relative to the upper left vertex of the Stateflow diagram editor workspace. Width and height of the box.
Position
Rect
RW
Subviewer
RO RW
State or chart in which this function can be graphically viewed. A field you can use to hold data of any type for this function.
Tag
B-28
Function Methods
BFunction Methods
Stateflow API objects of type Function have the methods listed in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Function objects. Also see Function Properties on page B-27.
Method defaultTransitions Description
Return the default transitions in this function at the top level of containment. Displays the Properties dialog of this function. Return all objects of specified type in this function at all levels of containment (i.e., infinite depth). Return all objects of specified type in this function at only the first level of containment (i.e., first depth). Display a list of properties for this Function object with short descriptions. Return the inner transitions that originate with this function and terminate on a contained object. Return an array of transitions that exit the outer edge of this function and terminate on an object outside the containment of this function. Return all inner and outer transitions whose source is this function. Display this functions chart in a diagram editor with this state highlighted.
dialog findDeep
findShallow
help
innerTransitions
outerTransitions
sourcedTransitions view
B-29
Note Properties
BNote Properties
Stateflow API objects of type Note have the properties listed in the table below. See also Note Methods on page B-32.
Property Alignment Type Acc Description
RW RO RW
Alignment of text in note box. Can be 'LEFT', 'CENTER', or 'RIGHT'. Chart object containing this note. Description of this note. Equivalent to entering a description in the Description field of the Properties dialog for this note. Document link to this note. Equivalent to entering the
Document Link field of the Properties dialog for this note.
Chart Description
Document
String String
RW RO
Font.
Name
Name of the font for the text in this note. Name of the font for the text in this note. This property is read only (RO) and set by the StateFont.Name property of the Chart object containing this note. Style of the font for the text in this note. Can be 'ITALIC' or 'NORMAL'. This property overrides the default style for this note which is set by the StateFont.Angle property of the Chart object containing this note. Size of the font for the label text for this note. This property overrides the default size for this note which is set by the StateFont.Size property of the Chart object containing this note. Equivalent to selecting Font Size > ... in the context menu for this note. Weight of the font for the label text for this note. Can be
'BOLD' or 'NORMAL'. This property overrides the default
Font.
String
RW
Angle
Font.
Double
RW
Size
Font.
String
RW
Weight
this note.
Id
Integer
RO
Unique identifier assigned to this note to distinguish it from other objects in the model.
B-30
Note Properties
Property Interpretation
Type
Acc
Description
RW RO RW
How the text in this note is interpreted for text processing. Can be 'NORMAL' or 'TEX'. Machine that contains this note. Position and size of this notes box in the Stateflow chart given in the form of a 1-by-4 array consisting of the following: (x,y) coordinate for the boxs left upper vertex relative to the upper left vertex of the Stateflow diagram editor workspace. Width and height of the box.
Machine Position
Subviewer
RO RW
State or chart in which this note can be graphically viewed. Label for this note. The text content for this note that you enter directly into the note in the diagram editor or in the Label field of the Properties dialog for this note.
Text
B-31
Note Methods
BNote Methods
Stateflow API objects of type Note have the methods listed in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Note objects. Also see Note Properties on page B-30.
Method dialog help view Description
Display the Properties dialog of this note. Display a list of properties for this Note object with short descriptions. Display this notes chart in a diagram editor with this note highlighted.
B-32
Transition Properties
BTransition Properties
Stateflow API objects of type Transition have the properties listed in the table below. See also Transition Methods on page B-36.
Property ArrowSize Chart Debug. Breakpoints. WhenTested Type Acc Description
RW RO RW
Size of the arrow for this transition. Stateflow chart object containing this transition If set to true, set a debugging breakpoint to occur when this transition is tested to see whether it is a valid transition or not. Equivalent to selecting When Tested check box in the Properties dialog of this transition. If set to true, set a debugging breakpoint to occur when this transition has tested valid. Equivalent to selecting the When Valid check box in the Properties dialog of this transition. Description of this transition. Equivalent to entering a description in the Description field of the Properties dialog for this transition. Document link to this transition. Equivalent to entering the Document Link field of the Properties dialog for this transition. Set the drawing style for this transition. Set to 'STATIC' for static transitions or 'SMART' for smart transitions. Equivalent to selecting the Smart switch toggle from the context menu for this transition. Destination state or junction of this transition. Assign Destination the destination object for this transition. You can also use the property Destination to detach the destination end of a transition through the command t.Destination = [] where t is the Transition object.
Boolean
RW
Description
String
RW
Document
String
RW
DrawStyle
Enum
RW
Destination
State or Junction
RW
B-33
Transition Properties
Property DestinationOClock
Type
Acc
Description
Double
RW
Location of transition destination connection on state. Varies from 0 to 12 for full clock cycle location. Its value is taken as modulus 12 of its assigned value. Size of the font for the label text for this box. This property overrides the default size for this box which is set by the TransitionFont.Size property of the Chart object containing this box. Equivalent to selecting Font Size > ... in the context menu for this box. Unique identifier of this transition among other objects in the Stateflow machine. Position and size of this transitions label in the Stateflow chart, given in the form of a 1-by-4 array consisting of the following: (x,y) coordinate for the labels left upper vertex relative to the upper left vertex of the Stateflow diagram editor workspace. Width and height of the label.
FontSize
Double
RW
Id
Integer Rect
RO RW
LabelPosition
LabelString
String
RW
Label for this transition. Equivalent to typing the label for this transition in its label text field in the diagram editor. Machine containing this transition. Position of the midpoint of this transition relative to the upper left corner of the Stateflow diagram editor workspace in a (x,y) point array. Source state or junction of this transition. Assign Source the source object for this transition. You can also use the property Source to detach the source end of a transition through the command t.Source = [] where t is the Transition object.
Machine MidPoint
Machine Rect
RO RW
Source
State of Junction
RW
B-34
Transition Properties
Property SourceEndPoint
Type
Acc
Description
Rect
RO*
x,y spatial coordinates for the end point of a transition. *This property is RW (read/write) only for default transitions. For all other transitions it is RO (read only). Location of transition source connection on state. Varies from 0 to 12 for full clock cycle location. The value taken for this property is the modulus 12 of the entered value. State or chart in which this transition can be graphically viewed. A field you can use to hold data of any type for this transition.
SourceOClock
Double
RW
Subviewer
RO RW
Tag
B-35
Transition Methods
BTransition Methods
Stateflow API objects of type Transition have the methods listed in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Transition objects. Also see Transition Properties on page B-33.
Method dialog help Description
Display the Properties dialog of this transition. Display a list of properties for this Transition object with short descriptions. Display this transitions chart in a diagram editor with this transition highlighted.
view
B-36
Junction Properties
BJunction Properties
Stateflow API objects of type Junction have the properties listed in the table below. See also Junction Methods on page B-38.
Property ArrowSize Chart Description Type Acc Description
RW RO RW
Size of transition arrows coming into this junction. Chart that this junction resides in. Description of this junction. Equivalent to entering a description in the Description field of the Properties dialog for this junction. Document link to this junction. Equivalent to entering the
Document Link field of the Properties dialog for this junction.
Document
String Integer Machine Rect Rect Chart or State Any Type Enum
RW RO RO RW RO RO RW RO
Unique Stateflow ID# assigned to this junction Machine containing this junction. Position of this junction relative to the upper left corner of the parent chart or state as an (x,y) point array Radius of this junction. State or chart in which this junction can be graphically viewed. A field you can use to hold data of any type for this junction. Type of this junction. For junctions can be one of the following: 'CONNECTIVE' 'HISTORY'
Tag
Type
B-37
Junction Methods
BJunction Methods
Stateflow API objects of type Junction have the methods listed in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Junction objects. Also see Junction Properties on page B-37.
Method dialog help Description
Display the Properties dialog for this junction Display a list of properties for this Junction object with short descriptions. Return all inner and outer transitions whose source is this junction. Display this junctions chart in a diagram editor with this junction highlighted.
sourcedTransitions view
B-38
Data Properties
BData Properties
Stateflow API objects of type Data have the properties listed in the table below. See also Data Methods on page B-43.
Property DataType Type Acc Description
Enum
RW
Data type of this data. Can have one of the following possible values: 'boolean', 'uint8', 'int8', 'uint16', 'int16', 'uint32', 'int32', 'single', 'double'. Equivalent to an entry in the Type column for this data in Explorer or the Type field in the Properties dialog for this data. If set to true, causes the debugger to halt execution if this data is modified. Setting this property to true is equivalent to selecting the Watch column entry for this data in the Explorer or selecting the Watch in debug check box in the Properties dialog for this data. Description of this data. Equivalent to entering description in Description field of the Properties dialog for this data. Document link to this data. Equivalent to entering the
Document Link field of the Properties dialog for this
Debug. Watch
Boolean
RW
Description
String
RW
Document
String
RW
data.
Id
Integer Boolean
RO RW
Unique Stateflow internal identification number for this data object. If set to true, this data is initialized from the MATLAB workspace. Setting this property to true is equivalent to selecting the FrWS column entry for this data in the Explorer or setting the Initialize from field to workspace in the Properties dialog for this data. Machine that contains this data.
InitFromWorkspace
Machine
Machine
RO
B-39
Data Properties
Property Name
Type
Acc
Description
String
RW
Name of this data. Equivalent to entering the name of this data in the Name field of its Properties dialog. Also can be named (renamed) in the Explorer by double-clicking on the entry in the Name column for this data and editing. State that this data belongs to. Numeric equivalent of Data property Props.Array.Size, a String. Numeric equivalent of Data property
Props.Range.FirstIndex, a String.
State Integer
RO RO
Integer
RO
Double Double
RO RO
InitialValue
ParsedInfo. Range. Maximum ParsedInfo. Range. Minimum Props. Range. Maximum
Numeric equivalent of Data property Props.InitialValue, a String. Numeric equivalent of Data property Props.Range.Maximum, a String. Numeric equivalent of Data property Props.Range.Minimum, a String. Maximum value that this data can have during execution or simulation of the state machine. Equivalent to entering value in the Max column for this data in Explorer or the Max field in the Properties dialog for this data. Minimum value that this data can have during execution or simulation of the state machine. Equivalent to entering a value in the Min column for this data in Explorer or the Min field in the Properties dialog for this data.
Double
RO
String
RW
String
RW
B-40
Data Properties
Type
Acc
Description
String
RW
If the source of the initial value for this data is the Stateflow data dictionary, this is the value used. Equivalent to entering this a value in the InitVal column for this data in the Explorer or similar field in the Properties dialog for this data. Specifying a positive value for this property specifies that this data is an array of specified size. Equivalent to entering a positive value in the Size column for this data in the Explorer or in the Sizes field of the Properties dialog for this data. Index of the first element of this data if it is an array (Props.Array.Size > 1). Equivalent to entering a value of zero or greater in the First Index field of the Properties dialog for this data. If set to true, this data is saved to the MATLAB workspace. Setting this property to true is equivalent to selecting the ToWS column entry for this data in the Explorer or selecting the Save final value to base workspace field in the Properties dialog for this data.
String
RW
String
RW
SaveToWorkspace
Boolean
RW
B-41
Data Properties
Property Scope
Type
Acc
Description
Enum
RW
Scope of this data. Allowed values vary with the object containing this data. The following apply to any data object: 'LOCAL_DATA' (Local) 'CONSTANT_DATA' (Constant) 'OUTPUT_DATA' (Output to Simulink) The following apply to data for machines only: 'IMPORTED_DATA' (Exported) 'EXPORTED_DATA' (Imported) The following apply to data for charts only: 'INPUT_DATA' (Input to Simulink) The following apply to data for charts and functions only: 'TEMPORARY_DATA' (Temporary) The following apply to data for functions only: 'FUNCTION_INPUT_DATA' (Input Data) 'FUNCTION_OUTPUT_DATA' (Output Data) Above values are equivalent to entering the value shown in parentheses in the Scope field of the Properties dialog or the Explorer for this data.
Tag
RW RW
A field you can use to hold data of any type for this Data object. Physical units corresponding to the value of this data object.
Units
B-42
Data Methods
BData Methods
Stateflow API objects of type Data have the methods shown in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Data objects. Also see Data Properties on page B-39.
Method dialog help view Description
Display the Properties dialog of this data object. Display a list of properties for this Data object with short descriptions. Display this data in the Data Properties dialog.
B-43
Event Properties
BEvent Properties
Stateflow API objects of type Event have the properties listed in the table below. See also Event Methods on page B-46.
Property Debug. Breakpoints. StartBroadcast Debug. Breakpoints. EndBroadcast Description Type Acc Description
Boolean
RW
If set to true, set a debugger breakpoint for the start of the broadcast of this event. Equivalent to selecting the Start of broadcast check box in the Properties dialog for this event. If set to true, set a debugger breakpoint for the end of the broadcast of this event. Equivalent to selecting the End of broadcast check box in the Properties dialog for this event. Description of this event. Equivalent to entering a desription in the Description field of the Properties dialog for this event. Document link to this event. Equivalent to entering the
Document Link field of the Properties dialog for this event.
Boolean
RW
String
RW
Document
RW RO RO RW
Id Machine Name
Unique Stateflow ID# assigned to this event Machine this event belongs to. Name of this event. Equivalent to entering the name in the
Name field of the Properties dialog for this event.
B-44
Event Properties
Property Scope
Type
Acc
Description
Enum
RW
Scope of this data. Allowed values vary with the object containing this data. The following apply to any event: 'LOCAL_EVENT' (Local) The following apply to events for charts only: 'INPUT_EVENT' (Input from Simulink) 'OUTPUT_EVENT' (Output to Simulink) The following apply to events for machines only: 'IMPORTED_EVENT' (Imported) 'EXPORTED_EVENT' (Exported) Above values are equivalent to entering the value shown in parentheses in the Scope field of the Properties dialog or the Explorer for this data.
Tag
RW RW
A field you can use to hold data of any type for this event. Type of signal that triggers this Input to Simulink or Output to Simulink event associated with its chart. Can be one of the following: 'EITHER_EDGE_EVENT' (Either Edge) 'RISING_EDGE_EVENT' (Rising Edge) 'FALLING_EDGE_EVENT' (Falling Edge) 'FUNCTION_CALL_EVENT' (Function Call) Equivalent to specifying the indicated parenthetical expression for the Trigger field of the Properties dialog for this event.
Trigger
B-45
Event Methods
BEvent Methods
Stateflow API objects of type Event have the methods listed in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Event objects. Also see Event Properties on page B-44.
Method dialog help Description
Display the Properties dialog for this event. Display a list of properties for this Event object with short descriptions. Display this event in its Properties dialog.
view
B-46
Target Properties
BTarget Properties
Stateflow API objects of type Target have the properties listed in the table below. See also Target Methods on page B-50.
Property ApplyToAllLibs Type Acc Description
Boolean
RW
If set to true, use settings in this target for all libraries. Equivalent to selecting the Use settings for all libraries check box in this targets Target Builder dialog. A MATLAB vector of structures containing information on n code flag settings for this target. Each of the n flags corresponds to a selection in the Coder Options dialog for this target. Each element in the vector is a MATLAB structure with information about a particular code flag. If you want to see information about the first flag for a Target object t, for example, use the following two commands:
cfi = t.CodeFlagsInfo disp(cfi(1))
CodeFlagsInfo
Array
RO
If you want to quickly see the names of all the flags, do the following:
cfi.name
Name member of the CodeFlagsInfo structure is shorthand for a longer expression in the Coder Options dialog. For example, the name 'comments' actually refers to the dialog setting Comments in generated code. You use the name of a code flag to get and set the code flag value with the methods getCodeFlag and setCodeFlag. Changing the vector returned by CodeFlagsInfo does not change an actual flag.
B-47
Target Properties
Property CodegenDirectory
Type
Acc
Description
String String
RW RW
Directory to receive generated code. Applies only to targets other than sfun and rtw targets. Custom code included at the top of the generated code. Equivalent to the setting of the Custom code included at the top of generated code selection of the Target Options dialog for this target. Custom initialization code. Equivalent to the setting of the Custom initialization code (called from mdlInitialize) selection of the Target Options dialog for this target. Applies only to sfun and rtw targets. Custom termination code. Equivalent to the setting of the Custom termination code (called from mdlTerminate) selection of the Target Options dialog for this target. Applies only to sfun and rtw targets. Description of this target. Equivalent to entering description in Description field of the Properties dialog for this target. Document link to this target. Equivalent to entering the Document Link field of the Properties dialog for this target. Unique identifier assigned to this Data object to distinguish it from other objects loaded in memory. Stateflow machine containing this target. Name of this target. Equivalent to naming or renaming this target in the Explorer. A field you can use to hold data of any type for this target. Custom include directory paths. Equivalent to the setting of the Custom include directory paths selection of the Target Options dialog for this target.
CustomCode
CustomInitializer
String
RW
CustomTerminator
String
RW
Description
String
RW
Document
String
RW
Id
RO RO RW RW RW
Machine Name
Tag
UserIncludeDirs
B-48
Target Properties
Property UserLibraries
Type
Acc
Description
String
RW
String
RW
B-49
Target Methods
BTarget Methods
Stateflow API objects of type Target have the methods listed in the table below. See the API Methods Reference for details on each method. See also the section Methods that Apply to All Objects on page B-5 for a list of methods that apply to all objects including Target objects. Also see Target Properties on page B-47.
Method build Description
Build this target only those portions of the targets charts that have changed since the last build (i.e., incrementally). Display the Properties dialog for this target. Generate code for this target only for those portions of this targets charts that have changed since the last code generation (i.e., incrementally). Return the value of the specified code flag for this target. Display a list of properties for this Target object with short descriptions. Compile this target for only those portions of this targets charts that have changed since the last compile (i.e., incrementally). For a simulation target (sfun), a dynamic link library (sfun.dll) is compiled from the generated code. Completely rebuild this target. Completely regenerate code for this target. Set the specified code flag for this target with the specified value. Display this target in the Target Properties dialog.
dialog generate
getCodeFlag help
make
B-50
C
API Methods Reference
API Methods
The following Stateflow API method references appear in alphabetical order.
Method build classhandle copy defaultTransitions Purpose
Build this target incrementally. Provide a handle to the schema class of this objects type. Copy the specified array of objects to the clipboard. Return the default transitions in this object at the top level of containment. Delete this object.
Return specified objects in this object at all levels of containment in this object. Includes this object, if specified. Return specified objects in this object at all levels of containment below this object. Return specified objects in this object at the first level of containment below this object. Generate code incrementally for this target. Return a MATLAB structure containing the property settings of this object. Return the code flag of specified name. Display list of properties for this object along with short descriptions. Return the inner transitions that originate with this chart or state and terminate on a contained object. Make (compile, link, load) this target incrementally with no code generation. List the names of the methods belonging to this object.
findDeep
findShallow
generate get
make
methods
C-2
API Methods
Purpose
Return an array of outer transitions for this state. Output the activity status of this state to Simulink via a data output port on the chart block of this state. Parse this chart. Paste the objects in the clipboard to the specified container object. Completely rebuild this target. Completely regenerate code for this target. Set the value of specified properties with the specified values. Set the code flag of specified name to the value you specify. Close all Simulink models containing Stateflow diagrams and exit the Stateflow environment. Display Stateflow online help. Create a Simulink model containing an empty Stateflow block. Print the visible portion of a Stateflow diagram. Save the current state machine (Simulink model). Return transitions sourced by this object. Open the Stateflow model window. Return a MATLAB structure containing the property settings of this object. Make this object visible for editing. Zoom in or out on this chart.
C-3
C-4
build
Cbuild
Target Build this target incrementally. The build method incrementally builds this target. It performs the following activities: Parse all charts completely. Generate code for charts incrementally. For a simulation target (sfun), a dynamic link library (sfun.dll) is compiled from the generated code. If a complete build has already taken place, the build method performs an incremental build that builds only those portions of the target corresponding to charts that have changed since the last build. See also the methods rebuildAll, generate, regenerateAll, and make.
thisTarget.build
None None If t is a Target object, the command t.build builds the target for the Stateflow charts that have changed in the targets model since the last build and/or code generation.
C-5
classhandle
Cclasshandle
All objects Provide a handle to the schema class of this objects type. The classhandle method returns a read-only handle to the schema class of this objects type. You can use the classhandle method to provide information about the structure of each object type.
handle = thisObject.classhandle
None
Name handle Type Description
Object
Example
If j is a Junction object, the class handle of a Junction object is j.classhandle. You can see the class schema for a Junction object by using the following get command:
j.classhandle.get
Two member arrays of the displayed class schema are Properties and Methods. These two members are members of the schema class for every object. List the class schema for Properties with the following command:
j.classhandle.Properties.get
Two displayed members of the Properties schema are Name and DataType. Finally, using the class handle for a junction, you can display the properties of a Junction object along with their data types with the following command:
get(j.classhandle.Properties,{'Name','DataType'})
C-6
copy
Ccopy
Clipboard Copy the specified array of objects to the clipboard. The copy method copies the specified objects to the clipboard. Objects to copy are specified through a single argument array of objects. Later, complete the copy operation by invoking the pasteTo method.
Syntax Arguments
objArray Object
Array of Stateflow objects to copy. These objects must conform to the following: The objects copied must be all graphical (states, boxes, functions, transitions, junctions) or all non-graphical (data, events, targets). If all objects are graphical, they must all be seen in the same subviewer.
Returns Example
C-7
defaultTransitions
CdefaultTransitions
Chart, State, Box, Function Return the default transitions in this object at the top level of containment. The defaultTransitions method returns the default transitions in this object at the top level of containment.
defaultTransitions = thisObject.defaultTransitions
None
Name defaultTransitions Type Description
Transition
Example
If state A contains state A1, and state A1 contains state A11, and states A1 and A11 have default transitions attached to them, the defaultTransitions method of state A returns the default transition attached to state A1.
C-8
delete
Cdelete
Machine, State, Box, Function, Note, Transition, Junction, Data, Event, Target Delete this object. The delete method deletes this object from the model. This is true for all but the Root, Chart, Clipboard, and Editor objects.
thisObject.delete
None None If a state A is represented by the State object sA, the command sA.delete deletes state A.
C-9
dialog
Cdialog
Machine, Chart, State, Box, Function, Note, Transition, Junction, Event, Data, Target Open the Properties dialog of this object. The dialog method opens the Properties dialog of its object.
thisObject.dialog
None None If state A is represented by State object sA, the MATLAB statement sA.dialog opens the Properties dialog for state A.
C-10
find
Cfind
Root, Machine, Chart, State, Box, Function Return specified objects in this object at all levels of containment in this object. Includes this object, if specified. Using combinations of specifier-value argument pairs, the find method returns objects in this object that match the specified criteria. The specifier-value pairs can be property based or based on other attributes of the objects such as its depth of containment. Specifiers can also be logical operators (-and, -or, etc.) that combine other specifier-value pairs. By default, the find command finds objects at all depths of containment within an object. You can specify the maximum depth of search with the -depth specifier. However, the zeroth level of containment, i.e., the searched object itself, is always included if it happens to satisfy the search criteria. If no arguments are specified, the find command returns all objects of this object at all levels of containment. See also the findDeep and findShallow methods.
Syntax
Arguments
Value
Description
Relates prior specifier-value pair to the following specifier-value pair in an AND relation. class name Search for object of specified class name. Use this option to find all objects whose class exactly matches a given class. To allow matches for subclasses of a given class, use the -isa specifier described below. Classes are specified as the string name (e.g., 'Stateflow.State', 'Stateflow.Transition', etc.) or as a handle to the class (see the method classhandle).
C-11
find
Value
Description
search depth Search to depth = 0,1,2,...,infinite. The default search depth is infinite. Specify that the value in the following specifier-value pair is a Function object and should be evaluated for each object visited in the search. The function must always return a logical scalar value that indicates whether or not the value is a match. If no property is specified, the function is passed the handle of the current object in the search. If a property is specified, the function is passed the value of that property. In the following example, a function f is used to filter a find to return only those objects of type 'andState':
f=@(h) (strcmp(get(h,'type'), 'andState')); objArray = thisObject.find('-function', f);
-isa
object type
Search for an object of the specified object type and its subtypes. Object types are specified as the string name (e.g., 'Stateflow.State', 'Stateflow.Transition', etc.) or as a handle to the object type (see method classhandle). Search for objects with specified method. Search for the negative of the following specifier-value pair. Relates the prior specifier-value pair to the following specifier-value pair in an OR relation. Note If no logical operator is specified, -or is assumed.
method name
C-12
find
Value
Description
Search for objects that have the specified property with the specified value. Search for objects that have the specified property. Relate the prior specifier-value pair to the following specifier-value pair in an XOR relation. Value of the following specifier-value pair contains a regular expression.
Returns
Name objArray
Type Object
Description
Example
If a Chart object c represents a Stateflow chart, the command states=c.find('-isa','Stateflow.State') returns an array, states, of all the states in the chart, and the command states=c.find('Name','A') returns an array of all states whose Name property is 'A'. If state A, which is represented by State object sA, contains two states, A1 and A2 and you specify a find command that finds all the states in A as follows:
states= sA.find( '-isa','Stateflow.State')
then the above command finds three states: A, A1, and A2.
C-13
findDeep
CfindDeep
Root, Machine, Chart, State, Box, Function Return specified objects in this object at all levels of containment below this object. The findDeep method of this object returns all objects of specified type at any and all depths of containment within this object. You specify the object type as a String argument. Only one type is allowed. See also the findShallow method which returns objects only at the first level of containment (i.e., first depth only). See also the find method.
Syntax Arguments
String
Workspace variable or literal string of contained object type. Can be 'Machine', 'Chart', 'State', 'Box', 'Function', 'Note', 'Transition', 'Junction', 'Event', 'Data', or 'Target'.
Description
Returns
Name objArray
Type
Object
Array of objects of specified type found in this object at any (all) depths.
Example
Chart object ch contains state A and state B connected by a transition. State A contains state A11 and A12 also connected by a transition. State A11 contains state A111 and a junction. The command ch.findDeep('State') returns an array of state objects for state A, A11, A12, A111, and B.
C-14
findShallow
CfindShallow
Root, Machine, Chart, State, Box, Function Return specified objects in this object at the first level of containment below this object. The findShallow method of this object returns all objects of the specified type at the first level of containment within this object. You specify the type of object as a String argument. Only one type is allowed. See also the findDeep method which returns objects only at all levels of containment (i.e., infinite depth). See also the find method.
Syntax Arguments
String
Workspace variable or literal string of contained object type. Can be 'Machine', 'Chart', 'State', 'Box', 'Function', 'Note', 'Transition', 'Junction', 'Event', 'Data', or 'Target'. If no type is specified (i.e., no argument), all possible object types are found.
Returns
Name objArray
Type
Description
Object
Array of objects of specified type found in this object at the top level of containment (i.e., first depth).
Example
Chart object ch contains state A and state B connected by a transition. State A contains state A11 and A12 also connected by a transition. State A11 contains state A111 and a junction. The command ch.findShallow ('State') returns an array of state objects for the states A and B.
C-15
generate
Cgenerate
Target Generate code incrementally for this target. The generate method generates code incrementally for this target. If a complete code generation has already taken place, it performs an incremental generation for only those portions of the target corresponding to charts that have changed since the last code generation. See also the methods build, rebuildAll, regenerateAll, and make.
thisTarget.generate
None None If t is a Target object, the command t.generate generates code for the Stateflow charts that have changed in the targets model since the last code generation.
C-16
get
Cget
Root, Machine, Chart, State, Box, Function, Note, Transition, Junction, Data, Event, Target Return a MATLAB structure containing the property settings of this object. The get method returns and displays a MATLAB structure containing the property settings of this object.
propList = thisObject.get
None
Name propList Type Description
MATLAB Structure
Example
State A is represented by the State object sA. The following command lists the properties of state A:
sA.get
The following command returns a handle to a MATLAB structure of the properties of state A to the workspace variable Aprops:
Aprops = sA.get
C-17
getCodeFlag
CgetCodeFlag
Target Return the code flag of specified name. The getCodeFlag method returns the value of a particular code flag whose name you specify. See also the setCodeFlag method for setting the value of code flags.
Syntax Arguments
String
Returns Example
None Assume that the Target object t represents the simulation target (sfun) for the loaded model. If m is the Stateflow machine object for this model, you can obtain t with the following command:
t = m.find('-isa','Stateflow.Target','-and', 'Name','sfun')
The simulation target has two code flags. Their names are 'debug' and 'echo'. You can verify this by looking at their names of the CodeFlagsInfo property of t. See the description for the CodeFlagsInfo property in the Target Properties section of this chapter for further details. The name 'debug' refers to the code flag identified in the Coder Options dialog as Enable debugging/animation. The 'debug' code flag is turned on (=1) by default for the simulation target. You can verify this with the following command:
t.getCodeFlag('debug')
You can also find the setting of the code flag 'echo' which refers to the code flag identified in the Coder Options dialog as Echo expressions without semicolons with the following command:
t.getCodeFlag('echo')
C-18
help
Chelp
All objects Return a list of properties for this object along with accompanying descriptions. The help method returns a list of properties for any object. To the right of this list appear simple descriptions for each property. Some properties do not have descriptions. These are considered obvious by reason of their name which is descriptive in itself.
thisObject.help
None None NA
C-19
innerTransitions
CinnerTransitions
State, Box, Function Return the inner transitions that originate with this chart or state and terminate on a contained object. The innerTransitions method returns the inner transitions that originate with this object and terminate on a contained object.
transitions = thisObject.innerTransitions
None
Name transitions Type Description
Transition
An array of inner transitions originating with this object and terminating on a contained state or junction.
Example
State A contains state A1, and state A1 contains state A11. State A has two transitions each originating from its inside edge and terminating inside of it. These are inner transitions. One transition terminates with state A1 and the other terminates with state A11. The innerTransitions method of state A returns both of these transitions.
C-20
make
3make
Target Incrementally compiles this target with no code generation. For a simulation target (sfun), a dynamic link library (sfun.dll) is compiled from the generated code. The make method performs an incremental compile of this target with no code generation. It performs the compile for only those portions of generated code that have changed since the last compile. See also the methods build, rebuildAll, generate, and regenerateAll.
thisTarget.make
None None If t is a Target object, the command t.make incrementally compiles generated code for that target. If t is a simulation target (sfun), its compiled code is then linked and loaded into the target.dll.
3-21
methods
Cmethods
All objects List the names of the methods belonging to this object. The methods method lists the names of the methods belonging to this object.
thisObject.methods
None None If state A is represented by State object sA, the following command lists the methods of state A:
sA.methods
C-22
outerTransitions
CouterTransitions
State, Box, Function Return an array of outer transitions for this object. The outerTransitions method returns an array of transitions that exit the outer edge of this object and terminate on objects outside the containment of this object.
transitions = thisObject.outerTransitions
None
Name transitions Type Description
Transition
Example
A chart contains three states, A, B, and C. State A is connected to state B through a transition from state A to state B. State B is connected to state C through a transition from state B to state C. And state C is connected to state A through a transition from state C to state A. If state A is represented by State object sA, the command sA.outerTransitions returns the transition from state A to state B.
C-23
outputData
CoutputData
State Creates, retrieves, or deletes a data output to Simulink of this states activity status. The outputData method of this state creates, retrieves, or deletes a special data object of type State. This data is attached internally to an output port on this states Stateflow block in Simulink to output the activity status of this state to Simulink during runtime.
Note You cannot use the Stateflow Explorer to create data objects of type State.
Syntax Arguments
String
Values can be as follows: 'create' returns a new data object of type State and attaches it internally to a new state activity output port on this states Stateflow block. 'get' returns this states existing data object of type State attached internally to an existing state activity output port on this states Stateflow block. 'delete' deletes this states data object of type State and the state activity output port on its Stateflow block to which it is attached.
Returns
Name StateData
Type
Description
Data
C-24
outputData
Example
If state A is represented by State object sA, the following command creates a new data object of type State which is output to Simulink and contains state As activity:
s.outputData('create')
The Stateflow chart block in Simulink that contains state A now has an output port labeled A, the name of state A. In Explorer, state A now contains a data object of type State whose scope is Output to Simulink. The following command returns a Data object, d, for the data output to Simulink containing state As activity:
s.outputData('get')
The following command deletes the data output to Simulink containing state As activity:
s.outputData('delete')
C-25
parse
Cparse
Machine, Chart For Chart objects, parse this chart; for Machine objects, parse the charts in this machine. For Chart objects, the parse method parses this chart. This is equivalent to selecting Parse from the Tools menu of the Stateflow diagram editor for this chart. For Machine objects, the parse method parses all the charts in this machine.
thisChart.parse thisMachine.parse
None None NA
C-26
pasteTo
CpasteTo
Clipboard Paste the objects in the Clipboard to the specified container object. The paste method pastes the contents of the Clipboard to the specified container object. The receiving container is specified through a single argument. Use of this method assumes that objects have been placed in the Clipboard with the copy method.
clipboardObj.pasteTo(newContainer) Name newContainer Type Description
Syntax Arguments
Can vary
Stateflow object to receive copy of contents of the clipboard object. If the objects in the clipboard are all graphical (states, boxes, functions, notes, transition, junctions), this object must be a chart or subchart.
Description
Returns
Name copiedObjs
Type
Can vary
Example
C-27
rebuildAll
CrebuildAll
Target Completely rebuild this target. The rebuildAll method completely rebuilds this target. It performs the following activities: Parse all charts completely. Regenerate code for all charts completely. For a simulation target (sfun), a dynamic link library (sfun.dll) is compiled from the generated code. See also the methods build, generate, regenerateAll, and make.
thisTarget.rebuildAll
None None If t is a Target object, the command t.rebuildAll completely rebuilds that target.
C-28
regenerateAll
CregenerateAll
Target Completely regenerate code for this target. The regenerateAll method regenerates this target. Regardless of previous code generations, it regenerates code for all charts in this targets model. See also the methods build, rebuildAll, generate, and make.
thisTarget.regenerateAll
None None If t is a Target object, the command t.regenerateAll completely regenerates code for the Stateflow charts in that targets model.
C-29
set
Cset
Set Set the value of specified properties with the specified values. The set method sets the value of a specified property or sets the values of a set of specified properties for this object. You specify properties and values through pairs of property name/value arguments.
object.set(propName, value [,propName, value,...])
Syntax
Arguments
Type
Description
Name of the property to set New value for the specified property
Returns Example
None The following command sets the Name and Description properties of the State object s:
s.set('Name', 'Kentucky', 'Description', 'Bluegrass State')
The following command sets the Position property of the State object s:
s.set('Position',[200,119,90,60])
C-30
setCodeFlag
CsetCodeFlag
Target Set the code flag of specified name to the value you specify. The setCodeFlag method sets the value of a code flag whose name you specify. See also the getCodeFlag method for getting the value of code flags.
Syntax Arguments
String Varies
Flag values can vary in type. Use the property CodeFlagsInfo to obtain the type for a particular flag.
Returns Example
None Assume that the Target object t represents the simulation target (sfun) for the loaded model. If m is the Stateflow machine object for this model, you can obtain t with the following command:
t = m.find('-isa','Stateflow.Target','-and', 'Name','sfun')
The simulation target has two code flags. Their names are 'debug' and 'echo' which you can verify by looking at the name of the CodeFlagsInfo property with the following command:
t.CodeFlagsInfo.name
The name 'debug' refers to the code flag identified in the Coder Options dialog as Enable debugging/animation. The debug code flag is turned on (=1) by default for the simulation target. You can verify this with the getCodeFlag method in the following command:
t.getCodeFlag('debug')
C-31
setCodeFlag
t.setCodeFlag('debug',0)
C-32
sfclipboard
Csfclipboard
None Return a handle to the Clipboard object. The global method sfclipboard method returns a handle to the Clipboard object. There is only one Clipboard object. Use it to copy objects from one owner to another. See the section Copying Objects on page 11-24.
cb = sfclipboard
None
Name cb Type Description
Clipboard
Example
NA
C-33
sfexit
Csfexit
None Close all Simulink models containing Stateflow diagrams and exit the Stateflow environment. The global sfexit method closes all Simulink models containing Stateflow diagrams and exits the Stateflow environment.
Caution Using the sfexit method causes all of models in Simulink to close without a request to save.
sfexit
None None NA
C-34
sfhelp
Csfhelp
None Display Stateflow online help. The global sfhelp method displays Stateflow online help.
sfhelp
None None NA
C-35
sfnew
Csfnew
None Create a Simulink model containing an empty Stateflow block. The sfnew method creates and displays an untitled Simulink model containing an empty Stateflow block. If you pass the sfnew method a model name it creates a Simulink model with the title specified.
sfnew [ModelName]
None None Create an untitled Simulink model that contains an empty Stateflow block.
sfnew
C-36
sfprint
Csfprint
None Print the visible portion of a Stateflow diagram. The sfprint method displays the visible portion of the specified Stateflow diagram. A read-only preview window appears while the print operation is in progress. An informational box appears indicating that the printing operation is starting. See Printing the Current View on page 3-71, for information on printing Stateflow diagrams that are larger than the editor display area.
Syntax Arguments
String
Name of the Stateflow diagram to print. Specifies the destination for the visible portion of the specified Stateflow diagram, as follows: 'ps' prints to a PostScript file. This is the default if the destination argument is omitted. 'psc' prints to a color PostScript file. 'eps' prints to an encapsulated PostScript file. 'epsc' prints to a color Encapsulated PostScript file. 'tif' prints to a .tif file. 'jpg' prints to a .jpg file. 'png' prints to a .png file. 'meta' prints to the clipboard as a meta file (PC version only). 'bitmap' prints to the clipboard as a bitmap file (PC version only).
destination String
Returns
None
C-37
sfprint
Example
Assume that you have a Simulink model named myModel loaded into MATLAB. The command sfprint ('myModel') prints the visible portion of the specified Stateflow diagram to a PostScript file. The command sfprint ('myModel','ps') prints the visible portion of the specified Stateflow diagram to a PostScript file. The command sfprint ('myModel','psc') prints the visible portion of the specified Stateflow diagram to a color PostScript file. The command sfprint ('myModel','tif') prints the visible portion of the specified Stateflow diagram to a .tif file. The command sfprint ('myModel','bitmap') prints the visible portion of the specified Stateflow diagram to a clipboard bitmap (PC version only).
C-38
sfroot
Csfroot
None Return a handle to the Clipboard object. The global method sfroot returns a handle to the Root object. There is only one Root object. It is the top object in the Stateflow model hierarchy of objects. Use it to begin accessing your Stateflow charts. See the section Access the Root Object on page 11-5
rt = sfroot
Arguments Returns
None
Name cb Type Description
Root
Example
NA
C-39
sfsave
Csfsave
None Save the current state machine (Simulink model). The global function sfsave saves the current model or a specified model either with the current model name or with an assigned save as model name.
sfsave ([modelname]) sfsave ('defaults') sfsave (machine.Id, 'saveasname') Name modelname 'defaults' Type Description
Arguments
Optional name of the current model to save. If no model is specified, saves the currently loaded model. If the string literal 'defaults' is specified, saves the current environment default settings in the defaults file The property Id of the machine object representing the machine (model) you want to save. If this is specified, this is an optional model name to save it to. If this is not specified, the specified model name is saved under its own name.
machine.Id saveasname
Returns Example
None Assume that you have a new Stateflow model. Its current default name is 'untitled'. The command sfsave saves the current model under the name untitled in the work directory. The command sfsave('untitled') saves the currently loaded model named untitled under the name untitled in the work directory. The command sfsave (m.Id,'myModel') saves the model represented by the machine m as the model myModel. The command sfsave ('defaults') saves the current environment default settings in the defaults file.
C-40
sourcedTransitions
CsourcedTransitions
State, Box, Function, Junction Return transitions whose source is this object. The sourcedTransitions method returns all inner and outer transitions that have their source in this object.
transitions = thisObject.sourcedTransitions
None
Name transitions Type Description
Transition
Example
Suppose that a chart contains three states, A, B, and state A1 which is contained by state A. The chart also has three transitions: one from A to B labeled AtoB, one from B to A labeled BtoA, and one from the inner edge of A to its state A1 (inner transition) labeled AtoA1. If State object sA represents state A, the command sA.sourcedTransitions returns two transitions: the outer transition labeled AtoB and the inner transition labeled AtoA1.
C-41
stateflow
Cstateflow
The global stateflow method 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 to include a Stateflow diagram in a Simulink model. Every Stateflow block has a corresponding S-function target called sfun. This target is the agent Simulink interacts with for simulation and analysis.
None None This example shows how to open the Stateflow model window and use a Stateflow block to create a Simulink model:
1 Invoke Stateflow.
stateflow
The Stateflow model window and an untitled Simulink model containing a Stateflow block are displayed.
C-42
stateflow
C-43
struct
Cstruct
All objects Return a MATLAB structure containing the property settings of this object. The struct method returns and displays a MATLAB structure containing the property settings of this object.
Note You can change the values of the properties in this structure just as you would a property of the object. However, the MATLAB structure is not a Stateflow object and changing it does not affect the Stateflow model.
propList = thisObject.struct
None
Name propList Type Description
MATLAB Structure
Example
If State object sA represents a state A, the command x = sA.struct returns a MATLAB structure x. You can use dot notation on x to report properties or set the value of other variables. For example, the command y=x.Name sets the MATLAB variable y to the Name property of the state A which is A. The command x.Name = 'Kansas' sets the Name property of x to 'Kansas' but does not change state As Name property.
C-44
view
Cview
Chart, State, Box, Function, Note, Transition, Junction, Event, Data, Trigger Make this object visible for editing. The view method opens the object in its appropriate editing environment as follows: For Chart objects, the view method opens the chart in a diagram editor on the chart if it is not already open. For State, Box, Function, Note, Junction, and Transition objects, the view method opens the chart containing the object in a diagram editor and highlights the object. If the diagram editor is already open, the object is highlighted only. For Event, Data, and Target objects, the view method opens the Explorer window.
thisObject.view
None None NA
C-45
Chart
Zoom in or out on this chart. The methods zoomIn and zoomOut cause the Stateflow diagram editor window for this chart to zoom in or zoom out, respectively, by 20 percentage points.
Note The zoomIn and zoomOut methods do not open or give focus to the Stateflow diagram editor for this chart.
thisChart.zoomIn thisChart.zoomOut
None None If the Chart object ch represents a Stateflow chart at the zoom level of 100%, the command ch.zoomIn raises the zoom level to 120%.
C-46
D
Regular Expressions
Regular Expression Syntax . . . . . . . . . . . . . D-3 Searching with Tokens . . . . . . . . . . . . . . . D-6
Regular Expressions
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. See the following sections for using regular expressions in the Stateflow Search and Replace tool: Regular Expression Syntax on page D-3 Searching with Tokens on page D-6
D-2
Note Any character appearing in a regular expression is ordinary, unless a '\' precedes it.
Metacharacters
Metacharacters dont match themselves but describe something else. Generally they represent groups of characters or keyboard keys without a representative character.
Expression \d Usage
A digit. Equivalent regular expression: [0-9] A nondigit. Equivalent regular expression: [^0-9] Form feed New line Carriage return A whitespace character. Equivalent regular expression: [ \t\n\r\f] A non-whitespace character. Equivalent regular expression: [^ \t\n\r\f] Tab
\D
\f \n \r \s
\S
\t
D-3
Regular Expressions
Expression \w
Usage
A word character. Equivalent regular expression: [a-zA-Z_0-9] A nonword character Equivalent regular expression: [^a-zA-Z_0-9] Matches any single character Matches any one of the characters contained within the brackets
\W
. [...]
Logical Operators
Logical operators do not match any specific characters. They are used to specify the context for matching an accompanying regular expression.
Expression \ Usage
If a character has special meaning in a regular expression, precede it with this character to match it literally. Groups regular expressions Matches either the expression preceding or following it Matches following expression only at the beginning of the string. Matches preceding expression only at the end of the string
(...) | ^
D-4
Quantifiers
Quantifiers are a type of logical operator. They are used to specify how many instances of the previous element that they can match.
Expression * Usage
Matches the preceding element 0 or more times. Equivalent regular expression: {0,} Matches the preceding element 1 or more times. Equivalent regular expression: {1,} Matches the preceding element 0 times or 1 time, also minimizes. Equivalent regular expression: {0,1} Must occur at least n times but no more than m times Must occur at least n times Must match exactly n times Equivalent regular expression: {n,n}
D-5
Regular Expressions
You choose to search the above text with the following search pattern.
and(y|rew)|(t)e(d)
In this pattern there are three parenthetical expressions that generate tokens. When you finally perform the search, the following tokens are generated for each match.
Match andy ted andrew andy ted Token 1 y t rew y t d d Token 2
Only the highest level parentheses are used. For example, if the search pattern and (y|rew) finds the text andrew, token 1 is assigned the value rew. However, if the search pattern (and(y|rew)) is used, token 1 is assigned the value andrew. The variables that allow you to use tokens in your search pattern have the form
\1, \2,..., \n (n<17) and are assigned left to right from parenthetical
D-6
As an example, suppose that you are searching an HTML file to find many table entries. Generally, HTML lines with table entries have the following form.
<TD><B>Crops<\B><\TD><TD>Wheat<\TD><TD>Corn<\TD><TD>Barley<\TD>
You can use search pattern tokens to search and find all table entries with the following search pattern.
<(\w*)>(.*?)<\\\1>
angle brackets. Because of the parentheses around \w*, the word characters matched are placed in token 1. In our example, <(\w*)> finds the string <TD> and places the string TD in token 1.
2 The expression (.*?) contains the expression .*?, which finds a minimum
number of any characters. Using the expression (.*) instead would find the maximum number of any characters and could use up the entire file before finding the angle bracket characters sought for by the next expression. The parentheses in the expression (.*?) places the matched characters in token 2. Although this is not necessary for the search, placing these characters in a token allows you to reference them in replacement text.
3 The expression <\\\1> uses the variable \1 for token 1 preceded by two
backslashes. Since backslashes are regular expression logical operators, two backslashes specify a single backslash as a search character. In the HTML example, since the first expression, <(\w*)>, finds the string <TD>, and places the string TD in token 1, the expression <\\\1> finds the following <\TD> string.
D-7
Regular Expressions
D-8
E
Obsolete Features
Error on Transition Action into Junction with Following Condition Action E-3
Obsolete Features
The sections that follow describe previous features that are now obsolete in the current version of Stateflow. Error on Transition Action into Junction with Following Condition Action on page E-3 These sections include modifications and workarounds that you can use to make your Stateflow models compatible with the current Stateflow version.
E-2
Assuming that there are no other actions than those indicated for the labeled transition segments between state A and state B, then the sequence of execution that takes place when state A is active is expressed by the following pseudo-code:
If (c1) { if(c2) { a2; exit A; a1; enter B; } }
Since condition actions are evaluated when their guarding condition is true and transition actions are evaluated when the transition is actually taken, condition action a2 is executed prior to transition action a1. This violates the apparent graphical sequence of executing a1 then a2. In this case, the above diagram is flagged for an error during build time. As a remedy, the user can change a1 and a2 to be both condition or transition actions.
E-3
Obsolete Features
E-4
F
Glossary
Glossary
Action
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. For example,
Condition action Transition action
States can have entry, during, exit, and, on event_name actions. For example,
If you enter the name and backslash followed directly by an action or actions (without the entry keyword), the action(s) are interpreted as entry action(s). This shorthand is useful if you are only specifying entry actions. The action language defines the categories of actions you can specify and their associated notations. An action can be a 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 7-37.
F-2
Chart Instance
A chart instance is a link from a Stateflow model to a chart stored in a Simulink library. A chart in a library can have many chart instances. Updating the chart in the library automatically updates all the instances of that chart.
Condition
A condition is a Boolean expression to specify that a transition occurs given that the specified expression is true. For example,
[speed>threshold] is a condition.
The action language defines the notation to define conditions associated with transitions. See the section titled Action Language on page 7-37 for more information.
Connective Junction
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. Connective junctions provide alternative ways to represent desired system behavior.
F-3
Glossary
This example shows how connective junctions (displayed as small circles) are used to represent the flow of an if code structure.
if [c1]{ a1 if [c2]{ a2 } else if [c3]{ a3 } }
Name
Button Icon
Description
Connective junction
One use of a Connective junction is 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.
See the section titled Connective Junctions on page 7-28 for more information.
Data
Data objects store numerical values for reference in the Stateflow diagram. See Defining Data on page 4-14 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
F-4
those objects is stored in the data dictionary once you save the Stateflow diagram.
Debugger
See Stateflow Debugger on page F-11.
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. 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 (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 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 then
F-5
Glossary
dropping it to attach to a destination object. The default transition object is a transition with a destination but no source object.
Name Button Icon Description
Default transition
Use a Default transition to indicate, when entering this level in the hierarchy, which state becomes active by default.
See the section titled Default Transitions on page 7-21 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. Events are broadcast in a top-down manner starting from the events parent in the hierarchy. Events are added, removed and edited through the Stateflow Explorer. See the section titled Defining Events on page 4-2 for more information.
Explorer
See Stateflow Explorer on page F-11.
Finder
See Stateflow Finder on page F-12.
Flow Graph
A flow graph is the set of flow paths that start from a transition segment that, in turn, starts from a state or a default transition segment.
F-6
Flow Path
A flow path is an ordered sequence of transition segments and junctions where each succeeding segment starts on the junction that terminated the previous segment.
Flow Subgraph
A flow subgraph is the set of flow paths that start on the same transition segment.
Graphical Function
A graphical function is a function whose logic is defined by a flow graph. See Working with Graphical Functions on page 3-50.
Hierarchy
Hierarchy enables you to organize complex systems 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 2-11 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, the transition to the 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 junction
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 be active.
See these sections for more information: History Junctions on page 7-35
F-7
Glossary
Example: Default Transition and a History Junction on page 8-19 Example: Labeled Default Transitions on page 8-21 Example: Inner Transition to a History Junction on page 8-29
Inner Transitions
An inner transition is a transition that does not exit the source state. Inner 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 7-24 and Example: Inner Transition to a History Junction on page 8-29 for more information.
Library Link
A library link is a link to a chart that is stored in a library model in a Simulink block library.
Library Model
A library model is a Stateflow model that is stored in a Simulink library. You can include charts from a library in your model by copying them. When you copy a chart from a library into your model, Stateflow does not physically include the chart in your model. Instead, it creates a link to the library chart. You can create multiple links to a single chart. Each link is called a chart instance. When you include a chart from a library in your model, you also include its state machine. Thus, a Stateflow model that includes links to library charts has multiple state machines. When Stateflow simulates a model that includes charts from a library model, it includes all charts from the library model even if there are links to only some of its models. However, when Stateflow generates a stand-alone or RTW target, it includes only those charts for which there are links. A model that includes links to a library model can be simulated only if all charts in the library model are free of parse and compile errors.
Machine
A machine is the collection of all Stateflow blocks defined by a Simulink model exclusive of chart instances (library links). If a model includes any library
F-8
links, it also includes the state machines defined by the models from which the links originate.
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. Stateflow notation consists of: A set of graphical objects A set of nongraphical text-based objects Defined relationships between those objects
Parallelism
A system with parallelism can have two or more states 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 State Decomposition on page 7-7 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 Users Guide for more information.
RTW Target
An RTW target is an executable built from code generated by the Real-Time Workshop. See Chapter 9, Building Targets for more information.
S-Function
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 the sfun target within Stateflow. For more information, see Using Simulink.
F-9
Glossary
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 continuous 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 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, 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 transitions among events and conditions. Every state has hierarchy. In a Stateflow diagram consisting of a single state, that states 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
F-10
actions that are executed in a sequence based upon action type. The action types are: entry, during, exit, or on event_name actions.
Name Button Icon Description
State
Stateflow Block
The Stateflow block is a masked Simulink model and is equivalent to an 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 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 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 Machine on page 2-4 for more information on Stateflow diagrams.
Stateflow Explorer
Use the Explorer to add, remove, and modify data, event, and target objects. See, Exploring Charts with Stateflow Explorer on page 6-3 for more information.
F-11
Glossary
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 Searching (Only) in Charts on page 6-14 for more information.
Subchart
A subchart is a chart contained by another chart. See Working with Graphical Functions on page 3-50.
Substate
A state is a substate if it is contained by a superstate.
Superstate
A state is a superstate if it contains other states, called substates.
Supertransition
A supertransition is a transition between objects residing in different subcharts. See Working with Supertransitions on page 3-64 for more information.
F-12
Target
A target is an executable program built from code generated by Stateflow or the Real-Time Workshop. See Chapter 9, Building Targets for more information.
Topdown Processing
Topdown processing refers to the way in which Stateflow processes states and events. In particular, Stateflow processes superstates before states. Stateflow processes a state only if its superstate is activated first.
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 source is 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.
Transition Path
A transition path is a flow path that starts and ends on a state.
Transition Segment
A transition segment is a single directed edge on a Stateflow diagram. Transition segments are sometimes loosely referred to as transitions.
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 arrowheads. Drag the mouse either horizontally or vertically to change the value. See the section titled Exploring Objects in the Editor Window on page 3-12 for more information.
F-13
Glossary
F-14
Index
Symbols
* in title bar 3-5 debugger control 10-8 API 11-2 references to properties and methods 11-4 array arguments 7-56 assignment operations 7-47 at operator 7-69
A
accessing existing objects (API) 11-21 with the find method 11-21 with the findDeep method 11-22 with the findShallow method 11-22 action definition of 2-14, E-2 action language array arguments 7-56 assignment operations 7-47 binary operations 7-44 bit operations 7-43 comments 7-65 components 7-41 condition action with transition action 8-14 continuation symbols 7-65 data and event arguments 7-56 definition of 2-15, E-2 directed event broadcasting 7-61 event broadcasting 7-59 floating point number precision 7-58 literals 7-64 ml() versus ml. 7-56 objects with actions 7-37 pointer and address operators 7-57 semicolon in 7-65 state action notation 7-40 time symbol 7-65 transition action notation 7-37 unary operations 7-46 address operators 7-57 after operator 7-66 animation
B
BadIntersection property (API) 11-19 before operator 7-68 binary operations 7-44 bit operations 7-43 box methods (API) B-26 properties (API) B-24 box object (API) description 11-3 breakpoints chart entry 10-7 event broadcast 10-7 overview 10-3 state entry 10-7 build method (API) C--5
C
C library functions 7-47 chart (Stateflow diagram) accessing chart object (API) 11-6 create new objects in (API) 11-7 debugger breakpoint property 3-48 description property 3-48 document link 3-48 editing 6-10 editor property 3-48
I-1
Index
methods (API) B-19 name property 3-46 notes. See notes open (API) 11-7 parent property 3-46 printing, large 3-71 properties (API) B-14 sample time property 3-47 setting properties 6-10 Simulink subsystem property 3-46 update method property 3-47 update methods for defining interface 5-4 classhandle method (API) C--6 Clipboard object (API) connecting to (API) 11-19 copying 11-24 description 11-3 methods (API) B-8 code generation error messages 9-21 comments (chart).See notes compilation error messages 9-21 condition definition E-3 definition of 2-12 notation overview 7-63 condition action cyclic behavior to avoid 8-17 with for loop 8-15 with transition action 8-14 condition coverage definition 10-26 example 10-32 specifying 10-22 conflicting transitions, debugging 10-16 connect to Stateflow objects (API) 11-18 connecting to
Clipboard object (API) 11-19 Editor object (API) 11-19 connective junction all conditions specified 7-29 back-tracking transitions to junctions 8-40 common events 7-34 common source 7-33 definition E-3 definition of 2-17 flow diagram 8-35 for loop 7-31 if-then-else decision 8-31 notation overview 7-28 self-loop 8-32 self-loop transition 7-30 transitions based on common event 8-39 transitions from a common source 8-37 transitions from multiple sources 8-38 unconditional transition 7-29 constructor for Stateflow objects (API) 11-18 containment of Stateflow objects 11-19 continuation symbols 7-65 copy method features and limitations 11-24 copy method (API) C--7 copying objects (API) by grouping (recommended) 11-25 copy method 11-24 Data, Event, and Target objects 11-27 individual objects 11-26 overview 11-24 using the Clipboard object 11-24 create handle to Stateflow objects (API) 11-18 new model and chart (API) 11-5 new objects in chart (API) 11-7 new state (API) 11-7
I-2
Index
D
Data 5-20 data constant 4-18 copying/moving to another parent 6-8 definition E-4 definition of 2-11 deleting 6-10 description property 4-21 exported 5-26 exported to an external code source 4-18 imported 5-28 imported from an external code source 4-18 input from Simulink 4-18, 5-18 local 4-17 methods (API) B-43 output to Simulink 4-18, 5-20 properties (API) B-39 renaming 6-10 setting properties 6-10 temporary 4-18 transferring properties 6-11 workspace 4-18 data dictionary definition E-4 data input from Simulink add and choose a parent task 5-17 apply and save task 5-18
changing index order 6-9 choose scope task 5-17 specify data attributes task 5-18 tasks 5-17 data output to Simulink add and choose a parent task 5-20 apply and save task 5-21 changing index order 6-9 choose scope task 5-20 specify data attributes task 5-20 tasks 5-20 data range violation, debugging 10-18 data scope and parent combinations 4-23 Debugger definition E-11 debugger action control buttons 10-7 active states display 10-8 animation controls 10-8 break button 10-7 break on controls 10-7 breakpoints display 10-9 browse data display 10-8 call stack display 10-8 clear output display 10-9 coverage display 10-8 display controls 10-8 Dynamic Checker options 10-8 Go button 10-7 including in the target build 10-2 main window 10-5 MATLAB command field 10-9 overview 10-2 status display area 10-6 Step button 10-7 Stop simulation button 10-8 typical tasks 10-2
I-3
Index
user interface 10-5 using 10-10 debugging model coverage 10-22 decision coverage chart as a superstate 10-23 chart as a triggered block 10-23 definition 10-23 example 10-32 specifying 10-22 superstates 10-23 transitions 10-26 decomposition definition E-5 specifying 3-16 default transition and exclusive (OR) decomposition 8-18 creating 3-33 definition 2-16, E-5 labeling notation 7-21 notation example 7-22 default transition notation, examples of to a junction 7-23 with a label 7-23 default transition semantics, examples of and a history junction 8-19 labeled default transition 8-21 to a junction 8-19 defaultTransitionsOf method (API) C--8 delete method (API) C--9
delete method (API)
using qualified event names 7-63 using send 7-62 directed event broadcasting semantics, examples of send 8-56 using qualified event names 8-58 displaying enumerated values for properties (API) 11-16 names of properties and methods (API) 11-15 sub-properties (API) 11-16 displaying properties and methods (API) 11-15 dot (.) notation (API) nesting 11-13 drawing area in Stateflow diagram editor 3-6
E
Editor object (API) connecting to 11-19 description 11-3 graphical changes 11-28 methods (API) B-7 properties B-6 either edge trigger 4-11 error messages code generation 9-21 compilation 9-21 parsing 9-20 target building 9-21 event broadcasting 7-59 copying/moving to another parent 6-8 definition E-6 definition of 2-10 deleting 6-10
example 11-20 deleting Stateflow objects (API) 11-20 destroying Stateflow objects (API) 11-20 dialog method (API) C--10 directed event broadcasting notation, examples of
I-4
Index
directed event broadcast using qualified names 7-63 directed event broadcasting 7-61 exported 5-23 imported 5-24 index property 4-8 methods (API) B-46 properties (API) B-44 renaming 6-10 representing hierarchy 7-6 setting properties 6-10 transferring properties 6-11 trigger property 4-8 event actions and superstates semantics example 8-42 event broadcast state action notation example 7-60 transition action notation example 7-60 event input from Simulink add and choose parent task 5-15 apply the changes task 5-16 changing index order 6-9 choose scope task 5-15 select the trigger task 5-16 tasks 5-15 event output to Simulink add and choose a parent task 5-19 apply and save task 5-19 changing index order 6-9 choose scope task 5-19 task overview 5-9 tasks 5-19 event triggers defining 5-12 defining function call 5-9 defining output to Simulink 5-8 function call example 5-9
function call semantics 5-11 every operator 7-70 exclusive (OR) decomposition and default transitions 8-18 exclusive (OR) state notation 7-8 Explorer contents of list 6-4 icons of objects 6-5 main window 6-4 moving objects to change parents 6-7 object hierarchy list 6-4 opening 6-3 opening new or existing model 6-8 overview 6-2, 6-3 parents of objects in Contents pane 6-5 properties in Contents pane 6-6 user interface 6-3 exploring and searching overview 6-2 exported data 5-26 event 5-23 external code sources defining interface for 5-23 definition 5-23
F
falling edge trigger 4-10 field Label 6-27 find method (API) C--11 examples 11-6 how to use 11-21 findDeep method (API) C--14 how to use 11-22 Finder definition E-12
I-5
Index
dialog box 6-15 clear button 6-17 close button 6-17 display area 6-18 help button 6-17 matches field 6-17 object type 6-16 refine button 6-17 representing hierarchy 6-19 search button 6-17 search history list 6-17 search method 6-16 string criteria field 6-15 overview 6-2 user interface 6-14 findShallow method (API) C--15 how to use 11-22 finite state machine definition E-6 references 2-3 representations 2-2 what is 2-2 floating point numbers precision in action language 7-58 flow diagram for loop notation example 7-31 notation example 7-32 notation overview 7-28 overview example 7-32 for loop notation example 7-31 semantics example 8-33 with condition action 8-15 function methods (API) B-29 properties (API) B-27 function call
defining output event 5-9 example output event semantics 5-11 output event example 5-9 function notation for API methods 11-14 function object (API) description 11-3 functions graphical, see graphical functions user-written 7-48 functions, calling C library 7-47 min and max 7-48 user-written C code 7-48
G
generate method (API) C--16 get method (API)
getting properties of objects 11-23 setting properties of objects 11-23 get method (API) C--17 examples 11-15 getCodeFlag method (API) C--18 global methods (API) B-4 graphical functions 3-50?? creating 3-50 exporting 3-55 inlining 3-57 invoking from charts 3-54 invoking from custom code 9-29 properties 3-55 graphical objects copying 3-11 cutting and pasting 3-11 graphics editor object button modes 3-15
I-6
Index
H
help method (API) C--19
example 11-15 Hexadecimal 7-58 hexadecimal notation 7-58 hierarchy 2-11 definition E-7 definition of 2-11 events 7-6 state 7-5 transition 7-6 history junction and a default transition semantics example 8-19 and an inner transition semantics example 8-29 definition E-7 definition of 2-13 use example 7-35
definition E-8 notation overview 7-24 processing a second event with an inner transition to a connective junction semantics example 8-28 processing a second event within an exclusive (OR) state semantics example 8-24 processing a third event within an exclusive (OR) state semantics example 8-25 processing one event with an inner transition to a connective junction semantics example 8-26 processing one event within an exclusive (OR) state semantics example 8-23 to a connective junction(1) notation example 7-25 to a history junction notation example 7-26 to a history junction semantics example 8-29 innerTransitionsOf method (API) C--20 installation xxvii
I
I/O event triggers 4-10
if-then-else
J
junction changing size 3-23 description property 3-25 document link property 3-25 editing properties 3-24 methods (API) B-38 moving 3-24 parent property 3-25 properties 3-25 properties (API) B-37 junction, connective See connective junction
another notation example 7-29 notation example 7-29 semantics example 8-31 implicit local events example 4-12 overview 4-11 imported data 5-28 event 5-24 inlining graphical functions 3-57 inner transition before using an inner transition(1) notation example 7-24
I-7
Index
K
keywords
change(data_name) 7-41 during 7-41 entry 7-41 entry(state_name) 7-41 exit 7-41 exit(state_name) 7-41 in(state_name) 7-41 matlab() 7-42 matlab. 7-42 on event_name 7-41 send(event_name,state_name) 7-42
description 11-3
make method (API) C--21
L
Label field 6-27 labels multi-line labels using API 11-29 listing enumerated values for properties (API) 11-16 names of properties and methods (API) 11-15 sub-properties (API) 11-16 listing properties and methods (API) 11-15 literals 7-64
M
machine definition E-8 methods (API) B-13 properties (API) B-10 setting properties 6-10 machine object (API) accessing 11-6
MATLAB API scripts 11-11 requirements for xx max function 7-48 MCDC Coverage definition 10-26 example 10-32 explanation 10-33 irrelevant conditions 10-33 specifying 10-22 menu bar in Stateflow diagram editor 3-5 methods (API) all objects B-5 box B-26 chart B-19 Clipboard B-8 data B-43 description of 11-3 displaying 11-15 Editor B-7 event B-46 function B-29 function notation 11-14 global B-4 junction B-38 machine B-13 naming 11-13 nesting 11-14 note B-32 overview of methods C-4 Root B-9 state B-23 target B-50 transition B-36
I-8
Index
state
during action 7-12 entry action 7-11 exit action 7-12
example 11-15 min function 7-48 ml() functions 7-51 ml. name space operator 7-54 model coverage Condition Coverage 10-26 definition 10-22 MCDC Coverage 10-26 report 10-22 Chart 10-30 Details 10-28 State 10-31 Subsystem 10-29 Summary 10-28 Transition 10-32 reports for Stateflow charts 10-27 specifying reports 10-22 tool 10-22
N
naming of properties and methods (API) 11-13 notation connective junction overview 7-28 definition 7-2, E-9 definition of 2-3 flow diagram overview 7-28 graphical objects 7-3 history junctions and inner transitions overview 7-35 how is the notation checked 7-2 inner transition overview 7-24 keywords 7-41 motivation for 7-2 representing hierarchy 7-4 self-loop transition overview 7-26
labeling example 7-11 name 7-11 on action 7-12 transition label example 7-15 labeling 7-15 transition label condition 7-15 condition action 7-16 event 7-15 transition action 7-16 transition types 7-17 notes (chart) changing color 3-44 changing font 3-44 creating 3-43 deleting 3-45 editing 3-43 methods (API) B-32 moving 3-45 properties (API) B-30 TeX format 3-44
O
object palette in Stateflow diagram editor 3-6 objects (API) copying 11-24 getting properties 11-23 setting properties 11-23 obsoleted features
I-9
Index
transition actions for transitions into junctions E-3 outerTransitionsOf method (API) C--23 output events defining edge-triggered 5-12 outputData method (API) C--24 overlapping object edges 11-19 overview of API methods C-4
P
parallel (AND) state event broadcast condition action semantics example 8-52 event broadcast state action semantics example 8-44 event broadcast transition action semantics example 8-48 notation 7-8 parallelism definition E-9 definition of 2-15 parse method (API) C--26 parsing error messages 9-20 how to 9-16 tasks 9-16 pasteTo method (API) C--27 Pointer 7-57 pointer operators 7-57 prerequisites xx properties (API) description of 11-3 displaying 11-15 displaying enumerated values for 11-16 displaying sub-properties 11-16 getting 11-23
naming 11-13 nesting 11-13 of Box object B-24 of Chart object B-14 of Data object B-39 of Editor object B-6 of Event object B-44 of Function object B-27 of Junction object B-37 of Machine object B-10 of Note object B-30 of State object B-20 of Target object B-47 of Transition object B-33 setting 11-23
Q
quick start creating a Simulink model 1-6 creating a Stateflow diagram 1-9 debugging the Stateflow diagram 1-18 defining the Stateflow interface 1-12 generating code 1-16 overview 1-5, 2-30 running a simulation 1-15 sample solution 1-5 Stateflow API 11-5 Stateflow typical tasks 1-5
R
Real-Time Workshop definition E-9 glossary definition D-3 rebuildAll method (API) C--28 references 2-3
I-10
Index
regular expressions logical operators D-4 metacharacters D-3 quantifiers D-5 Search & Replace D-1 Stateflow Finder 6-16 syntax D-3 tokens D-6 replacing 6-21 rising edge trigger 4-10 Root object (API) access 11-5 description 11-3 methods B-9 RTW target 1-4 definition E-9
S
saving Simulink model (API) 11-11 Stateflow diagram 1-19 script of API commands 11-11 Search & Replace 6-21 containing object 6-28 Custom Code field 6-27 Description field 6-27 Document Links field 6-27 Explore 6-29 icon of found object 6-28 Messages object type 6-32 Name field 6-26 object properties 6-29 object types 6-22 portal area 6-28 Replace All button 6-32
Replace All in This Object button 6-32 Replace button 6-31 replacement text 6-22 Search button 6-27 Search For field 6-22 search order 6-28 Search Scope 6-22 Show Portal 6-29 viewer 6-28 viewing a match 6-28 searching 6-21 entering text to search for 6-22 Finder user interface 6-14 self-loop transition creating 3-32 notation example 7-30 notation overview 7-26 semantics definition E-10 definition of 2-3 execution order 8-60
send
keyword 7-42 notations example 7-62 semantics example 8-56 set method (API) C--30 setCodeFlag method (API) C--31 sfclipboard method (API) C--33 example 11-19 sfexit method (API) C--34 sfhelp method (API) C--35, C--39 sfnew method (API) C--36 sfprint method (API) C--37 sfprj directory generated code 1-16 model information 1-19 sfsave method (API) C--40
I-11
Index
S-function definition E-9 shortcut menus in Stateflow diagram editor 3-6 Simulink definition E-10 requirements for xx Simulink model and Stateflow machine relationship between 2-4 smart transitions. See transition, smart sourcedTransitionsOf method (API) C--41 state active and inactive notation 7-8 active notation 7-8 changing incoming transition arrowhead size 3-21 corners 3-26 create (API) 11-7 debugger breakpoint property 3-19 definition E-10 description property 3-19, 3-57 document link property 3-19, 3-57 editing 6-10 exclusive (OR) decomposition notation 7-8 grouping and ungrouping 3-21 inactive notation 7-8 label property 3-19 label, multi-line (API) 11-29 labeling notation 7-10 methods (API) B-23 name property 3-19 notation during action 7-12 entry action 7-11 exit action 7-12 labeling example 7-11 name 7-11
on action 7-12 notation overview 7-7 operations 3-16 parallel (AND) decomposition notation 7-8 properties (API) B-20 representing hierarchy 7-5 resizing 3-16 setting properties 6-10 specifying decomposition 3-16 unique name notation example 7-12 state inconsistencies, debugging 10-14 state label changing font size 3-21 state object (API) description 11-3 Stateflow 3-71 applications, types of 1-2 component overview 1-3 defining interfaces overview 2-6 design approaches 1-3 feature overview 1-2 representations 2-2 Stateflow API 11-2 box object 11-3 chart object (API), accessing 11-6 Clipboard object 11-3 common properties and methods 11-3 create new model and chart 11-5 Editor object (API) 11-3 function object 11-3 machine object 11-3 machine object (API), access 11-6 methods of objects 11-3 naming and notation 11-13 object hierarchy 11-2 open chart 11-7 properties of objects 11-3
I-12
Index
quick start 11-5 Root object 11-3, 11-5 state object 11-3 unique properties and methods 11-3 Stateflow block considerations in choosing continuous update 5-7 continuous 5-4 continuous example 5-8 defining a continuous 5-7 defining a sampled 5-5 defining a triggered 5-5 defining an inherited 5-6 inherited 5-4 inherited example 5-6 sampled 5-4 sampled example 5-6 triggered 5-4 triggered example 5-5 update methods 5-4 Stateflow diagram definition E-11 graphical components 2-8 objects 2-8 saving 1-19 update methods 5-4 Stateflow diagram editor drawing area 3-6 menu bar 3-5 object palleter 3-6 shortcut menus 3-6 status bar 3-6 title bar 3-5 toolbar 3-5 zoom control 3-6 Stateflow interfaces overview 5-2
status bar in Stateflow diagram editor 3-6 struct method (API) C--44 subcharts 3-50 creating 3-59 editing 3-62 opening 3-61 substate definition E-12 superstate definition E-12 supertransitions 3-64 labeling 3-69 Symbol Autocreation Wizard 4-27
T
target building error messages 9-21 copying/moving to another parent 6-8 deleting 6-10 in Explorer 6-7 methods (API) B-50 properties (API) B-47 setting properties 6-10 transferring properties 6-11 temporal logic operators 7-65 after 7-66 at operator 7-69 before operator 7-68 every operator 7-70 usage rules 7-65 text replacing 6-21, 6-22 searching 6-21
I-13
Index
time 7-65 title bar in Stateflow diagram editor 3-5 toolbar in Stateflow diagram editor 3-5 Tools Search & Replace 6-21 transition changing arrowhead size 3-30 creating and deleting 3-26 creating straight transitions 3-26 debugger breakpoint property 3-32 debugging conflicting 10-16 default transitions 3-33 definition E-13 definition of 2-10 definition of default transition 2-16 description property 3-32 destination property 3-32 document link property 3-32 editing properties 3-31 label format 3-29 label property 3-32 labeling 3-29 labels, multi-line (API) 11-29 methods (API) B-36 moving 3-27 moving attach points 3-28 moving label 3-28 non-smart anchored connection points 3-41 asymmetric distortion 3-41 notation label example 7-15 labeling 7-15 transition actions for transitions into junctions E-3
types 7-17 parent property 3-32 properties 3-32 properties (API) B-33 representing hierarchy 7-6 self-loop transitions 3-32 smart bowing symmetrically 3-39 connecting to junctions at 90 degree angles 3-37 overview 3-34 sliding and maintaining shape 3-36 sliding around surfaces 3-34 snapping to an invisible grid 3-38 source property 3-32 to and from exclusive (OR) states(1) semantics example 8-8 to and from exclusive (OR) states(2) semantics example 8-9 to and from exclusive (OR) states(3) semantics example 8-10 to and from junctions notation example 7-18 to and from OR states notation example 7-18 to and from OR superstates notation example 7-19 to and from substates notation example 7-20 valid labels 3-29 transition action with condition action 8-14 transition label changing font size 3-30 condition 3-29 condition action 3-29 event 3-29 notation condition 7-15 condition action 7-16
I-14
Index
event 7-15 transition action 7-16 transition action 3-29 typecast operators 7-59 typographical conventions (table) xxvi
U
unary actions 7-46 unary operations 7-46 user-written C code functions 7-48 user-written functions 7-48
V
view method (API) C--45
W
wormhole 3-66
Z
zoom control in Stateflow diagram editor 3-6 zoomIn and zoomOut methods (API) C--46 zooming a diagram 3-13 shortcut keys 3-14 using zoom factor selector 3-13
I-15
Index
I-16