You are on page 1of 250

1 0000

Matlab, Simulink, StateFlow and xPC Target for Controls Engineers

Sabri Cetinkunt, Ph.D. Professor Department of Mechanical and Industrial Engineering University of Illinois at Chicago c All rights reserved Last Revision: September 14, 2011

Contents
1 Matlab and Its Tools 1.1 Matlab Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.1 Matlab Setup Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.2 Data in Matlab Environment . . . . . . . . . . . . . . . . . . . . . . 1.1.3 Program Flow Control Statements in Matlab . . . . . . . . . . . . . 1.1.4 Functions in Matlab: M-script les and M-function les . . . . . . . 1.1.5 Input and Output in Matlab: . . . . . . . . . . . . . . . . . . . . . . 1.1.6 Matlab Toolboxes: . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.7 Controller Design Functions: Transform Domain and State Space Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 Simulation of Dynamic Systems Using Matlab . . . . . . . . . . . . . . . . . 1.2.1 Linearization: Linearization of Nonlinear Functions . . . . . . . . . . 1.2.2 Linearization of Nonlinear First Order Dierential Equations . . . . 1.2.3 Linearization of Multi-Dimensional Nonlinear Diential Equations . 1.2.4 Numerical Solution of ODEs and Simulation of Dynamic Systems . . 1.2.5 Numerical Methods for Solving O.D.Es . . . . . . . . . . . . . . . . 1.2.6 Time Domain Simulation of Dynamic Systems . . . . . . . . . . . . 1.3 Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3.1 Simulink Block Examples . . . . . . . . . . . . . . . . . . . . . . . . 1.3.2 S-Functions in C Language . . . . . . . . . . . . . . . . . . . . . . . 1.4 Stateow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.4.1 Accessing Matlab Data and Matlab Functions from Stateow Chart 1.4.2 Function Calls from Stateow Chart . . . . . . . . . . . . . . . . . . 1.5 Real-time Auto Code Generation: RTW and SFC . . . . . . . . . . . . . . . 1.5.1 Target language compiler (TLC) . . . . . . . . . . . . . . . . . . . . 1.6 xPC Target: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.6.1 xPC Target Application Example: Testing CAN Bus . . . . . . . . . 1.6.2 xPC Target Application Example: Digital and Analog I/O Using Diamond DMM-AT-32X Card . . . . . . . . . . . . . . . . . . . . . 13 13 20 21 30 33 39 64 64 69 69 72 73 76 78 80 90 100 126 176 191 197 227 233 233 242 243

CONTENTS

List of Figures
1.1 1.2 Matlab, its add-on tools and their typical relationships in an engineering application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Real-time controller development process using Matlab environment. In this gure, target real-time controller is shown as the xPC hardware platform which is based on DOS and PC-bus. There are many other target real-time controller harware supported by Matlab. . . . . . . . . . . . . . . . . . . . Controls development phases: Phase 1) O-line development and non-real time simulation. 2)Hardware in the loop real-time simulation, 3) Real-time controller testing with a prototype controlled process hardware. . . . . . . . Matlab environment and main user interface windows. . . . . . . . . . . . . Example for calculating requried sattelite speed versus altitude. . . . . . . . Output plot of the Matlab M-function le example. . . . . . . . . . . . . . . Excel data le I/O example: the content of Sheet1 and Sheet2 of the Excel data le in the begining. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Excel data le I/O example: the content of Sheet1 and Sheet2 of the Excel data le after writing to it. . . . . . . . . . . . . . . . . . . . . . . . . . . . Output plot of the Matlab M-function le example. . . . . . . . . . . . . . . Excel data le I/O example: plot of the data. . . . . . . . . . . . . . . . . . Polar plot examples: Cos(x) function and 10 - 10 Sin(x) function. . . . . . . Polar plot example: Nautilus curve. . . . . . . . . . . . . . . . . . . . . . . 3-D line plot example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-D curve plot example: tornado plot. . . . . . . . . . . . . . . . . . . . . . 3-d surface plot examples: using mesh, surf, contour and surfc functions. 3D movie animation using getframe() and movie() functions. . . . . . . . Simulation results of a second order system for impulse, step and a userdened input function using the Matlab functions impulse, step and lsim. . Linearization of functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pendulum model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Eulers method for solution of o.d.es . . . . . . . . . . . . . . . . . . . . . . 4th order Runga-Kutta nite dierence approximation. . . . . . . . . . . . . A continuous time feedback control system - controller and process are both analog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

16

17

1.3

1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.17 1.18 1.19 1.20 1.21 1.22

17 19 30 36 48 49 49 51 55 56 59 60 61 63 77 86 87 87 88 89

LIST OF FIGURES 1.23 A digital control system: process is analog, controller is digital. . . . . . . . 90 1.24 Simulation results of a mass-force system under a PD controller. Commanded signal is a step function starting at time t = 1.0sec. . . . . . . . . . . . . . 91 1.25 Simulink window: Simulink library browser. To start a new model le or open an existing model le, use the File menu. Then pick, drag and drop component blocks from this library window. . . . . . . . . . . . . . . . . . . 93 1.26 Drawing connections in Simulink: straight and perpendicular lines, diagonal lines, creating break points on a line. . . . . . . . . . . . . . . . . . . . . . . 95 1.27 Simulink model of a mass-spring-damper system. . . . . . . . . . . . . . . . 95 1.28 The mass-spring-damper system is grouped into a sub-system block showing the input and output ports, hiding the internal details of it. . . . . . . . . . 96 1.29 Grouping and masking of Simulink blocks. This example shows the grouping and masking for a PD control block diagram. . . . . . . . . . . . . . . . . . 98 1.30 PD control and mass-spring-damper system model and simulation results using Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 1.31 Integrator Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 1.32 Inport and outport blocks for Simulink subsystems. . . . . . . . . . . . . . . 101 1.33 Ground block used to terminate open input point, Terminal block is used to terminate open output point. . . . . . . . . . . . . . . . . . . . . . . . . . . 101 1.34 Logical, comparator blocks, and look-up tables. . . . . . . . . . . . . . . . . 102 1.35 Enable and trigger blocks to make a subsystem enabled and triggered. . . . 103 1.36 Goto and From blocks to simplify line connections in simulink graphical model description. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 1.37 Connection signal line management blocks to simplify graphical display: Mux, Demux, Bus Create and Bus Selector blocks used in an example. . . . 104 1.38 Input sources and ouput destinations for the data of a Simulink model. . . . 105 1.39 Function blocks in Simulink: Matlab Function (a single Matlab function), Fnc() allows an expression, Embedded Matlab Function which is linked to an m-function script le. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 1.40 Decision blocks: loops (for, while, do-while) and conditional (if, switch) blocks.108 1.41 Nonlinear dynamic model of a pendulum and simulation result in Simulink. 110 1.42 Liquid level control in a container. . . . . . . . . . . . . . . . . . . . . . . . 112 1.43 A liquid level/ow-rate control system (a) components, (b) block diagram . 118 1.44 Model and simulation of a liquid level control system. . . . . . . . . . . . . 119 1.45 Temperature control of a space (i.e. room or furnace). . . . . . . . . . . . . 119 1.46 Model and simulation of furnace or room temperature control system. . . . 120 1.47 Web tension control system. . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 1.48 Model and simulation of web tension control system. Top gure is the Simulink model of the tension control system. The left plot shows the commanded tension on the top and actual tension at the bottom. Right plot shows the wind-o and wind-up speeds. . . . . . . . . . . . . . . . . . . . . 121

LIST OF FIGURES 1.49 Conguration of Parameters in Simulink for a particular model simulation. Before running a simulation, Simulation > Conguration Parameters > Solver (and other options as needed) should be congured appropriately for the model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.50 Simulink model for an ABS brake system and vehicle model simulation shown with two main subsystems: ABS controller and vehicle dynamics. . . . . . . 1.51 Simulink model for an ABS brake system and vehicle model simulation shown with two main subsystem details: details of ABS controller and vehicle dynamics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.52 Simulation results for the ABS system. The gure on the left is without ABS controller, the gure on the right is with ABS controller. . . . . . . . . . . 1.53 Adding an S-function block to a Simulink model le. . . . . . . . . . . . . . 1.54 Developing S-functions in C-language and using them in Simulink models. . 1.55 Writing an S-Function le using S-Function Builder block. . . . . . . . . 1.56 S-functions and Simulink operation. . . . . . . . . . . . . . . . . . . . . . . 1.57 Writing an S-Function le using S-Function Builder Block. . . . . . . .

122 123

124 125 128 130 132 134 142

1.58 Using an S-Funtion le in a Simulink model: mass-spring system with a PID controller, where the PID controller is implemented as an C-MEX S-function. 143 1.59 Writing an S-Funtion le using S-Function Builder Block: Initialization setup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.60 Writing an S-Funtion le using S-Function Builder Block: Data Properties >Input ports setup. . . . . . . . . . . . . . . . . . . . . . . . . . . 1.61 Writing an S-Funtion le using S-Function Builder Block: Data Properties > Output port setup. . . . . . . . . . . . . . . . . . . . . . . . . . 1.62 Writing an S-Funtion le using S-Function Builder Block: Data Properties > Parameters menu option. Data types are entered at the bottom. Actual parameter values are entered at the top. . . . . . . . . . . . . . . . 1.63 Writing an S-Funtion le using S-Function Builder Block: Data Type Attributes properties menu. . . . . . . . . . . . . . . . . . . . . . . . . . . 1.64 Writing an S-Funtion le using S-Function Builder Block: Library pane is used to dene the libraries and other les referenced by the S-function. . 1.65 Writing an S-Funtion le using S-Function Builder Block: Outputs logic section. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.67 Writing an S-Funtion le using S-Function Builder Block: Build the S-function for a dynamically loadable executbale code. This step can also be performed by executing the mex lename command in the Matlab command window. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 145 146

147 148 149 150

1.66 Writing an S-Funtion le using S-Function Builder Block: Discrete Updates.151

152

LIST OF FIGURES 1.68 Using an S-funtion le in a Simulink model: copy S-function block into the model from User-Dened Functions library of Simulink. Then doubleclick on it. Then type the name of the S-function le in the name area, and provide parameters (if any). When you click apply, the S-function block should reect the correct number of input and output ports. Finally, connect the input and output signals to the rest of the model. The system is ready for simulation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.69 Simulation results: top two plots are commanded and actual positions, bottom plot is the controller output. . . . . . . . . . . . . . . . . . . . . . . . . 1.70 Writing an S-Function le by directly modifying a template C-MEX le . . 1.71 Writing an S-Function le by use of Legacy Code Tool (LCT): C source and header les. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.72 Writing an S-Function le by use of Legacy Code Tool (LCT) to generate and compile the S-function les. . . . . . . . . . . . . . . . . . . . . . . . . 1.73 Example of les involved in writing an S-function using Legacy Code Tool (LCT): on the left, the Simulink model les using the S-function created by the LCT. On the right, the text fource les for creating the S-function MEX le: the script-m le to create MEX le for S-function, and C-source le which the script le uses to create a another source le ex sfun myfun, and Matlab command line command to run the script-m le. On the far right corner, the result of the simulation of the Simulink model is shown which conrms the correct operation of the S-function. . . . . . . . . . . . . . . . 1.74 Stateow and its relationship to Simulink. . . . . . . . . . . . . . . . . . . .

153 154 168 173 174

175 177

1.75 Stateow windows in Matlab. . . . . . . . . . . . . . . . . . . . . . . . . . . 179 1.76 Stateow Editor window and its tools. On the Object palette the graphical components of the Stateow chart are displayed: state, history junciton, default transition, connective junction, truth table, function call (may used to implement Actions), embedded Matlab functions (may be used to implement Actions), and box for graphical grouping. . . . . . . . . . . . . . . . 180 1.77 Stateow Editor Menu. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 1.78 Stateow Editor Menu: File > Chart Properties and File > Machine Properties.182 1.79 Typical steps involved in designing a Stateow chart as part of a Simulink model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 1.80 Two states: X and Y, each with sub-states X1 and Y1, and two transitions dened between them, along with conditions and actions. The states X and Y are exclusive (OR type) states which meabs only one of them can be active at a given time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 1.81 Decomposition of states: exclusive (OR) or parallel (AND) states. At a super state, only one of the exclusive states can be active, whereas multiple parallel states (AND states) can be concurrently active. . . . . . . . . . . . . . . . . 193

LIST OF FIGURES

1.82 Graphical components of a Stateow diagram: state (parallel and exclusive), transitions (normal transitions, default transitions), actions, junctions (connective and history types), conditions. . . . . . . . . . . . . . . . . . . . . . 194 1.83 Example Stateow model: illustration of accessing Matlab workspace data (for read and write) and Matlabs built-in functions in Stateow chart. . . . 196 1.84 Calling User-Written C-functions from Stateow Charts: calls from transition actions and state actions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 1.85 Including User-Written C-functions from Stateow Charts for Simulation Target. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 1.86 Including User-Written C-functions from Stateow Charts for RTW Target. 200 1.87 Example to illustrate how to include user-written C-functions from Stateow Charts for Simulation Target: Illustrative gure 1 of 2. Windows 1 thru 6 shows the development process involved in order. . . . . . . . . . . . . . . . 202 1.88 Example to illustrate how to include user-written C-functions from Stateow Charts for Simulation Target: Illustrative gure 2 of 2. Windows 7 thru 11, including the location of the C-source le in the directory, how it is specied in the dialog window of Stateow Editor, and the C-source le content. . . 203 1.89 Adding an Embedded Matlab Function in a Stateow chart: 1. Type the name of the function in an action (i.e a transition action). 2. Uing Embedded Matlab Function icon from the Stateow Chart Editor, copy one to the Chart, and type the name on it. 3. Double-click on the Embedded Matlab Function rectangle to bring up the text editor for the function, 4. Type in the logical code in text le, 5. from the Embedded Matlab Editors tool menu, select Model Explorer, and dene the input-output data (as well as local data) to the function. . . . . . . . . . . . . . . . . . . 205 1.90 Adding an Embedded Matlab Function in a Stateow chart: from the Embedded Matlab Editors tool menu, select Model Explorer, and dene the input-output data as well as local variables to the function. . . . . . . . . . 206 1.91 Adding an Embedded Matlab Function in a Stateow chart: one of two (1/2) sets of windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 1.92 Adding an Embedded Matlab Function in a Stateow chart: two of two (2/2) sets of windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 1.93 Liquid level control example using Stateow chart for supervisory control logic.211 1.94 Liquid level control example using Stateow chart for supervisory control logic: Stateow chart details. This Stateow chart implements the supervisory logic shown in Matlab text programming language form shown in the previos page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 1.95 Simulation results for the liquid level control example using Stateow chart for supervisory control: Scope 1 top: Desired Liquid Level, Scope 1 botom: Measured Liquid Level, Scope 2 top: Supervisory Controller Output: Control Mode (1, 2, 3), Scope 2 bottom: Control Signal to Valve Amplier. . . . . . 213

10

LIST OF FIGURES 1.96 Automotive powertrain components: engine, transmission (torque converter and gear set), nal drive and wheel. . . . . . . . . . . . . . . . . . . . . . . 1.97 Look-up table for gear shift logic for a 4-speed automatic transmission. . . 1.98 Simulink and Stateow model of the automatic transmission control and powertrain. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.99 Simulink model details of engine and transmission. . . . . . . . . . . . . . 1.100Simulink model details of transmission. . . . . . . . . . . . . . . . . . . . . 1.101Stateow chart for the automatic transmission control logic. . . . . . . . . 1.102Simulink models of vehicle dynamics: considered as inertia with nal gear ratio, tire radius, and road resistance. . . . . . . . . . . . . . . . . . . . . . 1.103Simulation results of automotive powertrain and automatic transmission control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.104RTW and SFC conguration example. For dierent target CPUs, dierent settings are used. Many third party target CPU hardware suppliers provide tools to congure RTW and SFC for their particular target hardware. . . . 1.105Conguring the auto-code generation process in Simulink and Stafeow for xPC Target Hardware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.106An example model in Simulink: Simulation version (non-real time) and realtime version with appropriate I/O software drivers for the target ECU. . . . 1.107xPC Hardware: (top view) - components shown separately in PC-104 form factor: DC power supply, CPU card, I/O card(s) and connectors, bottom view) - components assembled in PC-104 stack (without the enclosure) . . 1.108xPC Target Explorer Window and target boot oppy creation. . . . . . . . 1.109Host PC and target xPC: parameter tunning and signal logging or tracing. 1.110Host PC and target xPC: Signal (data) logging. . . . . . . . . . . . . . . . 1.111Host PC and target xPC: Graphical User Interface (GUI) . . . . . . . . . . 1.112xPC Target application example: 1. the xPC hardware (PC/104 based CPU board, CAN bus Card, DC power supply card), 2. Host PC is a notebook PC which hosts the Matlab development environment, 3. Ethernet connection cable between the two PCs, 4. VGA monitor connected to the xPC for monitoring and debugging purposes. . . . . . . . . . . . . . . . . . . . . . . 1.113Example Simulink program to test CAN bus communication. . . . . . . . . 1.114A picture of the VGA monitor screen while running the CAN bus test application program on the target PC (xPC hardware) in real-time. . . . . . . . 1.115xPC Target application example: 1. the xPC hardware (PC/104 based CPU board, I/O Card by Diamond DMM-32-ATX, DC power supply card), 2. Host PC is a notebook PC which hosts the Matlab development environment, 3. Ethernet connection cable between the two PCs, 4. VGA monitor connected to the xPC for monitoring and debugging purposes. . . . . . . . 1.116Example Simulink program to test digital and analog I/O. . . . . . . . . .

221 221 222 223 224 225 226 228

230 232 234

237 238 240 241 242

244 245 246

246 247

LIST OF FIGURES 1.117A picture of the VGA monitor screen and the digital storage oscilloscope, while running the digital I/O test application program on the target PC(xPC hardware) in real-time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

11

248

12

LIST OF FIGURES

Preface
Modern control engineers use Matlab and its tools extensively in control system development. In addition to Matlab, the following tools are used as part of a control system development, proto-type deployment and testing: Simulink, Stateow, Real Time Workshop (RTW) and Stateow Coder (SFC). Simulink is the main graphical modeling tool for control system design. Stateow is a complimentary tool that is most suitable for modeling event-driven supervisory logic aspects of a control software, where as Simulink is more suitable for more mathematical aspects of it. RTW and SFC are auto-code generation tools for Simulink and Stateow so that developed code can be automatically converted to Clanguage and deployed on a target microcontroller hardware. There are many, and growing, number of target microcontroller/DSP hardware supported by Matlab and its tools. One of the most general purpose one of the those is xPC hardware. xPC is an industrial PC/104 bus based controller harware architecure. It is a exible and general purpose real-time controller harware platform for development purposes. Matlab and its tools support the xPC hardware thru xPC Target software tool that allows the RTW and SFC to generate C-code for the xPC target hardware. The purpose of this tutorial is to provide one concise learning tool for control engineers who use Matlab and its tools (Simulink, Stateow, RTW, SFC, xPC Target). The concise, to the point presentation of this complete suite of development tools is the objective of the tutorial. Quite often, an engineer is faced with multiple manuals with thousands of pages of detailed reference information. There are very few reference books or tutorials that address the complete suite of Matlab and its tools used by a typical control engineer. This makes the learning process rather long with many unnecessary details. The view taken here is that only the essential elements of software that are needed in control system development are discussed. In addition, all of the Matlab tools that one would need in control system development are discussed within a single document. As is the case in any learning, the student must be active participant in the process as opposed to a passive listener or reader. This is especially true in learning a programming language such as Matlab. Therefore, working with examples and trying out variations of the examples and making them work, and reecting on the results without rush, but slow-steady-calm thinking, is essential for successful study. It is hoped that this tutorial will be a useful concise learning tool for practicing control engineers and students. Sabri Cetinkunt, PhD University of Illinois at Chicago January 2008, Chicago

Chapter 1

Matlab and Its Tools


1.1 Matlab Overview

Matlab is a general purpose modeling and simulation software, widely used in the world by control engineers. This brief discussion provides an introduction to Matlab and its tools in order to get the students start programming in Matlab environment as quickly as possible instead of referring them to a large set of Matlab manuals with thousands of pages. The student can use this introduction as a starting point, and get more details on specic points using the online help of Matlab. Matlab software package is an integrated software tool with many components and new components are being added continuously. Those components are 1. Matlab being the main front end tool, text based programming environment. In addition to those basic Matlab components, there are Toolboxes that can be added to each one to increase its capabilities. For instance, Control Systems Toolbox can be added to Matlab to extend its function libraries for that purpose. Similar toolboxes exit for Simulink, Stateow and other software components. 2. Simulink for graphical block diagram modeling of dynamic systems, 3. Stateow for event-driven system and supervisory control logic modeling, 4. Real-time Workshop (RTW) for auto-code generation in C-language from Simulink les, 5. Stateow Coder (SFC) for auto-code generation in C-language from Stateow les, 6. xPC-Target software for the PC-based embedded hardware tool called xPC-hardware. There are other embedded target microcontroller software and hardware combinations supported, such as Real-time Windows environment to run real-time code on a PC with relevant I/O cards. 13

14

CHAPTER 1. MATLAB AND ITS TOOLS 7. C Compiler to compile the generated code for the target embedded controller hardware. Matlab installation includes the LCC C-Complier.

In the discussion that follows, we used the term Matlab or Matlab/Simulink to refer to this whole suite of tools in Matlab package. If testing on actual embedded controller hardware is not needed and simulations are sucient for a given purpose, then only the Matlab, Simulink and Stateow package components are needed. It should be noted that the supervisory and even driven logic can be coded in Matlab and Simulink alone without the use of Stateow. However, the Stateow environment makes it more convenient and easy to code the event driven nature of logic. Many examples are provided under Matlab > Help > Demos menu with example categories in automotive, aerospace and heating systems. The trend in industrial practice is that modern controls engineering is being done using the auto-code generation tools such as RTW and SFC in Matlab environment. A control system is developed graphical tools, such as Simulink and Stateow, simulated and analyzed on the computer. Then the same code is tested on a target embedded controller. That same code is is the C-code auto-generated from the graphical diagrams of Simulink and Stateow using RTW and SFC. That real-time controller software is run on the target embedded controller hardware which can be connected to an actual prototype hardware of the controlled process or machine, or it can run in combination with another computer which may simulate the controlled process dynamics in real time. The former case is called the rapid controls development process or real-time rapid prototyping. The later case is called the hardware in the loop (HIL) simulation. HIL is the testing and validation tool between pure software simulation (100% software) and pure hardware (100 % actual machine with all its hardware and embedded software), where some of the components are actaul hardware and some are simulated in real-time software. HIL tools have been developed rapidly in recent years in that various hardware components of the control system is included in a real-time testing/validation process where some of the components are present in hardware and runs in real time (such as electronic control unit (ECU), engine, transmission, dynamometer) and some of the components are present in software form running in real time and its results are reected on the control system by a generic simulator (i.e. dynamometer which represent the load on the powertrain based on the machine dynamics and operating conditions). Early versions of HIL simulations were used to test the static input output behavior of the ECU running the intended real time control code, where I/O behavior is tested with a static I/O simulator. Modern HIL simulations are performed for dynamic testing where the I/O to ECU is driven by dynamic and detailed models of the actual machine. The fundamental challenge in HIL simulations is the to nd a balance between the model accuracy (hence more complex and detailed models) and the need for real-time execution. As the real-time modeling capabilities improve, virtual dynamic testing and validation of complete machines using HIL will become a reality. In summary, there are three phases of control system development using Matlab tools (Fig.Fig:matlab4): 1. Develop control algorithm, the run non-real simulations with the dynamic model of

1.1. MATLAB OVERVIEW

15

the controlled process o-line using a desktop PC environment. This is called non real time simulation. 2. Run the control algorithm at a target hardware (embedded controller or general purpose computer such as PC as long as it has the capacity to run the controller code in real-time) and have the process dynamics run in real-time on another computer. This is called hardware in the loop (HIL) simulation. For instance, both of these real-time code can be generated for Real-Time Windows Target (one of the real-time target environments supported by Matlab) and run on two PCs in real-time under Windows. Alternatively, controller code can also be run on rapid prototyping hardware such as xPC in real-time (xPC Target), and the process dynamics simulation can be run in real-time on a Windows PC environment (Real-Time Windows Target). The two computers would have to communicate with each other in real-time, where the simulated controlled process dynamics provides the sensory data and actuator connections to the controller. If the host computer is powerful enough, both codes can be run on one computer in real-time and they communicate with each other on the same computer. 3. Run the controller software at a target hardware (embedded controller or general purpose computer, i.e. xPC Targetbox) in real-time and have it interfaced the the actual hardware of the controlled process, such as a prototype or laboratory setup. This is called real-time rapid prototyping. Before testing the real-time controlled performance on the actual hardware, careful debugging procedure should be followed with safety in mind. For instance, in machine control applications, rst step should be to verify that emergency shut-down process works reliably since things invariably do not work right on the rst trial. Then, input/output interface should be veried for proper operation. Then, actual operational performance should be tested in a planned increments of complexity. Such test and debug proceedure would necessarily be planned for each application. The main benet of Matlab/Simulink environment over the standard high level programming languages such as C/C++ are: 1. faster program development due to reduced detail in dening data structures (i.e. in Matlab we dont have to declare data types before usage) and easy to use library functions (including I/O functions), 2. good graphical communication of the model structure in Simulink as oppose to text based programming language description, 3. auto-code generation tools for real-time implementation. In addition, Matlab/Simulink environment can interface with external user written C functions. However, use of external functions should be balanced with the diculty they impose and maintaining the advantages of Matlab environment.

16

CHAPTER 1. MATLAB AND ITS TOOLS

Cfiles (S functions) -

Cfiles

Matlab
CCompiler
Executable File

Figure 1.1: Matlab, its add-on tools and their typical relationships in an engineering application Matlab is the main foundation software upon which dierent software modules are added. Figure?? shows the relationship between Matlab and its main add-on tools. Simulink is used to model primarily continuous event systems. StateFlow is used to model event-driven systems. In a typical application, StateFlow charts are included in the Simulink model in order to more conveniently dene the event-driven and supervisory logic aspects of the dynamic systems, whereas the Simulink model is used to model the algorithmic aspects of a dynamic system. For rapid prototyping and real-time implementation purposes, the Simulink and StateFlow models can be automatically converted to C-code by the Realtime Workshop (RTW) and StateFlow Coder (SFC) software tools (Fig. ??). RTW and SFC are auto-code generation tools. Real-Time Workshop (RTW) and StateFlow Coder (SFC) are auto-code generation programs that generates C-code from Simulink and Stateow model les, respectively. Before auto-code generation, the parameters of the RTW and SFC can be set to customize code generation for a specic target hardware (i.e. xPC Target, Windows or one of the supported embedded target hardware and softwarte environment). The real-time code generation tools generate code which are target processor specic. Therefore, the RTW and SFC auto-code generation process involves the setting up of various target system specic parameters before they are run on a given model. Matlab is started by double clicking on the Matlab short-cut icon on the desktop under Windows development environment. The standard prompt of Matlab when it starts and opens its user interface window, called the command window, is >> The user interacts with Matlab from the command window. In addition, the window has menu items which will allow the user to perform typical le I/O, print, setup operations, and get help on any Matlab topic. Matlab development environment has seven basic windows. Each window is dockablecan be disconnected from the Matlab window and treated as a separate window. Each window can be opened/closed using the View menu check mark next to each window. The

1.1. MATLAB OVERVIEW

17

Control Algorithm
- Matlab -Simulink Model:~PID Servo control loops - Stateflow Model: ~PLC Supervisory logic - Mode Select, - Sensor Failure RTW / SFC Cfiles VC++
Compiler

DOS DOS App App

xPC + ABL xPC Hardware Hardware

I/O: I/O: Lab/Machine Lab/Machine

Matlab, Simulink, StateFlow, RTW, SFC

Visual C++

ii) Hardware Implementation: Lab & Machine

Figure 1.2: Real-time controller development process using Matlab environment. In this gure, target real-time controller is shown as the xPC hardware platform which is based on DOS and PC-bus. There are many other target real-time controller harware supported by Matlab.

Controller alg. run in real-time Controller algorithm + Process model, off-line (non-real time) simulations.

Controller alg. run in real-time

Process model simulation run in real-time Process hardware, lab setup, proto-type, actual controlled process

Figure 1.3: Controls development phases: Phase 1) O-line development and non-real time simulation. 2)Hardware in the loop real-time simulation, 3) Real-time controller testing with a prototype controlled process hardware.

18

CHAPTER 1. MATLAB AND ITS TOOLS

Matlabs user interface is modied in each version a little bit. The most current version may have a little dierent user interface then described here. However, basic operation of the environment does not change. The main windows are (Fig.??): 1. Command Window:the window through which the user enters Matlab commands interactively.

>> clc ;

Clears the screen of the Command Window.

2. Command History Window: used to store and reuse previously used interactive Matlab commands. It is useful during program debugging. 3. Workspace Window: this window shows all of the variables dened in the Matlab workspace and their values.
>> clear ; >> who >> whos ; ; % Clears (deletes) all data variables defined from the Matlab Workspace. % Displays the currently defined data variables % (without their size info) in the Matlab Workspace. % Displays the currently defined data variables %(with their size info) in the Matlab Workspace.

4. Current Directory Window: directory navigation window. Using the icons on this window, the user can quickly change the current directory. Unless species otherwise, Matlab saves/accesses the les from the Current Working Directory. If it can not nd a le in the Current Working Directory, then it searches the deirectories dened in the Path. 5. Launch Pad Window: to start dierent components of Matlab such as Simulink, StateFlow, etc. 6. Proler: The prole function is used to debug and optimize M-les by tracking their execution time. For each function in the M-le, prole records information about execution time, number of calls, parent functions, child functions, code line hit count, and code line execution time. 7. Help Window: a separate window that allows access to complete on line help on all of the Matlab tools.

1.1. MATLAB OVERVIEW

19

Figure 1.4: Matlab environment and main user interface windows.

20

CHAPTER 1. MATLAB AND ITS TOOLS

1.1.1

Matlab Setup Issues

Before starting to develop programs in Matlab, we should address various setup issues that will be needed or will be convenient in every Matlab session. At the beginning of every Matlab session, the Matlabrc.m le is executed automatically. It is located in the Matlab installation directory, and subdirectory "...\toolbox\local\" Matlabrc.m

If startup.m le exists in the Matlab path directories, Matlabrc.m executes it. Startup.m An example format for startup.m le is given in startupsav.m le. The content of that le can be modied and saved as startup.m le in the same directory to meet the needs of a specic computer installation. At the end of each Matlab session, the following le is executed automatically, if nish.m le exists in any directory included in the Matlab Path variable. Finish.m Therefore, it is a good idea to put our custom setup commands in these les. For instance, if we want to add additional search directories into the Matlab environment so that when we type the name of a le, Matlab searches certain directories in specied order. We should add that command in the startup.m le. Matlab provides default les named Startupsav.m, and Finishsav.m which can be copied into Startup.m and Finish.m, and modied for the desired customization. After installing Matlab, only the Startupsav.m and Finishsav.m les exist. The user then should copy these les to Startup.m and Finish.m les, modify content if needed or leave it alone in their original form. Here is a typical startup.m le content cd c:\matlab-r12\work\myfile load matlab.mat simulink stateflow The above commands change the current working directory in Matlab to

1.1. MATLAB OVERVIEW "c:\matlab-r12\work\myfile"

21

, then loads the matlab.mat le to restore the workspace from the previous session, starts Simulink, then starts Stateow. In general, we can leave the content of the Matlabrc.m, startup.m and nish.m les in their default condition setup by the Matlab installation. If we want to save the current Matlab sessions workspace in a le before exiting the Matlab session, we should add the following command to the Finish.m le, so that the variables in the current Matlab workspace can be loaded in during the next Matlab session. Here is a possible content for nish.m le disp(Saving the Matlab worskpace to file matlab.mat) ; save The save command saves the whole workspace (all of the variables dened in the current Matlab session) to the default lename matlab.mat. Note that the Matlab workspace refers to the memory content allocated for all of the variables dened in the current Matlab session. By saving the workspace, we can recall these variable names and their values during a dierent Matlab session. Using File Set Path menu item, dene a default directory and search path in which the les will be saved or will be rst looked for when we use File Open or File Save menu items. The user can change that at any time in a given Matlab session. The default can be dened and executed automatically at the beginning of each Matlab session if the user denes the default directory using the File Set Path (make changes) Save button to save the setup for future sessions. Matlab is used in one of two modes: 1. Interactive mode: user types the commands in the Command Window and gets results after executing that command. 2. Programming mode: user writes programs in Matlab language and saves them in Mles. The name of the M-le is typed at the command window to run the programs.

1.1.2

Data in Matlab Environment

In Matlab, a data variable is created by giving it a name and assigning a value to that name by placing it on the left handside of an assignment statement. For instance, the following example shows how to create a variable named x and assign a value to it. By default, it has data type of double. >> x = 1.25 ;

22

CHAPTER 1. MATLAB AND ITS TOOLS

Unlike in high level languages such as C and Fortran, we do not need to declare the data type of a variable before it is used. The main data structure in Matlab is a matrix. A scalar is considered as a 1x1 matrix. A vector is considered as a row matrix. Matlab does not require the data type of a variable or matrix be dened. By default, all numerical data is treated as double. The percent sign, %, is used to indicate the beginning of comments. The semi column ; at the end of a line suppresses the echo of the data to the screen. Three dots are used to indicate the command line continues in the next line. The rst 31 characters in a variable name is eective and must be unique in a program. Variable names must start with a character, and are case sensitive, i.e. x and X are dierent variable names. Help on any topic can be obtained by >> >> help help topic

The display accuracy of the numerical data can be controlled by >> >> >> >> >> >> format format format format format format short ; long ; short e ; long e ; bank ; rat ;

% to display in scientific notation % Display two decimals only, i.e. 5.40 % Display in fractional form, i.e. 10/3

Matrix data is dened as follows, >> A = [ 1 4 7 2 5 8 3 6 9

The same matrix, A, can also be dened with the following syntax, >> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] ;

Instead of spaces between matrix elements, comma , can be used, >> A = [ 1,2,3 ; 4,5,6 ; 7,8,9] ;

A specic element of a matrix, (k,l) - row k, column l, is referenced as ,

1.1. MATLAB OVERVIEW >> >> >> x = A(k,l) ; A(k,l) = 5.0

23

A row, or a column or a sub-matrix of a matrix can be referenced (for reading and writing) >> >> >> row_k = A(k, : ) col_l = A(:, l ) B = A(1:k, 10:20) ; ; ;

B is a sub-matrix of A.

Note that Matlab uses variable names i and j for representing 1 imaginary number for complex variable denitions. In order to make sure we do not change the denition of built in variables i and j, we should not use i and j in our programs as data variables, such as index number to vectors and matrices. When clear statement is executed, the original denitions of variables are restored. >> clear >> i ans = 0 + 1.0000i >> j ans = 0 + 1.0000i >> i=2.0 i = 2 >> v= 5 + 10*i v = 25

24 >> i i = 2 >> clear >> i ans = 0 + 1.0000i >>

CHAPTER 1. MATLAB AND ITS TOOLS

A large vector can be assigned as follows using starting value, increment value, and nal value, >> x = 0 : 1 : 100 ; % x=[0 1 2 . . . . . 100];

By default, vectors are row vectors of (1xn). To change a vector into a column vector, simply use the transpose operator, >> x = x ; % Original x is a row vector. % After this statement it is a column vector.

Dening matrices with rows and columns as follows is often needed, as shown below. Notice how we transpose the row vectors into column vectors in the denition of the matrix >> Angle_Degrees = [ 0 Angle_Degrees = 0 90 180 270 360 90 180 270 360]

>> Angle_Radians = (pi/180) * Angle_Degrees Angle_Radians = 0 1.5708 3.1416 4.7124 6.2832

>> Angle_Matrix = [Angle_Degrees , Angle_Radians ] Angle_Matrix =

1.1. MATLAB OVERVIEW

25

0 90.0000 180.0000 270.0000 360.0000 >>

0 1.5708 3.1416 4.7124 6.2832

Default numerical data type in Matlab is double precision oating point data, double in C-language. Data can be dened and converted to integer data type using data conversion functions. Matlab supports 8-bit, 16-bit, 32-bit and 64-bit signed and unsigned integer data types. The data conversion function examples are shown below, k1=int8(-10.3) l1=int16(-1000.4) m1=int32(-1000000.5) n1=int64(-100000000.6) k2=uint8(-10.3) l2=uint16(1000.4) m2=uint32(1000000.5) n2=uint64(-100000000.6) >> k1 l1 m1 n1 k2 l2 m2 n2 >> Character and string (array of characters) are stored also as vectors of ASCII code for each character using single quote to assign to a string variable. For instance myTitle=Plot of Torque versus Speed ;

= = = = = = = =

-10 -1000 -1000001 -100000001 0 1000 1000001 0

26 size(myTitle) >> ans = 1 27

CHAPTER 1. MATLAB AND ITS TOOLS

The character array variable (equivalently called the string variable) myTitle is a vector, where each element of the vector stores the ASCII code of the characters. The size() function counts the number of elements in this variable. The conversion between character representation, ASCII code, and numerical representaitons can be performed as follows,
char(97) % Prints the character corresponding to ASCII code 97: double(a) % ...........ASCII code corresponding to character a S = [1 2 3 4] ; X = str2num(S) S = num2str(X) ; >> ans = a ans = 97 X = 1 3 S = 1 3 2 4 2 4 a

The basic arithmetic operators, +,-,*,/ are dened for scalars as well as vectors and matrices. In C++ terminology, the +, -, *, / operators have been overloaded to handle scalar, vector, and matrix data objects. In Matlab, we can add two matrices like scalars, >> >> A = [ B = [ 1 1 2 ; 2 ; 3 3 4 4 ] ; ] ;

1.1. MATLAB OVERVIEW >> C = A + B ;

27

Element by element algebraic operations are also dened using the following operators: .+, ., ., ./ The following is a standard matrix multiplication operator, >> C = A * B ;

Whereas, the following multiplies the A and B matrices element by element and assigns it to the C matrix >> C = A .* B ; % C(i,j) = A(i,j) * B(i,j)

Matlab automatically denes the following variables, >> >> >> >> >> >> pi eps inf NaN i j

where pi is , eps is a very small number which is 252 2.2204E 16, and inf represents the innity. NaN is used to represent a condition that data is not a number. The maximum and minimum numbers Matlab can represent as integer and oating point can be determined on a given computer as follows. Any mathematical operation that results in a number beyond this range will result in overow (larger than maximum representable number) or underow (smaller than the smallest representable number) errors. >> intmax ans = 2147483647 >> intmin ans = -2147483648

28 >> realmax ans = 1.7977e+308 >> realmin ans = 2.2251e-308 >>

CHAPTER 1. MATLAB AND ITS TOOLS

For complex numbers, the constant i and j are both dened as square root of 1, 1, when used in the context of complex variables. >> >> >> >> >> >> >> >> >> >> >> z = 2+3*i z = x+i*y z = 2+3j z = x+j*y z=complex(2,3) x = real(z) y = imag(z) w = conj(z) ; % equivalent to z = 2 + 3*i ; % Assign real parf of z to x ; % Assign imaginary parf of z to y ; % if z = 2 + 3* i, then w = 2 - 3 * i

Note that i and j are commonly used as loop counters in programming languages such as C and Fortran. In Matlab, if in a program we use i or j for loop counter or for any other purpose on the left hand side of an assignment statement, then we eectively redened the meaning of it, hence can not longer be used as a complex number 1 within the scope of its denition. In other words, if i and j are redened in an m-script le with global visibility, it will eect the rednition of the i and j as complex number globally. However, if i and j are redened in a function as local variable, it will only eect the denition locally within the scope of that function. M-script les, m-function les and variable scopes are discussed later in this chapter. Example: Let us consider a sattelite orbiting around the earth at a constant distance. Given that the gravitational pull of the earth (due to the inertia of the earth) is g = 9.81m/s2 , determine

1.1. MATLAB OVERVIEW

29

the linear speed necessary for the sattelite to travel at dierent orbital heights. Earths radius is rearth = 6357 km. The sattelite would stay at constant orbital height when the gravitational force is equal to the centrifugal force due t othe rotation of the sattelite around the earth,

msattelite g V

=
V2 r

msattelite g ( )1/2 r

V2 r

(1.1) (1.2) (1.3)

g =

Notice that the relationship is independent of the inertia of the sattelite. Our goal is to determine V as function of r , where r is the distance of sattelite from the earths center. Hence, we can dene r as follows,

r = h + rearth h = r rearth

(1.4) (1.5)

where h is the distance of sattelite from the earths surface. The Matlab script le to solve this problem is shown below. % Filename: sattelite_orbit.m format short g = 9.81 ; % [m/s^2] r_earth = 6357* 10^3 ; % [m] for k = 0:100 h(1,k+1) = k * 1000 ; r = r_earth + h(1,k+1) ; V(1,k+1) = (g*r)^0.5 ; % Units [m/sec] w(1,k+1) = V(1,k+1)/r ; % Units [rad/sec] w2(1,k+1) = (w(1,k+1)/(2*pi)) *3600 % [rev/hour] end Result=[ h , V ,w] figure(1) subplot(311) plot(h/1000,V/1000) subplot(312)

; % h in [km] units,

V units in [km/sec]

30

CHAPTER 1. MATLAB AND ITS TOOLS

8 7.95 7.9 7.85 0 x 10


3

20

40

60

80

100

1.25 1.245 1.24 1.235

0 0.715

20

40

60

80

100

0.71

0.705

20

40

60

80

100

Figure 1.5: Example for calculating requried sattelite speed versus altitude. plot(h/1000,w) subplot(313) plot(h/1000,w2) ; % w units in [rad/sec]

; % w2 units in [rev/hour]

1.1.3

Program Flow Control Statements in Matlab

The following logic and ow control statements, coupled with operators ( arithmentic, logical and relational operators), allows us to code logic into our Matlab programs in the form of loops (iterative and conditional loops) and decision blocks, % Loops: for for and while constructs. % Iterative loop: execute the loop 10 times.

i=1:10 ...

1.1. MATLAB OVERVIEW statements ... end % Conditional loop: % Execute the loop while the (condition) is true or non-zero while (condition) ... statements . . . end % % for i= start_value: increment_value : end_value increment_value is 1 by default if omitted

31

The continue and break statements are dened for for and while loops. The continue ; statement skips the rest of the block and continues the next iteration of the loop in for or while loop. The break statement breaks out of the current loop. Decision Blocks: if and switch constructs.

if (expression1) statements1 % execute the first block for which (expressionX) is true % or non-zero . . . elseif (expression2) statements2 . . . elseif (expression3) statements3 . . . % (repeat elseif (exp) as many times as necessary) else statementsN . . . end

switch (switch_expr) case (case_expr ) % Execute the block for which case_expr = switch_expr statements

32

CHAPTER 1. MATLAB AND ITS TOOLS

... case {case_expr1,case_expr2,case_expr3,...} statements ... otherwise statements ... end Example for switch construct, method = Bilinear; switch lower(method) case {linear,bilinear} disp(Method is linear) case cubic disp(Method is cubic) case nearest disp(Method is nearest) otherwise disp(Unknown method.) end The otherwise part is executed only if none of the preceding case expressions match the switch expression. Only the statements between the matching case and the next case, otherwise, or end are executed. Unlike C, the switch statement does not fall through, so break statements are not necessary. The various operators used in Matlab are summarized below. Arithmetic operators A+B A-B A*B A/B A\B A^B A

A.*B A./B A.\B A.^B A.

Relational operators, A A A A < B > B <= B >= B

1.1. MATLAB OVERVIEW A == B A ~= B Logical operators, A & B A | B A && B A || B ~A xor(A,B) ; ; ; ; ; ; AND element-by-element (bit-wise) evaluation OR element-by-element (bit-wise) evaluation AND OR (equal ?) (not equal ?)

33

NOT Exclusive OR, logical 1 (TRUE) where either A or B, but not both, is non-zero.

1.1.4

Functions in Matlab: M-script les and M-function les

There are two dierent ways to call functions in Matlab: 1. run another M-le: script le 2. call another Matlab function in an M-le: function le. To run another M-le, called script le, just include the name of that le in the program M-le. It is equivalent to including the content of that M-le at that location. The data in the M-le is global and accessible in the Matlab workspace as well as the current workspace data is accessible in the script M-le. One M-script le can be include and execute another M-script le, and in turn that le can include yet another M-script le. The nesting can continue as part of the program logic. Script M-le example: Matrix1.m
% Filename: Matrix1.m % Example of an M-script file. % Typing the file name in Matlab command window or another Matlab M-file is % equivalent to running the code in this file as if they were typed explicity at that location. A = [ 1 2 ; 3 B = [ 5 6 ; 7 C = A + B ; Matrix2 ; G = C + F ; 4 ] ; 8 ] ;

Script M-le example: Matrix2.m

34

CHAPTER 1. MATLAB AND ITS TOOLS

% Filename: Matrix2.m % Example of an M-script file. % This file is executed by the "Matrix2" line in the Matrix1.m script file. D = [ 10 20 ; 30 E= [ 50 60 ; 70 F = C + D ; 40 ] ; 80 ] ;

>> Matrix1

% to run the Matrix1.m script file. % Then Matrix1.m script file runs Matrix2.m script file.

Calling another user-written Matlab function follows the typical function call rules in high level programming languages such as C and Fortran: it accepts input arguments in the function call and returns data. The data dened locally in the function is local to the function le. Unlike the script M-les, they are not globally accessible. Likewise, the function can access only the data variables passed through the function call argument list. It can not access the variables in the workspace. Good programming practice suggests that we use M-function les with controlled local data scope, and minimize the use of Mscript les with global data scope that can lead to unintended data over-writes. The syntax of a user-written Matlab function M-le is as follows (lename is the function-name with extension .m), Filename: function name.m
function [Y,Z] = function_name(input_1, input_2) % Input variable to this function from the caller: input_1, input_2, ... % Output variable from this function to the caller: Y, Z % % Local data % % Logic % % I/O Y= 5.0 * input_1 ; Z= 10.0 * input_2 ; % % % % Return (output) variables Y and Z must appear on the left hand side of assignment operator. This is the end of the function.

Matlab Example for M-Function File


% Filename: Example1.m %

1.1. MATLAB OVERVIEW


% x=[0.0:0.1:2*pi]; y = My_Function1(x) ; plot(x,y) ; grid on; % End of file % This will plot the sine function on Figure 1.

35

function z1 = My_Function1(u1) % Input variable to this function from the caller: input_1, input_2, ... % Output variable from this function to the caller: Y, Z % % Local data % % Logic % % I/O z1 = My_Function2(u1) ; % % % % % Lets illustrate that function calls can be nested.

Return (output) z1 must appear on the left hand side of assignment operator. This is the end of the function.

function y1 = My_Function2(x1) % Input variable to this function from the caller: input_1, input_2, ... % Output variable from this function to the caller: Y, Z % % Local data % % Logic % % I/O y1 = sin(x1) ; % % % % Return (output) y1 must appear on the left hand side of assignment operator. This is the end of the function.

Global variables can be dened in Matlab for data variables to be shared across functions without having to pass it in the input - output arguments. However, global data denition violates the encapsulation principle in programming. Therefore, it is not recommended for a good programming practice. However, it it must be used, the global variables are

36

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.6: Output plot of the Matlab M-function le example.

1.1. MATLAB OVERVIEW

37

declared so both in m-script le (i.e the m-script le which holds your main program or in the Command Window of Matlab) and in the function that uses it.

% %

Main script file: filename.m

global gravity gravity = 9.81 ; ....

----------------------------------------function z = myFunction1(time) global gravity ... return

Built-in Functions in Matlab Environment Matlab provides a rich library of buil-in functions to provide convenience to the programmer for data manipluation. It is the simplicty of data handling with this rich set of built-in functions and the simplicity of I/O handling that makes Matlab an attractive computational engineering tool. The following built-in functions are useful in data generation >> A = zeros(5,5) ; % all elements of

A matrix, 5x5, are zero

>>

ones(6,4) ; % all elements of B

matrix, 6x4, are

ones.

>>

eye(n) ; % Returns (creates) an identity matrix: nxn eye(m,n) ;

>>

38 % >> Y = ............... mxn

CHAPTER 1. MATLAB AND ITS TOOLS

eye(size(A)) ; % Return an identity matrix of size of A--> mxn

Matrices can be concatenated to build larger size matrices or elements can be deleted to build smaller matrices,
>> >> >> >> >> >> >> >> B = [ A, A+2 ; A+2, A ] ; column of matrix A

A(:,2)=[] ;

% Delete second

C = B(2:4, 3:6) ; % Assign sub-set of B to C: rows 2,3,4 and colums 3, 4, 5, 6 of % B are assigned to C v=linspace(0,10,6) % Create an array v: start at 0, end at 10, 6 numbers evenly spaced

v = 0 2 4 6 8 10 argument is the number of elements

>> v=logspace(0,3,4) ; % First two arguments are powers of 10, third % in the range, in Logarithmic scale. v = 1 10 100 1000

Various matrix properties are calculated using Matlab library functions, such as determinant, eigenvalues of a matrix, rank of a matrix, inverse of a matrix >> >> >> >> Value Lambda n Ainv = det(A) = eig(A) = rank(A) = inv(A) ; ; ; ; % % % % Determinant of Eigenvalues of Rank of matrix inverse of A: matrix A, matrix A. A A^-1

Some commonly used built-in mathematical funtions in Matlab are as follows:


>> >> >> >> >> >> >> >> >> >> >> y y y y y x y y y y = = = = = = = = = = sqrt(x) ; exp(x) ; abs(x) ; log(x) ; log10(x) ; 5.4 ; round(x) ; fix(x) ; ceil(x) ; floor(x) ; % Square root of x assigned to y % Exponential function % Absolute value of x assigned to y % y = ln(x). Log(x) is logarithmic function with base e. % y = log(x). Log(x) is logarithmic function with base 10.

% % % %

Round Round Round Round

to to to to

nearest integer integer integer

integer: y = 5 towards zero: y = 5 towards infinity : y = 6 towards negative infinity: y = 5

>> y = rem(x,z) ; % Reminder function: y = x - fix(x/z)

1.1. MATLAB OVERVIEW


>> y = sign(x) ; % returns 1 if x>0, 0 if x=0, -1 if x< 0. >> >> >> >> >> % Trigonometric functions % Sin function % Cosine function % Tangent function % Cotangent function

39

y y y y

= = = =

sin(x) cos(x) tan(x) cot(x)

; ; ; ;

>> y = asin(x) ; % Arcsin (inverse Sin) function >> y = sinh(x) ; % Hyperbolic sin function >> y = asinh(x) ; % Inverse hyperbolic Sin function % Similar functions for cos, tan, cot.

Polynomials, their roots, and multiplication of polynomials are handled by the coecients data vector. Let the polynomial be

a0 sn + a1 sn1 + a2 sn2 + .... + an = 0 The roots of the polynominal can be found as follows
>> >> >> c = [ a_0 a_1 a_2 ... a_n] ; % Defines the coefficients of the polynomial r is the vector that has the roots of the polynomial. poly() does the opposite of roots() -- given the roots, it calculates the coefficients of the corresponding polynomial.

(1.6)

r = roots(c); % c = poly(r) ; % %

>>

c3 = conv(c1, c2) ; % multiplies two polynomials, and % returns the coefficients of the resulting polynomial. % (Length of c3) = (length of c1 + length of c2 - 1) y1 = interp1(x,y,x1); % given (x,y) vecor pair, % find interpolated value(s) of y1 at x1 % using linear (default) interpolation. % If x1 is scalar, y1 is scalar. If x1 is vector, so is y1.

>>

1.1.5

Input and Output in Matlab:

Matlab has most of the features of a high level programming language, such as C, plus the additional convenience of easily handling graphical plotting of data, and automatic declaration of data type. Unlike in C, the data type of a variable does not need to declared in advance of its usage. Matlab automatically handles that. In any programming environment, we need to be able to input-output the data to-and-from the program and apply logic to it. Data can be input to a Matlab environment in one of the following ways: 1. From keyboard, using input

40

CHAPTER 1. MATLAB AND ITS TOOLS 2. From an M-le where data is dened following the Matlab syntax (this is the most common form of inputing data in Matlab environment), using the lename in the program or in command window 3. From a previously saved *.mat le, using load. 4. From an Excel spreadsheet data le, lename.xls

>>

n = input (Enter value for n : ) ;

% Inputs numeric data to variable n.

To enter a vector or matrix, use the same notion that we use in m-script le or Command Window, i.e.
>> v = input (Enter value for v: ) ; [ 1 >> [ 2 3] ; % Inputs numeric data for vector v % Inputs numeric data for vector v

matrix1 = input (Enter value for Matrix1: ) ; 1 4 7 2 5 8 3 ; 6 ; 9 ] ;

The entered data are assigned to the variable on the left side of the assignment statement. Formatted input and output can be accomplished using fscanf() and fprintf() functions, respectively, which are similar to the same named functions in C language. Before a le can be accessed for read/write operations, it must be opened with fopen() function. When the read/write operations are completed for the current application, the le should be closed using fclose() function. As a result, there ar typically four functions used for formated le I/O operations, fHandle = fopen(Filename,rt) ; [A,COUNT] = fscanf(fHandle,FORMAT,SIZE) ; fprintf(fHandle,The matrix has %4.0f rows and \t %4.0f columns \r\n, row, col) ; status = fclose(fHandle) ; Let us look at the details of these four main functions for formatted I/O.

1.1. MATLAB OVERVIEW fHandle = fopen(Filename,rt) ; if (fHandle <0) error(Error: File Filename does not exist.); end [A,COUNT] = fscanf(fHandle,FORMAT,SIZE) ; status = fclose(fHandle) ; if (status ~= 0) error(Error: Could not close File Filename.) ; end

41

fHandle=fopen(FILENAME,PERMISSION) ; opens the le FILENAME in the mode specied by PERMISSION. PERMISSION can be: r w a r+ w+ a+ W A read write (create if necessary) append (create if necessary) read and write (do not create) truncate or create for read and write read and append (create if necessary) write without automatic flushing append without automatic flushing

To open a le in text mode, append t to the permission string, for example rt and w+t. fscanf(fHandle, FORMAT, SIZE) reads data from the le specied by le identier fHandle which is obtained from fopen(), converts it according to the specied FORMAT string, and returns it in matrix A. COUNT is an optional output argument that returns the number of elements successfully read. SIZE is optional which denes the maximum number of elements to read. If not specied, all of the le is read. If SIZE is specied, valid entries are: N inf [M,N] read at most N elements into a column vector. read at most to the end of the file. read at most M * N elements filling at least an M-by-N matrix, in column order. N can be inf, but not M.

If the matrix A results from using character conversions only and SIZE is not of the form [M,N] then a row vector is returned.

42

CHAPTER 1. MATLAB AND ITS TOOLS

S = fscanf(fHandle,%s)

reads a character string.

A = fscanf(fHandle,%10d) reads 10-digit decimal integers.

FORMAT is a string containing C language like conversion specications. fclose(fHandle) closes the le identied by the fHandle, and returns zero if successfull, non-zero if not successful.
>> name = input (Enter string data for name , s) ; % enters the string data (specified by s) into variable name >> filename ; % executes the filename.m % all the data defined in the m-file becomes part % of the Matlab workspace and % therefore accessible to the program. >> load filename % loads the variables saved in the filename.mat file % which was saved before. >> load(filename.dat, v) % Loads ASCII data from the file to variable v

>> save % saves all worspace variables to

matlab.mat file in binary format.

>> save filename % save all of the workspace variables in the filename.mat in binary format. >> save filename var1 var2 -ascii -double -tab % saves the selected variables in ascii format in the filename specified. % if no variable name is provided, all of the variables % in workspace is saved.

Data can be displayed in text format on the screen, plotted in graphical form, or saved to a le,
x % % Not terminating a line in m-file (or in command window) ";" displays the numerical result of the current line on the screen including the name of the variables

disp(x) % Displays the value of x without printing the name of the variable disp(Message);

1.1. MATLAB OVERVIEW


% display the text string Message

43

Formatted printing to screen or le can be done using the fprintf() function, which is almost identical to the fprintf() function used in C language. This function uses % symbol to indicate the format, and special characters to dene linefeed, carrier return, tab, and backspace in formatting the output. Format %f %e %g %c %s \r \n \t \b
A = [ 1 4 2 3 ; 5 6 ]

Meaning means decimal format means exponential format means use %f or %e format, whichever is shorter ...... character data format ...... string data format indicates : carriage return indicates: line feed indicates: tab indicates: backspace

[row,col]=size(A) ;

fprintf(The matrix has %4.0f rows and \t %4.0f columns \r\n, row, col) ; % % % the %5d means the data for 5 digit integer format, the %4.0f means the data is in decimal notation, 4 characters long, 0 digits after the decimal point.

myTitle = Result: Force versus Time ; fprintf(%s \n, myTitle) ;

The result is >> The matrix has 2 rows and 3 columns

Result: Force versus Time >>

44

CHAPTER 1. MATLAB AND ITS TOOLS

The n format specier adds carriage-return after printing myTitle on the screen. In the above example, fprintf() statements print on the screen. The fprintf() output can also be directed to a le, as follows, x = 0:.1:1; y = [x ; exp(x)]; fHandle = fopen(exponential.txt,wt); fprintf(fHandle,%6.2f %12.8f\n,y); fclose(fHandle); Data can be input from dierent le formats that Matlab built-in functions supports. Below is a list of typical le formats supported by Matlab built-in functions.
File Format Filename extensions Matlab Built-in Functions ----------------------------------------------------------------------------------------------------Text File *.dat, *.txt, *.may y= load( .. ) save(...., y) fscanf() fprintf() Excel File *.xls y=xlsread(..) xlswrite(..,y) *.jpg, *,jpeg WL=imread(wheel_loader.jpg) ; % to read image(WL); % to display imwrite(WL,MWL.jpg) % to write [Adata,Af]=wavread(myAudio1.wav) ; % to input sound(Adata,Af) ; % to play it wavwrite(Adata,Af, Ares,myAudio2.wav) % to write it getframe() movie()

Image File

*.bmp,

Audio File

*.wav,

*.au

Video File

*.avi

where Af is sampling frequency in [Hz] and Ares is the number of bits per sample (resolution of sound data). In sound le of type *.wav, the magnitude of the data should be between 1.0 anmd 1.0 which represent the amplitude or the volume of the sound. A useful Matlab built-in function for user interface using monitor and keyboard is the menu() function. The menu() function is used to display a window on the screen, provides a number of choices, whichever one is selected by the user, the result is returned to the variable on the assignment statement as an integer, indicating the choice. General format of the menu() function is as follows, choice = menu(menu_header_message, item1 text, item2 text, ... ) and an example of usage is given below.

1.1. MATLAB OVERVIEW choice = menu(Simulation choices:, Case 1, Case 2, Case 3) switch choice case 1 disp(Case 1 is selected); case 2 disp(Case 2 is selected); case 3 disp(Case 3 is selected); end

45

Example: Working with Excel Files Excel is a commonly used spreadsheet program. Data in conveniently saved, processed and communicated using Excel format les among many dierent elds, from engineering and science to accounting eld. Therefore, it is useful to learn how read data from Excel formatted les, and how to write (save) data in Excel formatted les. An Excel le typically has a matrix of data, and also some text information on the top (or spread across the le) to explain the meaning of data to the user. Therefore, the user must know the meaning of the data and interpert it accordingly before using it in Matlab. Matlab can read in the data from an Excel le, but the meaning of the data must be known by the user/programmer. Data from an Excel le can be entered to a Matlab variable by speciying the 1) Excel lename, 2) worksheet name in the le, 3) optionally a specied range of rows and columns in the spreadsheet and assign it to a Matlab variable. The following functions are used with various arguments [NUMERIC,TXT,RAW]= xlsread(FILE, SHEET, RANGE)

reads the data specied in the Excel le, FILE, in the SHEET, from the RANGE specied on the that sheet. The numeric cells in FILE are returned in NUMERIC, the text cells in FILE are returned in TXT, while the raw, unprocessed cell content is returned in RAW.

xlswrite(FILE, DATA, SHEET, RANGE) ;

writes to the Excel FILE, the DATA, into SHEET (if SHEET does not exist, it is created), into the RANGE. The RANGE can be the index of the top left corner of the cell, i.e. D1, where the rst element of the matrix data DATA is written, and the rest of the data lled in from there. If the RANGE is specied as top-left and bottom-right corner, i.e. D1:H10,

46

CHAPTER 1. MATLAB AND ITS TOOLS

then the DATA is written into that eld. If the RANGE is smaller than the size of the DATA, subset of the DATA is written to the eld that ts. If the RANGE is larger than the DATA, the empty elds are lled with N/A. The following reads the specied worksheet, where sheet is either a positive, double scalar value or a quoted string containing the sheet name. Specify range using the syntax C1:D20,where C1 and D20 are two opposing corners that dene the region to be read. For example, C2:G4 represents the 3-by-5 rectangular region between the two corners C2 and G4 on the worksheet. Get data from a specied region in a sheet other than the rst sheet,

y = xlsread(filename, sheetname, range); y = xlsread(c:\matlab\work\mySpreadSheet,Sheet2,a2:j5) ;

Interactive region selection mode, the following opens the le lename in an Excel window, enabling you to interactively select the worksheet to be read and the range of data on that worksheet to import. To import an entire worksheet, rst select the sheet in the Excel window and then click the OK button in the Data Selection Dialog box. To import a certain range of data from the sheet, select the worksheet in the Excel window, drag and drop the mouse over the desired range, and then click OK. myNumericData = xlsread(c:\matlab\work\myspreadsheet,-1); You have to select the active region and the active sheet in the EXCEL window that will come into focus. Click OK in the Data Selection Dialog when you have nished selecting the active region. Writing data output to an Excel le from Matlab is accomplished with xlswrite(MyMatrix.xls, myData2, Sheet1, A1) ; which writes matrix myData2 to an Excel lenamed MyMatrix.xls, starting at the A1 cell in worksheet Sheet1 of the le lename MyMatrix.xls. Let us assume that we have an Excel le with three colums of data, rst column represents the time, second column represent the force, and the third column represent the position. At the very top of the le, in row 1, we have the text information on top of colums 1, 2, 3 as time, force, position, respectively. Our objective is to read the numeric data interactively, plot the results, and modify the data, and then write the modied data by appending it to colums next the existing data on the same worksheet. Plot the data in position versus time and force versus time, then multiply the force data by 2 and position data by 3, save the new data into the same le into columns 5, 6, 7 as time,

1.1. MATLAB OVERVIEW

47

force, position. Before running this program, make sure Excel program does not have the data le myExcelDataFile1.xls open. The host PC should have the Excel program installed in order to run the program properly. % Filename; myExcelFile1.m disp(Reading Excel Data File...) ; myData = xlsread(c:\temp\myExcelDataFile1,-1); disp(Completed reading...); subplot(221) plot(myData(:,1), myData(:,2)) ylabel(Position); xlabel(Time); subplot(222) plot(myData(:,1), myData(:,3)) ylabel(Force); xlabel(Time); myData2(:,2) = 2.0 .* myData(:,2) ; myData2(:,3) = 3.0 .* myData(:,3) ; subplot(223) plot(myData(:,1), myData2(:,2)) ylabel(Position); xlabel(Time); subplot(224) plot(myData(:,1), myData2(:,3)) ylabel(Force); xlabel(Time);

disp(Writing Excel Data File...); xlswrite(c:\temp\myExcelDataFile1.xls, myData2, Sheet1, E2) ; xlswrite(c:\temp\myExcelDataFile1.xls, myData2, Sheet2, A2) ; disp(Competed writing...);

48 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.7: Excel data le I/O example: the content of Sheet1 and Sheet2 of the Excel data le in the begining.

1.1. MATLAB OVERVIEW

Figure 1.8: Excel data le I/O example: the content of Sheet1 and Sheet2 of the Excel data le after writing to it. Figure 1.9: Output plot of the Matlab M-function le example. 49

50

CHAPTER 1. MATLAB AND ITS TOOLS

Example: Sound File using Chirp Signal Let us create a chirp signal in the frequency range of audible spectrum, i.e 10Hz to 20kHz. We will create a sinusoidal signal starting at 20Hz frequency, and increment the frequency in 10Hz increments. This results in 2000 increments in frequency. Let us plan on a 200seconds long sound. Therefore, we have about 0.1sec duration for the sound per frequency. Audio signals typically are sampled at 44100Hz, hence per frequency we will have 4410 samples. First, we will generate the sound data. Then we will play the sound on the speaker of the computer. We will save the data to a le. To exercise le I/O operations fully, we will read the sound data back from the le and play it again. The sound data is

y(t) = A Sin(2t) A t ; ; ;

(1.7) (1.8) (1.9) (1.10)

f requency 10 Hz to 20 kHz range

amplitude (volume) 1 to 1 range, i.e. 0.60 is time f rom 0.0sec to 200sec in 1/44100sec increments

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Filename: mySound1.m % % Chirp sound example: generate sound data % make sound via speakers. % save sound data to a file % read back the sound data from the file % make sound via speakers

% Define the parameters of the sound f_sample = 44100 ; % Sampling rate: t_duration = 200.0 ; % Sound duration in seconds A_sound = 0.6 ; % Volume of the sound signal Ares= 16 ; % Resolution: number of bits

% Generate the sound data: chirp signal. % 10 Hz to 20 kHz, 200 sec long sound signal. mySoundData = 0.0 .* [1:1:t_duration * f_sample] ;

1.1. MATLAB OVERVIEW

51

Figure 1.10: Excel data le I/O example: plot of the data.

52 i_index = 0 ;

CHAPTER 1. MATLAB AND ITS TOOLS

input(Hit any key to start generating the sound data); disp(Generating the sound data. Please wait...) ; for count2=1:2000 omega = 10 * count2 ; for count1=1:4410 i_index = i_index + 1 ; mySoundData(i_index) = A_sound * sin(2*pi*omega*(count1/f_sample)) ; end end

disp(Generating the sound data is complete.); input(Hit any key to play the sound); disp(Playing the sound...); sound(mySoundData, f_sample) ; input(Hit any key to write % play the sound

the sound data to a file: myAudio1.wav); % to write it to a file

wavwrite(mySoundData, f_sample, Ares,myAudio1.wav)

disp(Writing the sound file is complete.); disp(Wait until the current sound ends (for 200 seconds), then) ; input(Hit any key to read back the sound data from the file. ); [mySoundData2,f_sample2,Ares2] = wavread(myAudio1.wav) ; input(Hit any key to play the sound. ); sound(mySoundData2, f_sample2) ; disp(Playing the sound...); disp(It will take about 200 seconds for the sound to stop.) disp(Sound example is completed. ); % to input from the file

% play the sound

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% The ease of plotting in Matlab is one of the most attractive features of it. In plotting data, we need to open a gure window, divide the window into subplot areas if desired,

1.1. MATLAB OVERVIEW

53

dene the title, labels of x and y axes, scales of x and y axes, and for each x-y pair of data we can specify the line type and color. These are illustrated in the following example.
% open a new figure window % 2x3 grid of sub-plot areas in the figure, % current target is number 1 spot Figure(1); Subplot(2,3,1); % add plot title, x and y axis labels, axis scales, grid Title(My X-Y Plot); Xlabel(time(sec)); Ylabel(Position (meters)); Axis([xmin xmax ymin ymax]) ; Grid (on); % plot type: linear in both axes, data vector pairs % (x1, y1), (x2, y2), and plot line specs Plot(x1,y1,-0r, x2,y2,--+b); % line specs defined with the % - line type: % - line symbol: % - line color: ... following data pair definition: solid line -, dashed --, dotted :, dash-dot -. ... circle o , plus + , x-mark x, square s, diamond d ... red r, black k, blue b, green g, yellow y, cyan c, magneta m...

Plotting data in logaritmic scale, such as only x-axis in log scale, only y-axis in log scale or both in log scale is accomplished by the following statements instead of the plot semilogx(x1, y1); semilogy(x1, y1); loglog(x1,y1); % x-axis is in Log scale % y-axis is in Log scale % Both x and y axes are in Log scale

Sometimes it is necessary to generate a frequency data vector that is spaced logaritmically instead of linearly as shown below wlinear = 0.0: 1.0 : 100.0 ; wlog = logspace(-3,3,100); % generate frequencies % in the range of 10^-3 to 10^+3, 100 data points

54

CHAPTER 1. MATLAB AND ITS TOOLS % logaritmically spaced.

Polar plots, that is angle versus magniture ((, r) plots can be plotted using the polar() function, % Filename: polar_plot1.m theta = 0: pi/25 : 2*pi ; y = cos(theta) ; z = 10 - 10*sin(theta) ; figure(1) subplot(2,1,1) polar(theta, y) ; title(Polar plot of Cos function) ; subplot(2,1,2) polar(theta, z) ; title(Polar plot of 10-10 Sin(x) function) ;

Another example of polar plot is given below for the nautilus curve % plot_polar_nautilus.m x=0:10/100:20 ; r = exp(x*cot(80*pi/180)) ; polar(x,r,-r) Likewise, 3-dimensional plots are obtained either as 3-d line plots or 3-d surface plots. 3-d line plots are done by plot3(x,y,z) ; where x, y, and z all have the same number of elements and z value plotted for each x,y pair (Fig. ??). >> >> >> >> >> >> >> x = [1 2 3 4 ]; y = [1 2 3 4] ; z = [0 2 10 50] ; plot3(x,y, z) ; grid on

1.1. MATLAB OVERVIEW

55

Polar plot of Cos(x) function 90 1 120 60 150 0.5 30

180

210 240 270 300

330

Polar plot of 1010 Sin(x) function 90 20 120 60 150 10 30

180

210 240 270 300

330

Figure 1.11: Polar plot examples: Cos(x) function and 10 - 10 Sin(x) function.

56

CHAPTER 1. MATLAB AND ITS TOOLS

90 120

40 60 30

150

20

30

10

180

210

330

240 270

300

Figure 1.12: Polar plot example: Nautilus curve.

1.1. MATLAB OVERVIEW 3-d surface plots are done by mesh(x1,y1,z1) surf(x1,y1,z1) contour(x1,y1,z1) surfc(x1,y1,z1) ; ; ; ; % % % % 3-d plots 3-d plots Generates 3-d plots with lines with surface a contour plot with surface and contour combined

57

where x1, y1 are 2-d matrices dening the x-y grids coordinates. These data are typically created from row vectors x and y using [x1, y1]= meshgrid(x,y) function. The x1 vector is rows of the x vector, and y1 vector is the columns of the y vector. For example, to evaluate 2 2 the function x e(x y ) over the range 1 < x < 1, 1 < y < 1,
clc ; clf ; [X,Y] = meshgrid(-1:.1:1, -1:.1:1) Z = X .* exp(-X.^2 - Y.^2) surf(X,Y,Z) >> X = -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -0.5000 -0.5000 -0.5000 -0.5000 -0.5000 0 0 0 0 0 0.5000 0.5000 0.5000 0.5000 0.5000 1.0000 1.0000 1.0000 1.0000 1.0000

Y = -1.0000 -0.5000 0 0.5000 1.0000 -1.0000 -0.5000 0 0.5000 1.0000 -1.0000 -0.5000 0 0.5000 1.0000 -1.0000 -0.5000 0 0.5000 1.0000 -1.0000 -0.5000 0 0.5000 1.0000

Z = -0.1353 -0.2865 -0.3679 -0.2865 -0.1353 -0.1433 -0.3033 -0.3894 -0.3033 -0.1433 0 0 0 0 0 0.1433 0.3033 0.3894 0.3033 0.1433 0.1353 0.2865 0.3679 0.2865 0.1353

Another interesting example of a three dimensional curve (line) is the tornado shape, as shown below (Fig.??).

58 % Filename: plot_tornado.m x = 0 : pi/100 : 30*pi ; y = x .* sin(x) ; z = x .* cos(x) ;

CHAPTER 1. MATLAB AND ITS TOOLS

figure(1) ; plot3(y,z,x) ; title(Tornado plot); axis square ; grid on ; view(135,145); % Adjusts the viewing angle. The following is an example of four dierent three dimensional surface plots (Fig.??). x = [-2.0: 0.1 : 2.0]; y = [-2.0: 0.1 : 2.0]; [x1,y1] = meshgrid(x,y) ; z1= x1 .* exp(-x1.^2 y1.^2) ;

figure(1) subplot(2,2,1) mesh(x1,y1,z1) subplot(2,2,2) surf(x1,y1,z1) subplot(2,2,3) contour(x1,y1,z1) subplot(2,2,4) surfc(x1,y1,z1) Viewing angle of each 3-d plot can be changed using the interactive tool on the plot window using the mouse or can be programmed using view() function, az_angle = 45 ; el_angle = 45 ; view(azimuth_angle, elevation_angle) ; Plots can be printed from the File > Print menu of the plot window. In addition, in Windows environment, the screeen can also be captured using PrtScr key on the keyboard, which copies the content of the screen to memory. Then the content can be copied to a le using Microsoft Paint or similar program. The le can be saved in bit mapped format.

1.1. MATLAB OVERVIEW

59

60

CHAPTER 1. MATLAB AND ITS TOOLS

Tornado plot 100 100 50 0 50 100 50 0 50 100 100

80

60

40

20

Figure 1.14: 3-D curve plot example: tornado plot.

1.1. MATLAB OVERVIEW

61

0.5

0.5

0.5 2 0 2 2 0

0.5 2 0 2 2 0

2 0.5 1 0 1 2 2 0

0.5 2 0 1 0 1 2 2 2 0

Figure 1.15: 3-d surface plot examples: using mesh, surf, contour and surfc functions.

62

CHAPTER 1. MATLAB AND ITS TOOLS

Animation can be done by storing images into an array of frames, and displaying these frames in sequence using getframe and movie functions. for j=1:60 plot(.....); F(j) = getframe; end movie(F,10) ; % play the frames stored in F 10 times. % Once the movie frames are save to a matrix, i.e. F, % the animation can be replayed anytime.

Here is an example of animation by rst calculating and saving each frame, then playing them as an animation.
% Animation example clear clc clf x= 0 : pi/50 : 2*pi ; y = x ; [X,Y]=meshgrid(x,y); z=20*sin(X)+cos(Y); h=surf(z) ; axis tight ; % sets the axis limits to the range of the data. set(gca, nextplot,replacechildren); % gca is the current axis handle % next plot replaces the previous plot, without rescaling the axis. shading interp ; % color shading uses interpolation method based on the value of the plotted data colormap(jet) ; % Color map (number range versus color spectrum): jet = blue -- green -- yellow- red range. m=1 ; for k=0 : pi/50: 2*pi z = (sin(X)+cos(Y)).*10*sin(k) ; set(h,Zdata,z); M(m)=getframe; % create and save each frame m=m+1 ; end disp(Hit enter to start animation) ; pause; movie(M,3) ; % play the movie 3 times.

Other related Matlab functions are: axis, bar, grid, hold on, legend, line, LineSpec, loglog, plotyy, plot3, semilogx, semilogy, xlabel, xlim, ylabel, ylim, zlabel, zlim, stem, set.

1.1. MATLAB OVERVIEW

63

Figure 1.16: 3D movie animation using getframe() and movie() functions.

64

CHAPTER 1. MATLAB AND ITS TOOLS

1.1.6

Matlab Toolboxes:

The power of Matlab comes from its extensibility through libraries grouped into dierent functional categories. For instance all of the control system design functions are grouped into Control Systems Toolbox. Similarly, all of the signal processing related functions are grouped into Signal Processing Toolbox. There are many such toolboxes and new toolboxes are being added continuously for dierent application elds. A typical control engineer needs the Signal Processing Toolbox and Control Systems Toolbox. There are also toolboxes that provide functions specically for system identication, neural networks, fuzzy logic, power electronics, statistics, etc.

1.1.7

Controller Design Functions: Transform Domain and State Space Methods

A transfer function is dened with numerator and denominator coecients. A transfer function description can be converted between three dierent way of expressing it: 1) numerator and denominator polynomials form 2) poles-zeros and gain form, 3) partial fraction expansion form (poles, residues, and DC gain).

NUM(s) H(s) = -------DEN(s)

H(s) =

(s-z1)(s-z2)...(s-zn) K --------------------(s-p1)(s-p2)...(s-pn)

NUM(s) ---- = DEN(s)

R(1) R(2) R(n) -------- + -------- + ... + -------- + K(s) s - P(1) s - P(2) s - P(n)

These functions are applied in s-domain as well as z-domain transfer functions.


numG = [ 1 ] ; denG = [ 1 2 4] ; % Numerator coeficients % of the transfer function. % Denominator ...... % ........................... % Gs defines the transfer funtion. % convert to zero-pole-gain form

Gs = tf(numG,denG) ; [z,p,k] = tf2zp(numG, denG);

1.1. MATLAB OVERVIEW


% from the polynomial num(s)/den(s) form [numG, denG] = zp2tf(z,p,k); [r,p,k] = residue(numG, denG) ; % do the reverse % convert from num(s)/den(s) form % to Partial Fraction Expansion form % convert from partial fraction expansion form % to numerator and denominator polynomial form % Given G(s), get poles, % .......... get zeros and gain % obtain the num(s)/den(s) form

65

[num, den] = residue(r,p,k) ;

p = pole(Gs) ; [z, k] = zero(Gs) ; [num,den]=zp2tf(z,p,k) ;

s = TF(s) ; %

specifies the transfer function H(s) = s (Laplace variable). specifies H(z) = z with sample time TS.

z = TF(z,TS) ; %

You can then specify transfer functions directly as rational expressions in s or z, e.g., s G z H = = = = tf(s); (s+1)/(s^2+3*s+1) ; tf(z); (z+1)/(z^2+4*z +2) ;

Similar functions are available to convert between dierent forms of transfer function and state space representations as follows. [numG, denG] = ss2tf(A, B, C, D); [A,B,C,D] = tf2ss(numG, denG); [z, p, k] = ss2zp(A, B, C, D); [A, B, C, D] = zp2ss (z,p,k) ;

sys = ss(A,B,C,D) ; % creates a SS object SYS representing % the continuous-time state-space model p = eig(A) ; z = tzeros(sys) ; % Eigenvalues of A. % Transmission zeros of the corresponding % transfer function between input and output.

dx/dt = Ax(t) + Bu(t) y(t) = Cx(t) + Du(t)

66

CHAPTER 1. MATLAB AND ITS TOOLS

You can set D=0 to mean the zero matrix of appropriate dimensions. sys = ss(A,B,C,D,Ts) ; % creates a discrete-time state-space model with % sample time Ts (set Ts=-1 % if the sample time is undetermined).

Finding discrete equivalent of continuous system transfer functions using various approximation methods can be done as follows in transform and state space form sysD= c2d(sys, 0.01, tustin) ; % given sys for continuous system, % sampling period = 0.01, use Tustin method % to obtain sysD for discrete system equivalent. Gs = tf(num,den); Gz = c2d(Gs, T,zoh) ; % Define a G(s) % Obtain ZOH equivalent of it in z-domain G(z) for % sampling period T.

zgrid ;

% draws the constant damping ratio and constant natural frequency % contours on z-plane

zgrid([],[]) ; % draws the |z|=1 unit circle.

Series, parallel and feedback connection of transfer function can be combined using the following functions to nd the corresponding equivalent transfer functions,

sys3 = series(sys1, sys2);

% % % sys6 = parallel(sys4, sys5) ; % % % sysT = feedback(sysG, sysH); % % % % % % %

sys1 and sys2 are in series: effectively multiply the transfer functions sys3(s) = sys1(s) * sys2(s) sys4 and sys5 are in paralle: effectively adding the ................. sys6(s) = sys4(s) + sys5(s) sysG is in the main transfer function, sysH is in the feedback loop. sysT = sysG /(1+ sysG . sysH). Negative feedback is assumed. Use: feedback(sysG, sysH, +1) for positive feedback to obtain sysT = sysG / (1 - sysG . sysH).

Root locus related functions are illustrated with an example below.

1.1. MATLAB OVERVIEW

67

num = [1] ; den = [ 1 5 2 6] ; sys = tf(num, den); K = 0.0 : 0.1 : 100 ; rlocus(sys,K) ; % plot root locus for standard closed loop case, % for the given range of K values. k = rlocfind(sys) ; % interactively finds the gain % at the selected location on the root locus. % RLOCFIND puts up a crosshair cursor in the graphics window % which is used to select a pole location on an existing root locus. % The root locus gain associated with this point is returned in K % and all the system poles for this gain are returned in POLES. Frequency response related functions are illustrated in the example below. num = [1] ; den = [ 1 5 2 6] ; sys = tf(num, den); [mag, phase, w] = bode(sys) ; % Get Bode plot data loglog(w, mag); % plot magnitude plot semilogx(w, phase); % plot phase plot nyquist(sys) ; % Plot Nyquist (polar) plot

[GM, PM, wgm, wpm] = margin(G) ; % Obtain Gain Margin, Phase margin % and the freqencies at those locations. Given the A, B, C matrices of state space representation, controllability and obervability matrices can be obtained as follows, Wc = ctrb(A,B); Wo = obsv(A,C); % Calcualate controllability matrix % ........... observability........

nc = rank(Wc) ; % Get the rank of controllability matrix value1 = det(Wc) ; % ....... determinant of .............. no = rank(Wo) ; % value2 = det(Wo) ; Same for observability matrices.

Given the A, B, C, D matrices of state space representation, and desired pole locations for closed loop system pc , the state feedback gain can be calculated by

68

CHAPTER 1. MATLAB AND ITS TOOLS

K = acker(A, B, p_c) ; K = place(A, B, p_c) ; For the observer design, given the observer poles, pe , L = (acker(A, C, p_e)) ; L = (place(A, C, p_e)) ;

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB

69

1.2
1.2.1

Simulation of Dynamic Systems Using Matlab


Linearization: Linearization of Nonlinear Functions

We study the linearizarion in increasing order of complexity. First, we study the linearization of nonlinear functions, then that of rst order nonlinear dierential equations, and naly that of a set of rst order nonlinear dierential equations. Consider the function y = ax or y = ax + b which are both linear in x (Fig.??). If the linear function does not pass through the origin, it may be convenient to dene a new variable so that the input-output relationship of the static function passes through the origin,

y = y b = ax

(1.11) (1.12)

If the function between independent variable and dependent variable (or input and output) is nonlinear,

y = y(x)

(1.13)

it can be approximated by a linear function about a nominal point, (xo, yo ). This approximation is accomplished by expanding the function to its Taylor series about the nominal point, and neglecting the second order and higher order terms. Let us dene the total values of the independent and dependent variables as nominal values plus the small variations about that point,

x = xo + x y(x) = y(xo ) + y(x0 + x) The Taylor series expansion of y(x) about the nominal point (xo, yo ) is, d2 y(x) (x xo )2 dy(x) |xo (x xo ) + | xo +... dx dx2 2!

(1.14) (1.15)

y(x) = y(xo ) +

(1.16)

If we neglect the second and higher order terms, assuming that the approximation will be used in the close vicinity of the nominal point, (x0 , y0 ),

y(x) = y(xo) + y (xo )(x xo )

(1.17)

70

CHAPTER 1. MATLAB AND ITS TOOLS

The small variations around the (xo, yo ) nominal point has the following relation

y(x) y(xo ) = y (xo )(x xo ) y(x) = m x

(1.18) (1.19)

where m = y (xo ). Clearly, the closer the actual evaluation point to the nominal point, the more accurate the approximation is. As the evaluation point gets further away from the nominal point, the approximation gets poorer (Fig.??). We can apply the same idea to the linerization of nonlinear dierential equations. Every nonlinear function in the o.d.e. can be approximated by its rst order Taylor series expansion about the nominal point. Notice that linearizing a nonlinear algebraic function about a nominal operating condition involves taking the rst derivative of the nonlinear function and evaluating it at the nominal values of the independent variable. For multi variable nonlinear functions, the same operation would be performed using the rst order partial derivatives of the nonlinear function with respect to each individual independent variable. Let y = f (x) be a nonlinear albegraic function of single variable x, and z = h(x1 , x2 , x3 ) be a nonlinear algebraic multi variable function of variables x1 , x2 , x3 . Let us consdier the linearized approximation of these functions about the nominal conditions of x0 , (x10, x20 , x30),

y =

df (x) |x x dx 0

(1.20)

which is a linearized approximation to the original equation y = f (x) about the nominal operating point (x0 , y0 ).

y =

h(x1 , x2 , x3 ) |(x10,x20 ,x30 ) x1 x1 h(x1 , x2 , x3 ) + |(x10 ,x20 ,x30 ) x2 x2 h(x1 , x2 , x3 ) + |(x10 ,x20 ,x30 ) x3 x3

(1.21) (1.22) (1.23)

which is a linearized approximation to the original equation z = h(x1 , x2 , x3 ) about the nominal operating point (x10 , x20 , x30), z0 = h(x10 , x20 , x30).

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB Example

71

Let us study the linearization of a set of nonlinear dierential equations by an example. The key idea is that the system is operating about a nominal condition (a state or a time varying trajectory), and the variations about that nominal condition are small such that the second and higher order terms are negligable when all the nonlinearities are approximated by a Taylor series expansion about the nominal condition. Consider the dynamic model of a pendulum (Fig.??),

ml 2 + mglsin = 0 g + ( )sin = 0 l

(1.24) (1.25)

The dierential equation is nonlinear due to the presence of the nonlinear function sin() of the dependent variable . Let us consider the linearization of the nonlinear dynamic model of the pendulum about a nominal angle at rest. It is assumed that 1) the angular motion of the pendulum is small and it stays in the neigborhood of the nominal angular position, 2) position, speed, and acceleration changes are so small that the second order terms are negligable.

= 0 + = 0 + = 0 + sin = sin(0 + )|0 = sin0 + (cos0 ) Let us consider the nominal angular position 0 = 0 and , 0 = 0 , 0 = 0

(1.26) (1.27) (1.28) (1.29) (1.30)

sin|0 =0 = 0 , cos|0 =0 = 1 Finally, the linearized dynamic model is

(1.31)

g + ( ) = 0 l

(1.32)

Note that the linearization of cos and sin about the nominal angle 0 for small variations of angle around that nominal value,

72

CHAPTER 1. MATLAB AND ITS TOOLS

cos = cos0 + (sin0 ) + ... cos = 1 ; when 0 = 0 sin = sin(0 + )|0 = sin0 + (cos0 ) = ; when 0 = 0

(1.33) (1.34) (1.35) (1.36) (1.37)

1.2.2

Linearization of Nonlinear First Order Dierential Equations

Consider the following generic form of a nonlinear rst order o.d.e,

x = f (x, u)

(1.38)

We want to linearize about a nominal condition of state and inputs. If the state and input nominal conditions dene a constant state, we call this linearization about a nominal state. If the nominal state and input is function of time, we call this linearization about a nominal trajectory. Clearly, linerization about a nominal state is a special case of linearization about a nominal trajectory. (i) If the nominal state and its derivative is specied (x0 (t), x0 (t)), we can determine the necessary nominal input, u0 (t) x0 (t), x0 (t) specied ; x0 (t) = f (x0 (t), u0 (t)) , solve for u0 (t).

(ii) If the nominal state and nominal input is specied x0 (t), u0 (t), then we can calculate the corresponding nominal rst derivative of the state, x0 (t) = f (x0 (t), u0 (t)), solve for x0 (t). Either way, the nominal state and nominal input condition (x0 (t), u0 (t), x0 (t)) satises the nonlinear dynamic model. Otherwise, it could not be called a nominal state at which this particular dynamic system can be. Let us dene the total state and input values as nominal values plus the small variations about the nominal state,

x = x0 + x u = u0 + u

x = x0 + x

(1.39) (1.40)

The O.D.E. can be linearized about a nominal operating point or nominal trajectory by substitution of the above relations and expanding the nonlinear function to its Taylor series up to the rst order terms,

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB

73

x(t) = f (x, u) f f xo (t) + x(t) = f (xo (t), uo(t)) + |[xo (t),uo (t)]x + | u x u [xo(t),uo (t)] Since the nominal values would cancel out each other,

(1.41) (1.42)

x(t) =

f f |[xo (t),uo(t)]x + | u x u [xo(t),uo (t)] = a(t)x(t) + b(t)u(t)

(1.43) (1.44)

It must be emphasized that this linearized equation is an appriximation to the original nonlinear equation. It is accurate only within the close vicinity of the nominal conditions. As the operating conditions gets further away from the nominal conditions, the approximation gets poorer. The same idea can be directly extended to the vector case which represents multi dimensional dynamic systems.

1.2.3

Linearization of Multi-Dimensional Nonlinear Diential Equations

Consider the following n-set of rst order nonlinear dierential equation (note that any nth order dierential equation can be re-expressed as an n set of rst order dierential equation),

x = f (x, u) x u f
T T T

(1.45) (1.46) (1.47) (1.48)

= [x1 , x2 , ...., xn] = [u1 , u2 , ...., um] = [f1 , ...., fn] f f |x ,u x + |x ,u u + .... x 0 0 u 0 0

x + x = f (x0 , u0 ) +

x =

f f |x0 ,u0 x + |x ,u u x u 0 0 x = [A]x + [B]u

(1.49) (1.50)

where the elements of matrices are given by

74

CHAPTER 1. MATLAB AND ITS TOOLS

[Aij ] = [Bij ] =

fi |x ,u xj 0 0 fi |x ,u uj 0 0

(1.51) (1.52)

Linearization is valid for operating conditions for which neglecting second and higher order terms are valid and accurate enough. Notice that if the nominal condition is an equilibrium point, which means (xo , uo ) are constant, the A and B matrices are constant. Dynamic systems represented linear matrix dierential equations where matrices A and B are constant, are called linear time invariant (LTI) linear systems. If the nominal conditions dene a nominal trajectory in time, not an equilibrium condition, then (xo , (t), uo(t)) are functions of time, hence the A and B matrices will be function of time, A(t) and B(t). Such systems are called linear time varying (LTV) type.
% % % % linear0.m Numerical linearizarion example using Matlab.

x0 = [ pi/2 0.0 ] ; u0 = [ 0.0 ] ; [A,B] = linear1(pendulum, x0, u0) ; % % function [A,B] = linear1(Fname, x0, u0) % % Given: nonlinear function f(x,u) % nominal condition x0, u0 % % Calculate linearized equation matrices A, B % n = size(x0) ; m = size(u0) ; delta = 0.0001 ; x = x0 ; u = u0 ; for j=1:n x(j) = x(j) + delta; A(:,j) = (feval(Fname,x,u)-feval(Fname,x0,u0))/delta ; x(j) = x(j) - delta ; end

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB

75

for j=1:m u(j) = u(j) + delta; B(:,j) = (feval(Fname,x,u)-feval(Fname,x0,u0))/delta ; u(j) = u(j) - delta ; end % % function xdot=pendulum(x,u) % % Pendulum dynamic model: nonlinear model. % g = 9.81 ; l = 1.0 ; xdot = [ x(2) - (g/l)*sin(x(1)) + u] ;

Matlab Functions to Simulate Linear Dynamic Systems Matlab has three convenient functions to simulate linear dynamic systems. They are 1. impulse(sys,t) 2. step(sys,t) 3. lsim(sys,u,t) in vector u function for impulse response of the system for a given time duration, function for unit magnitude step function response function to simulate the response to an arbitrary input function dened

The example Matlab script le below illustrates their use. Note that these functions are useable only for dynamic systems dened by linear, constant coecient dierential equations. Figure ?? shows the results of the simulation.

% Simulating Linear Systems response using Matlab Functions % impulse() and step() and lsim() % Linear system definition: wn=2*pi*1.0; psi=0.5; num=[wn^2]; den=[1 2*psi*wn wn^2]; sys1=tf(num,den);

76 % Impulse response t=[0:0.01:4.0]; figure(1); impulse(sys1,t); % Step response t=[0:0.01:4.0]; figure(2); step(sys1,t) % Response to a general input t=[0:0.01:4.0]; u= 1.0 * sin(2*pi*t); figure(3); lsim(sys1,u,t) ;

CHAPTER 1. MATLAB AND ITS TOOLS

1.2.4

Numerical Solution of ODEs and Simulation of Dynamic Systems

Analytical solution methods are available for only linear, constant coecient dierential equations (i.e. variation of parameters, Laplace transforms). Only a few special cases of rst or second order nonlinear dierential equations can be solved by analytical methods. For all practical purposes, the only viable engineering solution method for nonlinear dierential equations is the numerical methods. The behavior of a dynamic system in time can be predicted by the solution of its mathematical model which typically is a set of ordinary dierential equation. Analytical solution of O.D.E.s are available for only linear O.D.E.s and very simple nonlinear O.D.E.s. Therefore, time domain response of any dynamic system model with reasonable complexity must be solved using numerical methods. The primary tool is the numerical integration of O.D.E.s in time. Numerical integration is performed by discretizing O.D.E.s using various approximations to dierentiation (i.e. Eulers approximation, trapezoidal approximation, Runga-Kutta approximation). First we will study various numerical integration methods for a general nonlinear O.D.E. set of the form,

x = f (x, u, t) x(t0 ) = x0 , u(t) given

(1.53) (1.54)

Then we will study the time domain simulation of a dynamic system that involves a digital controller in the determination of u(t).

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB

77

Figure 1.17: Simulation results of a second order system for impulse, step and a user-dened input function using the Matlab functions impulse, step and lsim.

78

CHAPTER 1. MATLAB AND ITS TOOLS

1.2.5

Numerical Methods for Solving O.D.Es

The problem is that given a nonlinear set of rst order O.D.E.s, with a specied initial condition and input, nd the solution of the O.D.E. system.

x = f (x, u; t) x(t0 ) = x0 , u(t) initial condition is given.

(1.55) (1.56) (1.57)

Numerical integration provides an approximate solution method for the dierential equations. Although the solution is approximate, the error in the approximation can be controlled to the point of being negligable. The essential approximation is that the derivatives of the dependent variables are approximated by nite dierences. Here we will consider various nite dierence approximations. Eulers Method The Eulers approximation is the simplest among others. In the following discussion, we drop the underline symbol from the x, f and u variables for simplicity in notation. The variables x, f, u are still considered to be vector quantities. The derivative of the dependent variable at a given time is approximated by the dierence between the values of the dependent variable at two consecutive samples divided by the sampling interval (Fig. ??). dx x(t + t) x(t) lim + dt t t0 x(t + t) = x(t) + xt x = x(t + t) = x(t) + f (x, u; t)t

(1.58) (1.59) (1.60)

where t is the sampling interval. We can use this approach to solve any nonlinear O.D.E.(although it may not be the most ecient nor accurate method) as follows: starting with initial condition we know x(t0 ), u(t), then we can evaluate f (x0 , u; t0), and calculate x(t0 + t) as

x(t0 + t) = x(t0 ) + f (x0 , u0 , t0 )t Similarly, using the new found values of x(t0 + t), we can nd the x(t0 + 2t) as

(1.61)

x(t0 + 2t) = x(t0 + t) + f (x, u, t)t

(1.62)

where f (x, u, t) is evaluated for those values at (t0 + t). This iteration can be continued until the desired solution time period is covered.

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB Runga-Kutta Method: 4th Order

79

Runga-Kuttas fourth order numerical integration method may be the best compromize between the complexity and accuracy. The dierence compared to Eulers method is that it uses a more accurate approximation for the dierentiation. If the sampling period is taken very small, the dierence between the two method would be insignicant in terms of accuracy. Given the same o.d.e solution problem, Runga-Kuttas fourth order approximation to the solution is given by (Fig.??). 1 x(ti + t) = x(ti ) + (k1 + 2k2 + 2k3 + k4 ) 6 where k1 = t f (ti ; x(ti), u(ti)) 1 t t ; x(ti ) + k1 , u(ti + )) k2 = t f (ti + 2 2 2 t 1 t k3 = t f (ti + ; x(ti ) + k2 , u(ti + )) 2 2 2 k4 = t f (ti + t; x(ti ) + k3 , u(ti + t)) Matlab Function ode45() for ODE Solution Matlab provides numerical integration funtions to solve dierential equations. We provide our own numerical integration algorithm here for the purpose of showing all the details involved in simulating a dynamic system. Matlab provided functions for the same purpose are [t, [t, [t, [t, [t, [t, [t, x]= x]= x]= x]= x]= x]= x]= ode45(ODE_FunctionName, t_vector, x_initial) ode23(ODE_FunctionName, t_vector, x_initial) ode113(ODE_FunctionName, t_vector, x_initial) ode15s(ODE_FunctionName, t_vector, x_initial) ; % ode23s(ODE_FunctionName, t_vector, x_initial) ode23t(ODE_FunctionName, t_vector, x_initial) ode23tb(ODE_FunctionName, t_vector, x_initial) (1.64) (1.65) (1.66) (1.67) (1.63)

for stiff problems

where ODE FunctionName is the name of the m-function le that has the dierential equations that describes the dynamics of the system, tvector can be either [to , tf ] begining and ending time interval of the simulation and the algorithm decides on the number of intermediate solution points or it can be a vector of time points at which solution is obtained and returned at the [t, x] output vector, xinitial is the initial conditions for states at the beginning time t0 . The dierence between dierent functions are about their eciency and suitablity in dealing with sti numerical problems. A sti numerical problem is one that has low frequency and very high frequency (sudden changes in the dynamics, i.e. impact problems) content in the solution.

80

CHAPTER 1. MATLAB AND ITS TOOLS

1.2.6

Time Domain Simulation of Dynamic Systems

Let us plan writing Matlab code to model and simulate this system. We need to write Matlab functions for the following: 1. A main program that denes the simulated time period and simulated conditions: Sim1.m 2. Controlled Process Dynamics (process dynamics) that express the mass-force equations and the actuator dynamics in Matlab syntax with input being the control signal, and initial conditions, and output being the calculated acceleration: Process Dynamics.m 3. Controller that expresses the PD control algorithm: Controller.m 4. A function that will dene the desired position signal xd (t), i.e. Command Signal.m 5. A numerical integration algorithm to solve the dierential equations: Euler.m We will consider the program structure for digital computer simulation of dynamic systems which has a) analog controller, b) digital controller with a given control sampling period. a) Dynamic system with analog controller (Fig.??): The signals in such a system are all continuous in time and no sampling is involved in reality. The numerical simulation will work on the samples of the signals in the system. For accuracy both the controller and process signals should be sampled at the same rate. Some numerical o.d.e. solution algorithms have automatic step size control in order to assure local error in each integration step be smaller than a given value. In such a case, in order to assure that the controller signals are sampled at the same rate as the process, thus simulate an analog control, the controller function should be called from the process dynamics. Hence, every time integration routine calls the process dynamic model, the controller routine will also be called. If we simulate a continuous time process model and an analog (non-sampled) controller, then the controller algorithm should be called at the same sampling rate as the process dynamics. b) Dynamic system with digital controller (Fig.??): In this case there are two sampling periods - one is decided upon by the numerical integration accuracy requirements for the purpose of accurate simulation of an actually continuous time process (Tint), the other is the sampling period of the digital controller which will physically exist in real-time implementation, Tcontrol . Almost all digital controllers are interfaced to a zero-order-hold (Z.O.H.) type D/A converter. Hence, between each sampling period, control action stays constant. In order to simulate the real world behavior accurately, the controller function should be called to get an updated control signal only every, Tcontrol , time period. The control signal value should be kept constant between the sampling instants to simulate a zero-order-hold D/A converter behavior. During that time period, the process dynamics may be called one or more time depending on the numerical accuracy requirements. Generally the integration step is integer multiples smaller than the control sampling period,

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB

81

{ Tcontrol = n Tint ; n = 1, 2, ...}. If we simulate a digital controller that is updated at a certain sampling rate, then we need to make calls to the controller at that time period frequency, whereas calls to the process dynamics may need to be made at smaller time increments in order to assure accuracy. In our simple numerical integration algorithm, numerical integration is done using xed step size. So, calling the controller from main function and then calling the numerical integration algorithm at the same rate is ne. However, if the numerical integration algorithm automatically adjusts the integration step for error control, then the controller should be called by a call from inside the process dynamics function to assure the best accuracy in the simulation (see Cetinkunt 2007). Simulation program: Initialize modules If simulating a digital controller: run control sample loop every Tcontrol period call controller and get u Simulation loop: Tint call o.d.e. solver next

next (if simulating digital controller) Controller desired response (command signal) sensor dynamics: y = g(x) calculate u = ..... O.D.E. solver in : t, x, u, t = h, process dynamics If simulating analog controller, call analog controller function here. call process dynamics, get x out : x(t + t) Process dynamics: x = f (x, u; t)

The structure of the simulation program is given below in more details. Initialize system parameters

82

CHAPTER 1. MATLAB AND ITS TOOLS t0 , tf - initial & nal simulation time x0 - initial states tsample , tint - control loop update time (sampling time period), integration step size Initialize controller controller parameters - i.e. gains, nonlinear compensation functions controller initial condition - i.e. observer initial states. Loop for each control sampling period (assuming digital controller implementation) begin simulation loop: t0 , t0 + tsampling , ...., tf control calculations: u begin loop to simulate dynamic system during the control sampling period: o.d.e. solver loop end

loop end loop end output results Simulation of a Dynamic System Using Matlab: Mass-Force and PD Controller Example Let us consider the modeling and simulation of a mass-force system, that is the controlled process, whose input-output relationship is described by Newtons Second Law, m x = f (t) (1.68)

where m is the mass, x(t) is the displacement(position) and f (t) is the input force acting on the mass. In state-space form (a set of rst order ordinary dierential equation (ODE) form), this equation can be represensted as

x1 (t) = x2 (t) x2 (t) = (1/m) f (t)

(1.69) (1.70)

Let us assume that we have a PD controller and output of the controller u(t) is amplied by an amplier/actuator pair to generate force f (t),

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB

83

f (t) = Ka u(t)

u(t) = Kp (xd (t) x(t)) Kd x(t)

(1.71) (1.72)

where Kp and Kd are proportional and derivative control gains, xd (t) is the desired position as function of time, and Ka is the amplier/actuator gain which converts the low power controller signal to a high power actuation signal proportionally.
/* Implementation of dynamic system simulation program using MATLAB */ % mass_s.m % % simulates a continuous time dynamic system using % 4 th order Runga-Kutta integration algorithm. % % dynamic system: mass-force system % controller : PD control algorithm % % Initialize simulation... %.....Dynamic system ..... t0 = 0.0 ; tf = 4.0 ; t_sample = 0.01 ; t_int = 0.005 ; x = [ 0.0 0.0 ] ; x_out = x ; u_out = 0 ; %.....initialize controller parameters.... k_p = k_v = 16.0 ; 4.0 ;

% Start the simulation loop... %Digital controller simulated % Controller is a digital controller with sampling period t_sample for (t = t0 : t_sample : tf ) mass_ct1 ; for (t1 = t : t_int : t+t_sample-t_int ) x = rk4(mass_dyn,t1,t1+t_int, x, u) ; end x_out=[x_out ; x ] ; u_out=[u_out ; u ] ; end

84

CHAPTER 1. MATLAB AND ITS TOOLS

% Analog controller simulated % -- Notice the call sequence to controller and dynamic model simulator. % for (t = t0 : t_sample : tf ) % for (t1 = t : t_int : t+t_sample ) % mass_ct1 ; % x = rk4(mass_dyn,t1,t1+t_int, x, u) ; % end % x_out=[x_out ; x ] ; % u_out=[u_out ; u ] ; % end % % ..Plot results.... t_out=t0:t_sample:tf ; t_out = [t_out ; tf+t_sample ] ; clg ; subplot(221) plot(t_out,x_out(:,1)) ; title(position vs time) ; subplot(222) plot(t_out,x_out(:,2)) ; title(velocity vs time ); subplot(223) plot(t_out,u_out) ; title(control vs time ); pause % ... end......

% % %

mass_ct1.m Implements a PD controller for a second order system...

% % % % % % %

get sensor measurements .... in simulation this is readily available, in hardware implementation that will require a call to sensor device drivers i.e. A/D converters.... x(1) - measured position, x(2) - measured velocity. desired motion ... xd = [ 1.0

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB


0.0 % % ] ;

85

PD control algorithm............. If a state estimator is used, it should be implemented here... u = k_p * (xd(1)-x(1)) + k_v * (xd(2) - x(2)) ;

% Output to D/A converter in hardware implementation.... % In simulation, the u is returned to the calling function... % ..end.... function xdot=mass_dyn(t,x,u) % % describes the dynamic model: o.d.es % returns xdot vector. % xdot = [ x(2) u(1) ]; function x1=rk4(FuncName,t0,tf,x,u) % % implements Runga-Kutta 4th order ingetration algorithm on % o.d.es. % h = tf - t0 ; h2= h/2 ; h6= h/6 ; th=t0+h2 ; xdot = feval(FuncName,t0,x,u) ; xt = x + h2 * xdot ; dxt = xt = dxm = xt = dxm = dxt = x1 = feval(FuncName,th,xt,u) ; x + h2 * dxt ; feval(FuncName,th,xt,u) ; x + h * dxm ; dxm + dxt ; feval(FuncName,tf,xt,u) ; x + h6 * (xdot + dxt + 2.0*dxm) ;

% .... End.....

86
y

CHAPTER 1. MATLAB AND ITS TOOLS


y

a 1 b 1

y
0

Figure 1.18: Linearization of functions.

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB

Figure 1.19: Pendulum model

u( t )

x( t )

x0

Figure 1.20: Eulers method for solution of o.d.es


t0
t
f

87

x ( t0 + t ) = x ( t 0 ) + f ( x0 ,u0 ; t0 ) t

t0

88

u( t )

t0
x( t )
k3

x0

k2
k1

k4

CHAPTER 1. MATLAB AND ITS TOOLS

t0

Dt 2

t
Dt

x ( t + Dt ) = x ( t )+ Dt xave

= x ( t )+ Dt f ave
f ave ; average of derivatives at , t + Dt 2 , t + Dt . t

Figure 1.21: 4th order Runga-Kutta nite dierence approximation.

1.2. SIMULATION OF DYNAMIC SYSTEMS USING MATLAB

Figure 1.22: A continuous time feedback control system - controller and process are both analog.

2 7 ) 2 6 3     5  #  4 2 '$&$"$!60 %%11) ##%1  (


89

90

1.3

Simulink is a graphical modeling and simulation software tool which runs as part of the Matlab package. In Matlab, a dynamic system is modeled using M-les which holds the model description in text le format written in Matlab language. In Simulink, a system is modeled using graphical block diagrams and the connections between the blocks. Therefore, the graphical representation of the model is easier to understand and facilitates better communication between dierent users working on the same model. A typical model development using Simulink involves the following steps: 1. Given a mathematical and logical description of a system, build the model of the system using Simulink blocks from the block library. This involves selecting a number of blocks from the Simulink block library, and making the connections between them.

e GV If GqFc ` d f e f tCCXaQTd spSc t B9di IHHbPc dX `aa cb b A ErgRc`aYWBW9 BDcAcaeYeWgYYe@8 9feB9D@cYg Uhe
CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.23: A digital control system: process is analog, controller is digital.

Simulink

2. Setup the parameters of each block. Double-clicking on a block brings up the user interface menu for the block which allows us to setup the parameters of the block, i.e. value of the gain for a Gain block. Numerical values can be constants directly typed in the user interface dialog box or can be variables where the values of the variables are assigned in the Matlab Workspace by either directly making assignment statements in the Matlab Command Window or placing the assignment statements into a script-M le (the recommended method), i.e. lename Filename Parameters.m. 3. Setup the simulation conditions on the Model Windows Simulation menu item, (a) select the integration algorithm related parameters, simulation time interval,

(b) select the variables to be saved and plotted and connect them to the appropriate Simulink blocks (Scope, To Workpace, etc). 4. Run the simulation in Simulink and analyze the results. Simulink also has a built in Debugger which is accessed from the Tools Debugger menu item of the model window.

1.3. SIMULINK

91

Figure 1.24: Simulation results of a mass-force system under a PD controller. Commanded signal is a step function starting at time t = 1.0sec.

92

CHAPTER 1. MATLAB AND ITS TOOLS

Simulink is started by typing simulink in the Matlab prompt, or placing that command in the Startup.m le, or it can be launched from the Launch Pad Window of Matlab. >> simulink Once the Simulink starts, it brings up the Simulink Library Browser window. A new model is developed by selecting File New menu item and save by selecting File Save As menu. The default name for a newly opened model le is Untitled.mdl. A Simulink model is saved in a le with .mdl extension. All the hiearchical levels of the model are saved in one le. To build a model, dierent blocks are selected from the Simulink Block Library and copied over to the Model Window, in one of two ways 1. copy/paste menu items of Edit menu item, or 2. a block can be selected from the Block Library and dragged over to the Model Window, which is the preferred method. Then the connections between the blocks are made to dene the relationship between blocks to form the complete model. Preferences in Simulink provides a window of many menu items to congure the Simulink environment. For most applications, the default settings works well. It is accessed from File > Preferences menu item. The parameters of a block can be modied by double clicking on the block once it is in the model window. A menu comes up associated with the block. The parameters can be set to either to 1. a constant value, or 2. a variable to be dened in the Matlab workspace later on. Simulink block library is grouped into functional categories such as Sources, Sinks, Connections, Math, Signals etc. In addition to the standard blocks provided with Simulink, application specic block libraries can be added as Block Library Toolboxes similar to the toolboxes of Matlab. Blocks: From the Simulink Library Browser window, a new model is created by File New Model menu selection. This creates a model window with name Untitled. Now we can pick dierent blocks from the Simulink Library Browser window, drag them into the Untitled model window and build a model. Help can be obtained on any library block by rightclicking on it, and selecting Help from the context-sensitive menu. Basic properties of a block, i.e. orientation of the block etc., can be accessed through the blocks contextsensitive properties menu. Each block has a name which is by default placed under the

1.3. SIMULINK

93

Figure 1.25: Simulink window: Simulink library browser. To start a new model le or open an existing model le, use the File menu. Then pick, drag and drop component blocks from this library window.

94

CHAPTER 1. MATLAB AND ITS TOOLS

block. The names are strictly for the benet of the user and not used as a variable reference in the Simulink operations. Names of the blocks must be unique, in other words, same name can not be used for more than one block. Parameters of a block are accessed by double-clicking on it. The model is saved in the Untitled model window menu: File Save As: enter lename (extension is .mdl). Once a name is specied for the model and saved, the window title for the model window changes from Untitled to the specied le name. Connections: After selecting the blocks for the model, the next step is to draw the proper connections between them (Fig ??). In order to draw a straight line connections from the output of one block to the input of another block, simply click the mouse at the output point and drag the mouse to the input point of the other block. In order to draw a perpendicular break point, simply click the mouse in the intermediate point, then continue the drawing. In order to draw diagonal lines, hold the Shift key while drawing. To dene a branch point on a line, place the mouse at the point on the line to create the branch point and hold Ctrl key plus click the left mouse button. In order to insert a block over an existing line, just move and drop the block over the line. If the block is not inserted into the line, delete the line, and make the line connections again. In order to delete a line, select the line with the mouse, and hit Delete key or use the Edit Delete menu item. To remove a connection without deleting it, select it, pick the edge of the connection and move it. To make a straight line into a non-straight line, select the line, pick a point on the line, and drag it while holding the Shift key. Grouping of Blocks: Simulink supports block hierarchy. A block can be made of smaller sub-blocks. The hierarchy can be many layers deep. An existing group of blocks can be grouped into a single sub-system block. In order to group a set of blocks into a subsystem block, select them with the mouse in a rectangular select box (left click to dene the corner of the bounding rectangle, then drag the move to include the blocks desired in the in the sub-system, and release the move), then right click to bring up the context-sensitive menu, then select from menu

1.3. SIMULINK

95

Figure 1.26: Drawing connections in Simulink: straight and perpendicular lines, diagonal lines, creating break points on a line.

Figure 1.27: Simulink model of a mass-spring-damper system.

96

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.28: The mass-spring-damper system is grouped into a sub-system block showing the input and output ports, hiding the internal details of it. Edit Create SubSystem The set of blocks will now be replaced by a sub-system block. The new block will show the input ports and output ports of the grouped set and hide the details. In order to look into the details of the sub-system block (lower level hierarchy details), double click on the sub-system block. It will open a new window with the details of the block (Fig ?? and Fig ??). Grouping of blocks is a very useful tool in designing Simulink models with clear graphical and logical organization. Good programming practice dictates that the systems should be divided into sub-systems, and then those sub-systems should be divided into further subsystems in a logical tree structure. The sub-system denitions should be representation of pyhsical reality, as opposed to programming short cuts, in order to have good re-usability and maitainability for the model. Masking: A related topic to grouping is the masking of a block. Masking allows the user to dene a custom user interface to access the block parameters. It is like a custom wrapper around the block (Fig ??). Using masking, we can provide 1. the user more descriptive parameter information about the block parameters, and 2. hide some or all of the block details. If a sub-system block is masked, double-clicking on the block brings up the user interface that shows the parameters of the block that the user can change. It does not show the logical details of the block. If a sub-system block is not masked but grouped, then doubleclicking on the block brings up a new window showing the logical details of that block. In order to mask a block or sub-system block, select it rst. Then, select Edit Mask Subsystem Under this selection, we need to dene the following three tabs

1.3. SIMULINK

97

Initialization Icon Documentation

Block masks can be activated and deactivated. Once a mask is dened, deactivating it does not make the mask information lost. The mask information is still saved and can be activated by the user at any time. The masked block parameters can be assigned values as constants in this interface or as variables where the variables would later be assigned values in the Matlab workspace. Icon allows us to dene a bit mapped image le to be displayed on the masked block (le formats supported: bmp, jpg, tif), image ( imread (filename.jpg)) The Icon feature can be very useful to visually describe the model and highly recommended. Another useful tool in Simulink models it to have a button, and by double-clicking it, it executes a Matlab command, such as running an M-le. The Simulink block used for that function is in Signals and Sytems Block Library: Model Info Block Copy this block to the model window. Right-click the mouse to bring up the block properties menu. In the Open Function: section, type the Matlab command desired to be executed when the block is double clicked. Change the background and foreground color if desired. Also type a text on the block that describes its function. Let us connect the PD controller (Fig??) and the mass-spring-damper model (Fig ??) and simulate the system response.The equations described by the Simulink graphics is

m(t) = u(t) ; x

u(t) = kp (xd(t) x(t)) kv x(t) ;

mass f orce dynamics

(1.73) (1.74) (1.75)

P D control

where xd (t) is the desired (commanded) position signal, x(t) is the actual position signal. In this model, the model parameters are; For the simulations, we use the following parameters:

m = 1.0 Kv = 0.7 2 A simulation case result is shown in Fig ??. Kp = (2 )


2

(1.76) (1.77) (1.78)

98

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.29: Grouping and masking of Simulink blocks. This example shows the grouping and masking for a PD control block diagram.

1.3. SIMULINK

99

Figure 1.30: PD control and mass-spring-damper system model and simulation results using Simulink

100

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.31: Integrator Block

1.3.1

Simulink Block Examples

A model in Simulink is 1. a collection of blocks, 2. their inter connections, and 3. the parameters of each block. Here we will examine some of the most commonly used Simulink blocks. Integrator block and its options are shown below (Fig.??). Integrator is used to integrate a signal. Generally, input is the derivative of a state, output is the state of a dynamic system. The options include: initial condition, saturation limits (max and min) on output, reset input signal to reset the output of the integral, and saturation status output. The state is basically same data as the output. But it is a little more accurate in terms of timing when integrator output is used between enabled systems. Inport and Outport are the input and output port connections for Simulink subystems so that it can connect to other subsystems and external I/O. The gure below (Fig.??) shows a subsystem with two inports (In1, In2) and one outport (Out1). The labels of the ports can be changed to anything desired. Unused input/output ports should be terminated with the Ground block (outputs zero to an input terminal otherwise would be left unconncted) and Terminal block (terminates an output otherwise would be left unconnected) as a good programming practice (Fig.??). Logical and relational operators provide TRUE (1) or FALSE (0) output based on the inputs. Logical operator block property can be set to AND, OR, XOR, NOT, NAND, NOR operators (Fig. ??). The relational operator property can be set to == , = , > , < , >= , <= Look-up tables and data interpolation based on a table is commonly used in control applications. Simulink provides one-dimensional (i.e. f (x)), two dimensional (i.e. f (x, y)) and

1.3. SIMULINK

101

Figure 1.32: Inport and outport blocks for Simulink subsystems.

Figure 1.33: Ground block used to terminate open input point, Terminal block is used to terminate open output point. multi-dimensional loop-up tables that can be used for interpollation. A single dimensional table is simply two data vectors: row-vector (independent variable values, x) and the corresponding function (f ()) values with the same dimension. Two-dimensional tables have two variables: row-vector (i.e. 1xm ) and column-vector (i.e. 1xn), then the table must be a matrix of dimension mxn. Row-vector variable is connected to the x-port and column vector variable is connected to the y-port of the 2-D look-up table interpolator. The block displays the table data as follows: thr row vector is treated as x-axis, and the column vector is parameter and there is a curve for each column-vector in 2-D plot. Conditionally executed sub-systems can be implemented in one of three dierent ways: 1. enabled, 2. triggered, and 3. enabled and triggered sub systems In order to make a sub system conditionally executed, just include one of, or both of, the enabled and triggered blocks in the sub system and setup the parameters (Fig.??). A sub-system can be made enabled by placing an enable block in it, triggered by placing a trigger block in it, or it can be both enabled and triggered by placing both blocks. When the user adds enable and/or trigger blocks inside a sub-system, Simulink automatically

102

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.34: Logical, comparator blocks, and look-up tables.

1.3. SIMULINK

103

Figure 1.35: Enable and trigger blocks to make a subsystem enabled and triggered.

Figure 1.36: Goto and From blocks to simplify line connections in simulink graphical model description. adds an input port for the enable and trigger signals on top line of the block that represents the sub-system. Enabled block makes the sub system execute during the time the enable signal is larger than zero. Triggered subsystem makes the subsystem execute once on every trigger signal condition true. These two can be combined so that an enabled and triggered sub system would execute once on the trigger signal if it is also already enabled. Simulink initializes the states in the enabled and triggered states at the beginning of the simulation based on the user choices (initial conditions are set to zero if they are not explicitly dened by the user). We can call these start-up condition of the states.. When the subsystem is disabled and re-enabled/re-triggered again, the states can either be held from the previous run or reset to the start-up condition initial values. In order to simplify the graphical visual display of connections between blocks, we can use Goto and From blocks (Fig.??). In complicated models, the number of connection lines and their routing can get very crowded for visual understanding. In order to simplify that, a signal can be connected to a Go to block in one part of the model, and that signal can be picked-up using From block in another part of the model. That way, long routing of the connection lines are eliminated. In order to make the graphical display easier when large number of I/O lines involved, Mux/Demux and Bus-Creater/Bus-Selector blocks can be used (Fig.??). Data can be input/output from/to signal sources (i.e. function generator), signal sinks (i.e. scope), Matlab workspace and le (Fig.??). The Signal Builder block is a particularly useful signal source tool. It can be used to dene custom signal groups rather quickly and interactively for simulation input signals. Signal Builder provides graphical interface to dene groups of signals (i.e. three dierent groups of signals), then within each group dene

104

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.37: Connection signal line management blocks to simplify graphical display: Mux, Demux, Bus Create and Bus Selector blocks used in an example. individual signals (i.e. input functions r1 (t), r2(t)). Each signal (such as r1 (t)) function can be dened using the main interface tools (such as constant, step, pulse, rectangular, triangular signal type), then pick picking signal data nodes with mouse and move it around to further custumize the signal graphically. In addition, custom signals can be dened by an array of x-axis vector data and y-axis vector data for each signal. The data in between the sample points are linearly interpolated by default. There are three main function blocks in Simulink block library (Fig.??): 1. MATLAB function block (like sin(), exp(), but not an expression) which accepts vector input and provides vector output. It allows selection of a single Matlab function. It does not allow typing an expression. 2. Fcn function and expression block which operates on scalar or vector inputs but provides a scalar output. This block allows an expression made of Matlab functions and operators and input data. 3. Embedded MATLAB function block which can accept vector input and provide vector output and implement any function desired, but computationally not ecient. This block is basically a link to an Matlab m-function le such the one shown below, function y = Myfcn(u) % This block supports an embeddable subset of the MATLAB language. % See the help menu for details. y = 2.0 * ( u + 1.0 );

1.3. SIMULINK

105

Figure 1.38: Input sources and ouput destinations for the data of a Simulink model.

Figure 1.39: Function blocks in Simulink: Matlab Function (a single Matlab function), Fnc() allows an expression, Embedded Matlab Function which is linked to an m-function script le.

106

CHAPTER 1. MATLAB AND ITS TOOLS

Simulink provides subsystem blocks that implements the equivalent ve (5) blocks for loops (for, while, do-while) and conditional blocks (if, switch-case). In each case, the block is executed within a given simulation sampling period as long as the condition is satised or iteration count is not larger than the maximum value set.

1. for (i=begin : increment : end) ... ... end % See "for loop" blocks

The for block parameters is set in the menu of the block. The number of input and output port signals and the logic inside the block can be decided by the user, i.e. one can dene three input signals (in1, in2, in3) and two output signals (out1, out2) and some logic in between them. The block is executed for the number of times the for block; spoecies within the current sampling period. This equivalent to the for-loop in C language. 2. while(condition) ... ... end % See "while" blokc

While loop has two signals to determine its execution: Condition and IC ports. If IC port is true, then it acts like a do-while loop. Again, as many inports and outports can be added in the subsystem and desired logic can be dened. There is a parameter for this block named maximum number of iterations. It is advisable to set this parameter to a nite value. Simulink executes the block endlessley as long as the while condition is TRUE. Unless you are certain that the while condition will become false at some point in the simulation, you should specify a maximum number of iterations to avoid endless loops, which can be broken only by terminating MATLAB. 3. do ... ... while(condition) The subsystem block is executed at least once. After that, the status of Condition input port is checked. If true, the subsystem block is executed again, until the Condition is % See "Do-while" block

1.3. SIMULINK

107

false. As many input ports and output ports can be dened, as well as any desired logic can be dened inside the subsystem block. The number of iterations (execution) within a sampling period follows the same rules for the while block. 4. if (condition) ... elseif ... elseif ... else ... end 5. switch case (variable) case 1: .... case 2: .... case 3: .... default: .... end % See "Switch case" and "Action blocks" % See "if" and "if-action" blocks

If and Switch statement blocks allows us to select a block from a set of blocks to execute. Each If and Switch block is accomponied by Action blocks. There must be as many action blocks as there are the number of sections to if - elseif - elseif - else and Switch case statements.

108 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.40: Decision blocks: loops (for, while, do-while) and conditional (if, switch) blocks.

1.3. SIMULINK Modeling and Simulation of a Dynamic System Using Simulink

109

Simulink is a numerical modeling and time domain simulation software that allows us to mix linear, nonlinear, analog and digital systems in the model using interconnected blocks. In Simulink, the dynamic model and control algorithm are modeled using inter connected blocks. The user interface is a graphical one. In order to simulate the system response for a given input conditions, inputs are connected to various source blocks (i.e. function generator block, step input block). The response is recorded by connecting various output signals to sink blocks (i.e. scope block). The simulation start time, stop time, sampling time and integration method are selected in the Simulink setup window. In Simulink models, the input-output relationships are described by interconnected blocks. The individual blocks may represent linear or nonlinear functions between its input and output, transfer functions in Laplace transform form for analog systems and z-transforms form for digital systems. Input functions for the simulated case are represented in time domain form. The response of the system are also time domain functions. Example Let us consider the pendulum problem and its nonlinear dierential equation which describes the relationship between the torque at the base and the angular position of the pendulum (Fig. ??). We will simulate the response of the pendulum as a result of zero input, non-zero initial velocity, and zero initial position. The equation to build a model of in Simulink is g (t) + Sin((t)) = u(t) l (t0 ) = 0.0 (t0 ) = 1.0 u(t) = 0.0 ; t t0

(1.79) (1.80) (1.81) (1.82)

Let us simulate this for t0 = 0.0 sec, and for a time period of t = 0.0 sec to 5.0 sec. Figure ?? shows the Simulink model that represents this equation and the simulation result for this condition. Since this is a second order system (highest derivative of the dependent variable in the dierential equation) is two, we use two integrators in the Simulink representation. Notice the use of initial conditions for position and velocity as constant inputs to the integration blocks. Example Consider the liquid level in a tank and its control system shown in (Fig.??). Let us further consider a computer controlled version of the system: the mechanical levers are replaced by a level sensor, a digital controller and a valve that is actuated by a solenoid. In-ow rate to the tank is controlled by the valve. The valve is controlled by a solenoid. The input to the solenoid is the current signal from the controller and output of the solenoid is

110

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.41: Nonlinear dynamic model of a pendulum and simulation result in Simulink. proportional force. The force generated by the solenoid is balanced by a centering spring. Hence, The valve position or opening of the orice is proportional to the current signal. The ow rate through the valve is proportional to the valve opening. Assuming simplied linear relationships, the input-output relationship for the valve can be expressed as

Fvalve (t) = K1 i(t)

(1.83) (1.84) (1.85) (1.86) (1.87)

Qin (t) = Kf low xvalve (t) 1 = Kf low K1 i(t) Kspring = Kvalve i(t)

= Kspring xvalve (t)

where Kvalve = Kf low K1 /Kspring , which is the valve gain between current input and ow rate through the valve. The liquid level in the tank is function of the rate of in-ow, rate of out-ow, and the cross-sectional area of the tank. The time rate of change in the volume of the liquid in the tank is equal to the dierence between in-ow rate and out-ow rate, d(V olume in T ank) = (In f low rate) (Out f low rate) dt d(A y(t)) = Qin (t) Qout (t) dt dy(t) A = Qin (t) Qout (t) dt

(1.88) (1.89) (1.90)

The Qin is controlled by the valve to be between zero and maximum ow that can go through the valve, [0, Qmax]. The Qout is function of the liquid level and the orice geometry at the outlet. Let us approximate the relationship as a linear one, that is the higher the liquid height is, the larger the out-ow rate,

1.3. SIMULINK

111

Qout (t) =

1 y(t) R

(1.91)

where R represent the orice restirction as the resistance to ow. Then, the tank dynamic model can be expressed as

dy(t) 1 + y(t) = Qin (t) dt R

(1.92)

Let us consider a practical ON/OFF type controller with hysteresis. The controller either fully turns ON or turns OFF the valve depending on the error between the actual and measured liquid level. In order to make sure the controller does not switch the valve ON/OFF at high frequency due to small changes in the liquid level, a small amount of hysteresis is added in the control function. This type of controller is called relay with hysteresis and commonly used in many automatic control systems such as home temperature contol, liquid level control ([emax, emax] range). In Simulink, the controller function is implemented with a hysteresis block. In mathematical terms, the controller function is

e(t) = yd (t) y(t)

(1.93) (1.94)

i(t) = RelayHysteresis (e)

The relay control function with hysteresis where hysteresis band is [emax , emax] range. Flow rate can vary linearly between zero and maximum ow rate as function of current signal. Since current signal is either zero or maximum value, ow rate will be either zero or maximum ow.

Qin (t) = Kvalve i(t) = Qmax ; when i(t) = imax = 0 ; when i(t) = 0

(1.95) (1.96) (1.97)

Let us simulate the liquid level control system for the following conditions. The system parameters are emax = 0.05, imax = 1.0 A, Qmax = 1200liter/min = 20liter/sec = 0.02m3/sec, A = 0.01m2 , R = 500[m]/[m3/sec]. Consider the case that the desired liquid height is yd (t) = 1.0m which is commanded as step function, and the initial height of the liquid is zero (empty tank). The gure (??) shows the simulink model and simulation results.

112

Example

Consider the room or furnace temperature control system (Fig.??). We need to consider room temperature, outside temperature (cold) and a heater. The heater is controlled by a relay type controller with hysteresis. The room temperature is initially at the same temperature as the outside temperature. The controller is set to increase the room temperature to a higher level. The heater is controlled to regulate the room temperature. As the room temperature increases and becomes larger than the outside temperature, there is a heat loss from room to outside. The net added heat rate to the room is the dierence between the heat generated by the heater and the heat loss to the outside since outside temperature is colder. The temperature raise in the room is function of this dierence and the size of the room. The heat loss is linear function of the inside and outside room temperatures. Net heat added (or lost) to the room will result in the temperature change,

where mc is the heat capacitance of the room which is function of the room size, R is the resistance of the heat transfer from walls due to the temperature dierence. The eective resistance to heat transfer between room and outside is function of the type of dominant mode of heat transfer (conduction, convetion, radiation) as well as the size and insulation type of walls. T and To are inside and outside temperatures, respectively. Let us simulate the room temperature control system for the following conditions; desired temperature Td = 72o F , initial temperature To = 42o F ,allowed error in room temperature in the hysteresis function of the relay control system, emax = 0.50 F , maximum heat-in

wx y v y v y yux yw y v
Figure 1.42: Liquid level control in a container. (N etHeat Added to Room) = (Heat in Rate) (Heat out Rate) Qnet = Qin Qout dT 1 mc = Qin (T To) dt R

CHAPTER 1. MATLAB AND ITS TOOLS

(1.98) (1.99) (1.100)

1.3. SIMULINK

113

rate Qmax = 100 , R = 100, mc = 1.0. Initially the room is assumed to be at the same temperature as the outside temperature. After entering the room, i.e. one second later, the temperature is commanded to be Td = 72oF . The relay controller is active if the temperature dierence is dierent than the commanded temperature by 0.5oF . Fig.?? shows the Simulink implementation of the model and simulation results. Example: Web Tension Control System Consider the web tension control system shown in (Fig.??). The wind-o roll is driven by another part of the machinery where the speed v1 (t) is dictated by other considerations. The wind-up roll is driven by an electric motor. This motor is required to run in such a way that the tension in the web (F ) is maintained constant and equal to a desired value (Fd ). So, if the wind-o roll speeds up, the wind-up roll is suppose to speed up. Similarly, if the wind-o roll slows down, the wind-up roll is suppose to slow down quickly. The wind-o roll speed is given as an external input and not under our control. The wind-op speed is our controlled variable. Our objective is to minimize the tension error, e(t) = Fd (t) F (t). The tension in the web will be determined by the dierence between the integral of v1 (t) and v2 (t),

y(t) = y(t0 ) +

to

(v2 (t) v1 (t))dt

(1.101) (1.102)

F (t) = Fo + k y(t)

If initially the web tension is adjusted so that when y = y0 , the tension F = F0 = 0 by proper calibration, then we can express the tension as function of change in y(t),

y(t) = y(t) y(t0 )


t

(1.103) (1.104) (1.105) (1.106) (1.107)

=
to

(v2 (t) v1 (t))dt

Y (s) =

1 (V2 (s) V1 (s)) s F (t) = k y(t) k F (s) = (V2 (s) V1 (s)) s

The control system that controls the v2 (t) is a closed loop control system and implemented using an analog controller (Op-amp in the Fig.??). Let us consider the dynamics of the amplier and motor as a rst order lter, that is the transfer function between the commanded speed w2,cmd to actual speed w2 ,

114

CHAPTER 1. MATLAB AND ITS TOOLS

w2 (s) 1 = w2,cmd (s) m s + 1

(1.108)

where m is the rst order lter time constant for the amplier and motor. The corresponding linear speeds are

v2,cmd (t) = r2 w2,cmd (t) v2 (t) = r2 w2 (t) Let us consider a proportional controller,

(1.109) (1.110)

w2,cmd (t) = Kp (Fd (t) F (t))

(1.111)

Figure ?? shows the model and simulation conditions in Simulink. The parameters of the system used in the simulation are,

k = 10000 [N/m] Kp = 10 [m/s/m] m = 0.01 [sec] r2 = 0.5 [m]

(1.112) (1.113) (1.114) (1.115)

We will simulate a condition where v1 (t) has a step change from its nominal value for a period of time.

v1 (t) = 10.0 + 2.5 f1 (t) Fd (t) = 50 step(t 1.0) ; step f unction starts at 1.0 sec

(1.116) (1.117)

where f1 (t) represents a square pulse function with a period of T = 30sec. Interested reader can easily experiment with dierent control algorithms as well as dierent process parameters, i.e. dierent roll diameter values r2 .

1.3. SIMULINK Example: Simulink Model for Anti-Lock Brake System (ABS) Let us consider a simplied ABS brake control algorithm:

115

1. while the vehicle is moving, when the operator presses the brake pedal, the ABS brake system activates. 2. the ABS algorithm measures (or estimates) the actual wheel slip, 3. compares it to the desired slip, which is sd = 0.2 4. and decides on brake pressure signal using an ON/OFF (bang-bang) type algorithm. The slip error based simple ABS control algorithm might be something like the following,

u = umax if e > 0.0 = umax if e 0.0

e = sd sa

(1.118) (1.119) (1.120) (1.121)

where sd , sa are desired and actual slip, u is the control signal to the ABS valve. In real application, the above ON/OFF relay type control algorithm would also include some small amount of hysteresis about the zero error condition in order to avoid high frequency chattering of the control signal. Notice that the band of the hysteresis (width of the hysteresis on error) should not be too large, which can lead to unstable closed loop system. If it is too small, it can result in a control signal with high frequency switching (chattering) signal around zero slip error. In this example Simulink model, we implement a small hysteresis function. The ABS hydraulic system dynamics is such that there is a rst order lter type delay between the ABS control signal and actual pressure build up. The pressure in the brakes builds up as an integral of the ABS control signal. The pressure is limited to zero at the lower limit and maximum supply pressure at the upper limit. Initial pressure value is zero at the beginning of any ABS activation. This information is used in the integrator blocks with saturation and initial condition.

up (s) =

Kv u(s) v s + 1 1 pb (s) = up (s) s Tb (s) = Kb pb (s)

(1.122) (1.123) (1.124) (1.125)

116

CHAPTER 1. MATLAB AND ITS TOOLS

where up (s) is the brake pressure signal reaching the brake valve (Laplace transform of the up (t)), Kv , v are the gain and time constant of the valve response, pb (s) is the brake pressure developed which is the integral of the ABS signal reaching it, Tb (s) is the brake torque, Kb is the gain between the brake pressure and the resulting brake torque generated at the wheel. The vehicle tire and traction dynamics is modeled as an inertia with two torque sources acting on it: 1. traction force which is determined by the actual slip (hence the friction coecient), vehicle weight and wheel radius, 2. brake torque. The integration of this inertia-torque model determnines the wheel speed.

ww (s) =

Ft (s) = (sa ) mv g/4

1 1 (Te (s) + Tt(s) Tb(s)) Jw s Tt(s) = Rw Ft (s)

(1.126) (1.127) (1.128) (1.129)

where Tt(s), Ft(s) are traction torque and traction force at the tire (Laplace transforms of their time domain form), Rw , mv are the radius of the tire and mass of the whole vehicle, g is the gravity. In this model, we assume that during ABS brake the wheels do not get any torque from the engine, Te (t) = 0. It is assumed that 1/4 of the vehicle weight is distributed over each wheel-tire. Vehicles translational motion is modeled as mass-force system where mass, mv , is the vehicle mass, and force is the traction force. While the vehicle is running at a constant speed, if the ABS brake is applied, the net traction force, that is the friction force at the tires, will be the force to decellerate the speed of the vehicle. We assume that torque delivered to the wheels from the engine during ABS action is zero. From the vehicles translational speed, we also calculate the corresponding wheel speed if there were zero slip. From this calculated wheel speed and measured actual wheel speed, we calculate the actual slip, which is needed to implement the ABS algorithm.

Vv (s) = wv (s) =

1 1 (Ft (s)) mv /4 s 1 Vv (s) Rw

(1.130) (1.131)

where mv is the mass of the whole vehicle. It is assumed that the vehicle mass is distributed over the four tires equally. The actual slip is calculated, assuming measured wheel speed (ww (t)) and measured vehicle liner speed (Vv (t)) from which equivalent wheel angular velocity is calculated (wv (t))

1.3. SIMULINK

117

sa = 1.0

ww wv

(1.132)

Simulink block diagram of the ABS algorithm and vehicle dynamics is shown in Fig.??. The model is simulated for the parameters shown on the gure and below. Two cases are simulated: Case 1 is for ABS is not active and brakes are always applied if pressed, Case 2 is for ABS is active. Simulated parameters;

sd = 0.2 ehys = eps Kb = 10.0 Kv = 100. umax = 1.0

Desiredslip Hysteresis band Brake pressure to torque gain Control signal to pressure gain T ime constant of ABS valve F riction coef f icient look up table maximum control signal

(1.133) (1.134) (1.135) (1.136) (1.137) (1.138) (1.139) (1.140) (1.142) (1.143) (1.144) (1.145) (1.146)

v = 0.001 sec = (sa ) =

= {(0, 0), (0.1, 0.8), (0.2, 1.0), (0.3, 0.96), (0.4, 0.92), mv = 1000.0 kg g = 9.81m/s Rw = 0.25 m Jw = 1.0kgm
2 2

(0.5, 0.88), (0.6, 0.83), (0.7, 0.79), (0.8, 0.75), (0.9, 0.72), (1.0, 0.7)}(1.141) V ehicle mass Gravitational acceleration W heel radius W heel rotational mass inertia

The results for the simulated cases are shown in Fig. ?? which clearly shows that when ABS is active during braking, vehicle stops faster (within a shorter distance) compared to the case when ABS is not active during braking.

118

CHAPTER 1. MATLAB AND ITS TOOLS

Kp

D / A A mp.

A /D

Valve

q supply

qin

L evel measurement : h

R estriction Flow Meter q Measurement : out

qout
h (a)

y
r -

- Out flow rate - Height

Kp

A mp.

Valve

Water Tank

(b)

Figure 1.43: A liquid level/ow-rate control system (a) components, (b) block diagram

1.3. SIMULINK

119

l l j l l q o w u v pm s l m m xlz pmk pl l onnmzii s gmnmnlgniy ipy s f we {l ~ lzd uziitdig jgsf k |uh }r | |ml
Figure 1.44: Model and simulation of a liquid level control system. Figure 1.45: Temperature control of a space (i.e. room or furnace).

120

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.46: Model and simulation of furnace or room temperature control system.

Figure 1.47: Web tension control system.

1.3. SIMULINK

121

Figure 1.48: Model and simulation of web tension control system. Top gure is the Simulink model of the tension control system. The left plot shows the commanded tension on the top and actual tension at the bottom. Right plot shows the wind-o and wind-up speeds.

122

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.49: Conguration of Parameters in Simulink for a particular model simulation. Before running a simulation, Simulation > Conguration Parameters > Solver (and other options as needed) should be congured appropriately for the model.

1.3. SIMULINK Figure 1.50: Simulink model for an ABS brake system and vehicle model simulation shown with two main subsystems: ABS controller and vehicle dynamics. 123

124 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.51: Simulink model for an ABS brake system and vehicle model simulation shown with two main subsystem details: details of ABS controller and vehicle dynamics.

1.3. SIMULINK 125 Figure 1.52: Simulation results for the ABS system. The gure on the left is without ABS controller, the gure on the right is with ABS controller.

126

CHAPTER 1. MATLAB AND ITS TOOLS

1.3.2

S-Functions in C Language

S-functions are the most powerful method of extending the capabilities of Simulink. Sfunctions can be written in Matlab, C, C++, Fortran and Ada languages. Here, we discuss the S-functions written in C language only. S-functions created in Matlab language are called M-File S-Functions. S-functions created by C, Fortran and Ada are called MEXFile S-Functions. Most third party companies add value to Simulink through the use of MEX-File S-functions, i.e. adding hardware device drivers and custom algorithms. MEXFile S-functions are more powerful than M-le S-functions. S-functions can also be processed by the Real Time Workshop (RTW). The code generated by the RTW can be customized by writing a Target Language Compiler (TLC) le. The user interface to S-functions can be masked to customize its dialog box with the user. S-functions are used to 1. add new functionalities to Simulink that are not provided by standard Simulink blocks, 2. develop hardware device drivers for Simulink, 3. include existing C-code (legacy code) C-functions into Simulink blocks. There are two main steps to using S-functions in Simulink: 1. Create S-function MEX-le. 2. Add S-function block to your Simulink model, associate it with the desired S-function MEX-le, and setup its parameters, if any. The process of creating S-functions in C-language and generating MEX-le from it is discussed below in detail. MEX Utility Setup and Usage An S-function is a MEX le with extension .mexw32 for 32-bit Windows environment. This le is generated from C-source les using the mex utility of Matlab. In a given development environment mex utility should be congured once using >> mex -setup

Matlab asks the user to select a compiler from an available list on the host, and the setup is completed. The Lcc C compiler is provided by the Matlab instalation and can be used for this purpose. Then nally, the S-function C-le must be processed by mex utility to create a dynamically loadable executable for Simulink (MEX short for Matlab Executable). For S-function les generated using S-Function Builder block, the compile process is done by

1.3. SIMULINK

127

using the Build button on the menu. The Build process generates three source les, and compiles them to a dynamically linkable le with extension *.mexw32 by calling the mex utility.
sfunc.c -- The C-file which implements the standard S-function format.

sfunc_wrapper.c -- The specific C-code for this S-function is in this file. sfunc.tlc -- File used for accelerated mode as well as to allow RTW to include the S-function in its auto-code generation. -- MEX file representing the S-function.

sfunc.mexw32

Adding S-Functions in a Simulink Model First, let us consider the steps of adding an S-function block to your Simulink model. Let us assume that the S-function (and its MEX le) is created. In order to add an S-function to a Simulink model le, 1. open your Simulink model le, 2. drag theS-function block from User-Dened Functions in the Simulink library into the Simulink model le, Simulink -> User-Defined Functions -> S-Function Block

3. By double-clicking on the S-function block, the S-function block parameters window comes up where we connect the S-function block to an MEX-type S-function le, along with initialization parameters if any (Fig.??). 4. Once the S-function conguration is completed, the block displays the correct number of input and output ports as dened in the C-le. Then input-output connections are made in Simulink. In order to pass parameters to the S-function from the Simulink model (i.e. gains of a PID controller), the user must know the list of parameters S-function expects. Then these parameters are passes in order as a list, separated by commas. The parameter values can be constants or data variables in Matlab workspace. With this step, we basically place an S-function block in the Simulink model, then dene the name of the MEX-le S-function that will be linked to this Simulink block, its inputs and outputs, and parameters (if any).

128 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.53: Adding an S-function block to a Simulink model le.

1.3. SIMULINK Creating MEX-type S-Functions in C-language There are three methods to create S-functions (Fig.??:

129

Using S-Function Builder block: This method uses a user-dialog box to allow the user to dene the inputs, outputs and parameters of the S-function, and generates a source le that has the proper structure as well as the function calls to the wrapperfunctions. The user then connects to his/her logic by inserting the calls from the wrapper functions to their own functions. The mex utility, which is used to generate the *.mexw32 MEX le, is activated by the Build button on the dialog box. Hand Written C S-Function Files Using Template C-les for S-functions: This method uses an example template le which should be edited to customize it for a given application, including the modications to dene inputs, outputs, parameters and the user logic. The mex utility is run from the command line of Matlab, in order to generate the *.mexw32 le. Integrate Existing C Functions as S-functions using Legacy Code Tool (LCT): This method takes the existing legacy C-code les, formats them automatically to t into the S-function format requirements, and using the mex utility in the background generates the *.mexw32 le. This method is basically implemented with a script-m le and includes less than ten function calls to LCT utility. The output of all three methods is a collection of C language les which has a special format that comforms to S-function requirments. Then these les are processed by the mex utility and compiled into a dynamically linkable le with extention *.mexw32. This is the le that represent the S-function. Then, we use this le to link it to an S-function block in a Simulink model. Creating MEX-type S-Functions in C-language using S-Function Builder Block For most users, the S-function format is best generated by the S-Function Builder block. Using this block, the user makes various conguration choices in the menus of a window, then the S-Function Builder generates an S-function le with the correct format. Then, the user has to type-in the code or call user-supplied C-functions from this le. In order to create an S-function le, in Simulink, drag and copy S-Function Builder block from Simulink Library into a Simulink Model le (Fig.??). Once an S-function generated, it can be used in a specic model in two dierent ways: Copy the generic S-function block from Simulink Library > User-Dened Blocks section. Then double-click on it, then type in the desired S-function le name and parameters in the approporiate eld. Finally, make the input and output connections. This method does not show the user the source code associated with the S-function. This is the normal method of using S-functions in a Simulink model.

130

CHAPTER 1. MATLAB AND ITS TOOLS

S-Function Builder Block

Hand-written code Using Templates

Legacy Code Tool

C-Header Files C-Source Code Files C-Wrapper/Template Function Files

MEX Utility: >> mex ...

MEX S-Function File File: *.mexw32

Simulink Model (using S-function)

Figure 1.54: Developing S-functions in C-language and using them in Simulink models.

1.3. SIMULINK

131

Copy the S-Function Builder block from the model which was used to generate the S-function, set its parameters, connect its input and output ports. Then, the model is ready to use. This method allows the user to see the source code associated with the S-function block. The major programming eort goes into creating the S-function C-le. The key to remember is that S-functions must have a certain format in order to work with Simulink. Then, once that format is obeyed, the logic that goes inside the S-function is all up to the user. The only thing the user needs to understand is 1. what the input-output variables are passed between the S-function and the Simulink environment, 2. what parameters (if any) are used. These parameters will be dened by the user when this S-function is later inserted into a model to congure it for a particular application, and 3. where the user-dened code should be inserted.

132 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.55: Writing an S-Function le using S-Function Builder block.

1.3. SIMULINK

133

S-functions work with Simulink using the so called callback functions. In the Simulink model le, S-function is called by Simulink. The S-function then calls back various general purpose Simulink functions to execute a general purpose model structure. In the general form, a Simulink block is a combination of continuous and discrete time system with input and outputs. An S-function implements the same in the most general form. A typical Sfunction may not implement all of its general features. For instance, a digital PID controller may only need to implement the discrete time system portion of the S-function. The general form of a Simulink block, hence that of an S-function, is as follows,

xc = fc (t, xc , xd, u) xd (k + 1) = fd (t, xc, xd , u) y = fo (t, xc, xd , u)

Derivatives U pdates Outputs

(1.147) (1.148) (1.149)

Simulink executes the model in the order as shown in Fig.??. At the beginning, the model is rst initialized. That includes allocating space for data, set proper dimensions for input ports and output ports. Then during the simulation, the simulation loop is executed every sampling period. For instance, if we implement a discrete PID control algorithm, it would be described in the Updates section or the Outputs section of the S-function and executed every sampling period. Double-click on the S-Function Builder block to bring up its conguration menu. Based on the settings on this window, the block generates an S-function C-le, which has the necessary format. This le can be considered the wrapper le for the custom code we intend to put in the le. When we use the S-Function Builder, we only need to be concerned with the input/output/parameters data and the user-code that goes into the wrapper functions. The user-dened code insertion location is aided by the S-Function Builder Block menu items as shown below. The user can either copy the C-code into these windows or simply place a function call to the user-supplied C-function. The version that is produced by the S-function Builder block includes the calls to ... wrapper(...) functions in appropriate functions. If desired, the ... wrapper(..) function calls can be skipped and the code logic can be directly added to the various function locations in the le. Any user-code typed in the Dialog Box of the S-Function Builder blocks Outputs, Continuous Derivatives, and Discrete Update panes will be inserted into the corresponding wrapper functions. Everytime Build button is pressed, the logic content entered in the Dialog Window panes Outputs, Derivatives, Updates are copied to the S-function source le and compiled. If the user code is to be manually typed (or cut/paste from another source) in the wrapper functions instead of automatically copied from the Dialog Window panes by the Build, then it is best to edit the wrapper functions directly, and compile the S function les using the command line execution of mex utility

134

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.56: S-functions and Simulink operation.

1.3. SIMULINK >>mex sfunc_file.c sfunc_file_wrapper.c

135

Then check to see that the build process generated the function sfunc le.mexw32. This is the le that is linked to the S-function block in a Simulink model. The user-code goes into one or more of the following locations: /* Filename: sfunc_1.c .... void mdlOutputs(.....) { /* ... calls corresponding wrapper function sfunc_1_Outputs_wrapper(...) } */ */

void mdlDerivatives(.....) { /* ... calls corresponding wrapper function sfunc_1_Derivatives_wrapper(...) }

*/

void mdlUpdate(.....) { /* ... calls corresponding wrapper function sfunc_1_Update_wrapper(...) } .....

*/

/*

Filename: sfunc_1_wrapper.c */

136

CHAPTER 1. MATLAB AND ITS TOOLS

void sfun_1_Outputs_wrapper(.....) { % Called from mdlOutputs(....) % User-defined code (or call to a user-defined function) goes here % Build copies the code from the Outputs pane to here .... } void sfun_1_Derivatives_wrapper(.....) { % Called from sfun_Derivatives(....) % User-defined code (or call to a user-defined function) goes here % Build copies the code from the Continuous Derivatives pane to here .... } void sfun_1_Update_wrapper(.....) { % Called from sfun_Update(....) % User-defined code (or call to a user-defined function) goes here % Build copies the code from the Discrete Update pane to here .... } The dialog window of the S-Function Builder Block has all the information needed to properly dene and generate an S-function. We will illustrate the use of the dialog window with an example below. Before the example, it is important to understand the input/output and parameters data exchange between Simulink and an S-function. These are dened in the Data Properties pane of the dialog window. The input variables u0, u1, u2, ..., uN are pointers to arrays containing the inputs to the S-function, where N is the number of input ports to the S-function and each port can be a scalar or a vector or a matrix. If the

1.3. SIMULINK

137

width of the input N = 1 is specied, then the length of of the input width is specied by the u width variable, which is the product of the input matrix dimensions (if the input is a vector, then it is the length of the vector). The output variables y0, y1, y2, ..., yM are pointers to arrays containing the outputs from the S-function, where M is the number of output ports to the S-function and each port can be a scalar or a vector or a matrix. If the width of the output M = 1 is specied, then the length of of the input width is specied by the y width variable. The state variables xD, xC are discrete and continuous state arrays, specied in the Initialization pane of the Sfunction Builder Block to create the S-function C-le. The parameters param0, param1, param2, ... paramN, p_width0, p_width1, p_width2, p_widthN

are the parameter arrays and the length of each array. These are specied in the S-Function Builder Blockss Data Properties Pane > Parameters pane. Parameters can be a scalar or a vector. The above variable names of the input, output and parameters in a specic case will reect the names used in the S-Function Builder blocks Dialog Box. In the wrapper functins, we refer to these data in the implemented logic using zerobased vector indexing. In two dimensional matrix case, the reference to matrix elements must be made using single-index, zero-based, column-by-column ordered, method. For instance, consider a parameter B(3, 2) matrix. The elements of the matrix reference would be referenced using B[0], B[1], B[2], B[3], ...., B[5], where the following relationship holds,

B[0] B[3] B(1, 1) B(1, 2) B(2, 1) B(2, 2) = B[1] B[4] B(3, 1) B(3, 2) B[2] B[5]

(1.150)

As an example, implementation of a linear matrix dierential equation in a wrapper function would be as follows,

138

CHAPTER 1. MATLAB AND ITS TOOLS

x1 (t) x3 (t)

x(t) = A x(t) + B u(t)


(1.151)

A(1, 1) A(1, 2) A(1, 3)

x1 (t) x3 (t)

x2 (t) =

A(2, 1) A(2, 2) A(2, 3) x2 (t) + B(2, 1) B(2, 2)

A(3, 1) A(3, 2) A(3, 3)

B(1, 1) B(1, 2) B(3, 1) B(3, 2)

u1 (t) (1.152) u2 (t)

The implementation code in the sfun 1 Derivatives wrapper(...) would be as follows, void sfunc_1_Derivatives_wrapper(const real_T *u, const real_T *y, real_T *dx, real_T *xC, const real_T *A, int_T p_width0, real_T *B, int_T p_width1, int_T y_width, /* optional */ int_T u_width) /* optional */ { /* Your ... dx[0] dx[1] dx[2] ... } code inserted here. */ = A[0] * xC[0] + A[3] * xC[1] + A[6] * xC[2] + B[0] * u[0] + B[3] * u[1] = A[1] * xC[0] + A[4] * xC[1] + A[7] * xC[2] + B[1] * u[0] + B[4] * u[1] = A[2] * xC[0] + A[5] * xC[1] + A[8] * xC[2] + B[2] * u[0] + B[5] * u[1]

1.3. SIMULINK Example: Simulink Model with an C MEX-File S-Function

139

This example shows the process of writing an C MEX-le S-function to implement a PID controller and simulate it with a mass-force system. First, we build the C MEX-le S-function of the PID controller. Then, we used in a mass-force dynamic system model to simulate the S-function PID controller. Start a new Simulink le for the S-function, sfunc PID.mdl using Simulink. Then, from User-Dened Functions library of Simulink, drag-and drop S-Function Builder block (Fig. ??). Simulink Library -> User Defined Functions -> S-Function Builder

Start a second Simulink model that will simulate the mass-force system with the PID S-function. Let the le name be MK PID.mdl (Fig. ??). Build the mass-force system as shown using two integrator blocks and two gain blocks. Then, use a Pulse generator block from Sources and a Scope block from Sinks to dene the input and outputs. Then from User-Dened Functions library of Simulink, drag-and drop S-Function block. Simulink Library -> User Defined Functions -> S-Function block

Once we complete the S-function build process in the sfun PID.mdl le and generated the MEX-le (let us call the le name PID Control.mexw32), we will setup the name, parameters and input-output of the S-Function block to this le. Now, let us go back to the rst le (sfunc PID.mdl) to develop the S-function le for the PID controller. We plan to implement the following PID controller: 1. Inputs: yd (t), y(t), y(t) desired position, measured position, measured speed, 2. Outputs: u(t) control signal, 3. Parameters: Kp , Kd, Ki proportional, derivative and integral gains, The PID algorithm in its digital (sampled) form, the following will be implemented at every sampling period,

ei = ei + (yd y) u = Kp (yd y) Kd y + Ki ei

(1.153) (1.154) (1.155)

where ei = 0.0 at the beginning of the simulation as the inital condition. Double-click on S-Function Builder block to bring up its conguration menu (Fig. ??). Enter the information for all the panes on the conguration menu. Let us pick the name for the S-function le to be generated as PID Control. In this menu, we dene the input and

140

CHAPTER 1. MATLAB AND ITS TOOLS

output ports, initializations of states (continuous or discrete states are dened), parameters of the algorithm. Then, we also dene the logic in appropriate section such as Outputs, Continuous Derivatives, and Discrete Update panes. In this example, we dene the integral of error as a discrete state. Initial condition of the integral of error is set to zero. Input to the block has three components: commanded position, measured position and measured speed. These three signals are used in the PID algorithm. In this example, we provided three input ports, each signal being scalar. It is possible that each port can be a 1-D vector or a 2-D matrix. In other words, we could package the three scalar inputs into a vector and feed that into a single input port as well. Ports are added or removed by clicking on the insert and delete icons on the window (Fig. ??). The order of the input port number and the corresponding input port variable can be changed using the up and down arrows on the left side of the pane. Output ports dene the output signals from the S-function block. Enter the name, dimension and data type as shown. Each output port can be a scalar, or vector or a matrix. Same rules apply to Output port conguration as the Input port conguration (Fig. ??). Parameters are the data used in the algorithm, in this case, the gains of the PID control algorithm. Each parameter is a vector (Fig. ??). If each parameter is scalar, they are refered as a single element vector in the equations (see the Outputs logic below). Note that the order of the parameters entered here should be documented for the S-function block. The user must pass the parameters from the S-function dialog window in the same order. Therefore, a brief description about the parameters and their order should be included in the documentation for the S-function by the developer using the S-Function Builder block. The data types pane is used to dene the data type of input and output port data, as shown. For each port, there is a row entry in the pane. For each port name, the user can select the appropriate data type (Fig. ??). Libraries pane is used to dene the library and other referenced source le locations. Library path (LIB PATH), source le path (SRC PATH) and include paths (INC PATH) can be entered to make the le information easier.

SRC_PATH INC_PATH LIB_PATH

c:\MyWork\Source c:\MyWork\Include c:\ProgramFiles\Matlab\Library

The S-function Builder inserts a call to the wrapper function from the mdlOutputs function. The user logic typed in this window is inserted into the wrapper function. Hence, the wrapper function will execute this code (Fig. ??). The continuos derivatives pane provides the space to implement the dierential equation relationships for continuous time dynamics. The same wrapper function relationship applies. Similarly, discrete type state relationship is entered at the Discrete Update pane. In this example, we implemented the integral of error as a discrete state, and hence discrete integration is entered at this location (Fig. ??).

1.3. SIMULINK

141

Once all the information is entered, click the Build button. If there are any errors, it is displayed on the pane. The following source les will be created by the Build process, 1. S-function C-language source le: PID Control.c, 2. wrapper functions le (C-language) that contains the custom code that was entered in the S-Function Builder Dialog Box: PID Control wrapper.c, 3. PID Control.tlc, TLC le, which is used to let Simulink to run the generated code in accelerated mode and Real Time Workshop (RTW) to include the S-function in the auto-code generation process. 4. The Build process uses mex command internally to compile and link and generate the dynamically executable code: PID Control.mexw32. Now, the S-function le is ready for use in a Simulink model. Every time Build button is clicked, the code typed in the Outputs, Continuous Derivatives, Discrete Update panes are copied over into the wrapper functions. The previous logic in the wrapper functions are over-written. Before running the simulation on the le MK PID.mdl, dene the S-function block parameters: name of the S-function le (PID Control), parameters (Kp, Kd, Ki), connect the input and output signals to this block appropriately (Fig.??). Finally setup the parameters of the gain blocks in the mass-force model, simulation time period. Then simulate the system response (Fig.??).

142 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.57: Writing an S-Function le using S-Function Builder Block.

1.3. SIMULINK Figure 1.58: Using an S-Funtion le in a Simulink model: mass-spring system with a PID controller, where the PID controller is implemented as an C-MEX S-function. 143

144 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.59: Writing an S-Funtion le using S-Function Builder Block: Initialization setup.

1.3. SIMULINK Figure 1.60: Writing an S-Funtion le using S-Function Builder Block: Data Properties >Input ports setup. 145

146 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.61: Writing an S-Funtion le using S-Function Builder Block: Data Properties > Output port setup.

1.3. SIMULINK Figure 1.62: Writing an S-Funtion le using S-Function Builder Block: Data Properties > Parameters menu option. Data types are entered at the bottom. Actual parameter values are entered at the top. 147

148 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.63: Writing an S-Funtion le using S-Function Builder Block: Data Type Attributes properties menu.

1.3. SIMULINK Figure 1.64: Writing an S-Funtion le using S-Function Builder Block: Library pane is used to dene the libraries and other les referenced by the S-function. 149

150 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.65: Writing an S-Funtion le using S-Function Builder Block: Outputs logic section.

1.3. SIMULINK

Figure 1.66: Writing an S-Funtion le using S-Function Builder Block: Discrete Updates.

151

152 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.67: Writing an S-Funtion le using S-Function Builder Block: Build the S-function for a dynamically loadable executbale code. This step can also be performed by executing the mex lename command in the Matlab command window.

1.3. SIMULINK Figure 1.68: Using an S-funtion le in a Simulink model: copy S-function block into the model from User-Dened Functions library of Simulink. Then double-click on it. Then type the name of the S-function le in the name area, and provide parameters (if any). When you click apply, the S-function block should reect the correct number of input and output ports. Finally, connect the input and output signals to the rest of the model. The system is ready for simulation. 153

154 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.69: Simulation results: top two plots are commanded and actual positions, bottom plot is the controller output.

1.3. SIMULINK

155

Creating C S-Functions Using Hand Written C S-Function via Template Files When creating C S-functions using hand-written code, there are two alternatives: 1. Hand-write the code into the wrapper functions generated by S-Function Builder block. In other words, directly edit the content of these les with a text editor. Then generate the *.mexw32 le using the mex command line utility, >>mex sfun_PID.c sfun_PID_wrapper.c

If you change the number of input, output, parameters, and sampling method or sampling period, it is best to regenerate the source les using the Build button of S-Function Builder block. Then edit or copy the logic content to the wrapper functions directly using a text editor, and then re-compile the les using the mex command line utility. In other words, we use the S-Function Builder block to generate the template les for us for the input/output/parameters/sampling-peroid information, then we hand-code our logic into the wrapper functions. 2. Hand-write the code using one of the template example les provided by Matlab. The template C S-function les, provided by Matlab installation, has the structure required for S-functions. Two versions of the template les are provided at the following directory: one is the basic version of the template S-function C-le, the other is more detailed and fully commented version. matlabroot/simulink/src/sfuntmpl_basic.c matlabroot/simulink/src/sfuntmpl_doc.c

The same les can also be accessed through the Simulink graphical interface as follows >> sfuncdemos

Then, select C-le S-functions group, then select the desired C-MEX Template le. Finally, edit the template le to code the desired logic (Fig.??). We will discuss the rst method in detail here, using the S-Function Builder tool, then edit the code in the wrapper functions directly using a text editor instead of using the panes of the Dialog Box of the S-Function Builder block, and then generate the *.mexw32 le using the command line mex utility. The following points should be kept in mind in editing the code in the source les:

156

CHAPTER 1. MATLAB AND ITS TOOLS

1. Inputs, output and parameters (i.e. gains) to/from the S-function: their names and size are specied in the #dene section of the le, i.e. in sfun PID.c, and these values are used in the function, mdlInitializeSizes( ... ) . 2. sampling method and sampling period are specied in the #dene section of the le sfun PID.c and these values are used in the function mdlInitializeSampleTimes(...), initial conditions of the states (if states used) specied in function mdlInitializeConditions( .... ) . 3. desired logic code entered, referencing the inputs/outputs and parameters. This code is entered in one or more of the following functions; including the local pointer variable denitions to access to the inputs, outputs, states and parameters, sfun PID Outputs wrapper(...), sfun PID Update wrapper(...), sfun PID Derivatives wrapper(....). which are same functions discussed in the earlier section for Creating S-Functions Using S-Function Builder. The S-function template is shown below to give the developer an idea about its format.
/* * Filename: sfun_PID.c */ /*=============================* * Required S-function header * *=============================*/ #define S_FUNCTION_NAME sfun_PID #define S_FUNCTION_LEVEL 2 #include "simstruc.h" /*==============================* * S-function methods * *==============================*/ static void mdlInitializeSizes(SimStruct *S) { ... } static void mdlInitializeSampleTimes(SimStruct *S) {

1.3. SIMULINK

157

.... } static void mdlInitializeConditions(SimStruct *S) { .... } static void mdlOutputs(SimStruct *S, int_T tid) { /* Your logic or call to wrapper function */

} static void mdlUpdate(SimStruct *S, int_T tid) { /* Your logic or call to wrapper function */ } static void mdlDerivatives(SimStruct *S) { /* Your logic or call to wrapper function */ } static void mdlTerminate(SimStruct *S) { /* Empty function is OK. */ }

/*=============================* * Required S-function trailer * *=============================*/ #ifdef MATLAB_MEX_FILE #include "simulink.c" #else #include "cg_sfun.h" #endif /* Is this file being compiled as a MEX-file? */ /* MEX-file interface mechanism */ /* Code generation registration function */

158

CHAPTER 1. MATLAB AND ITS TOOLS

Below is the complete source code generated by S-Function Builder block, and the content edited in the wrapper functions.
/* * File: sfun_PID.c * * * * --- THIS FILE GENERATED BY S-FUNCTION BUILDER: 3.0 --* * This file is an S-function produced by the S-Function * Builder which only recognizes certain fields. Changes made * outside these fields will be lost the next time the block is * used to load, edit, and resave this file. This file will be overwritten * by the S-function Builder block. If you want to edit this file by hand, * you must change it only in the area defined as: * * %%%-SFUNWIZ_defines_Changes_BEGIN * #define NAME replacement text * %%% SFUNWIZ_defines_Changes_END * * DO NOT change NAME--Change the replacement text only. * * For better compatibility with the Real-Time Workshop, the * "wrapper" S-function technique is used. This is discussed * in the Real-Time Workshop Users Manual in the Chapter titled, * "Wrapper S-functions". * * ------------------------------------------------------------------------* | See matlabroot/simulink/src/sfuntmpl_doc.c for a more detailed template | * ------------------------------------------------------------------------* Created: Thu Jun 24 12:31:59 2010 * * */

#define S_FUNCTION_NAME sfun_PID #define S_FUNCTION_LEVEL 2 /*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ /* %%%-SFUNWIZ_defines_Changes_BEGIN --- EDIT HERE TO _END */ #define NUM_INPUTS 3 /* Input Port 0 */ #define IN_PORT_0_NAME yd #define INPUT_0_WIDTH 1 #define INPUT_DIMS_0_COL 1 #define INPUT_0_DTYPE real_T #define INPUT_0_COMPLEX COMPLEX_NO #define IN_0_FRAME_BASED FRAME_NO #define IN_0_DIMS 1-D #define INPUT_0_FEEDTHROUGH 1 #define IN_0_ISSIGNED 0

1.3. SIMULINK
#define IN_0_WORDLENGTH 8 #define IN_0_FIXPOINTSCALING 1 #define IN_0_FRACTIONLENGTH 9 #define IN_0_BIAS 0 #define IN_0_SLOPE 0.125 /* Input Port 1 */ #define IN_PORT_1_NAME y #define INPUT_1_WIDTH 1 #define INPUT_DIMS_1_COL 1 #define INPUT_1_DTYPE real_T #define INPUT_1_COMPLEX COMPLEX_NO #define IN_1_FRAME_BASED FRAME_NO #define IN_1_DIMS 1-D #define INPUT_1_FEEDTHROUGH 1 #define IN_1_ISSIGNED 0 #define IN_1_WORDLENGTH 8 #define IN_1_FIXPOINTSCALING 1 #define IN_1_FRACTIONLENGTH 9 #define IN_1_BIAS 0 #define IN_1_SLOPE 0.125 /* Input Port 2 */ #define IN_PORT_2_NAME ydot #define INPUT_2_WIDTH 1 #define INPUT_DIMS_2_COL 1 #define INPUT_2_DTYPE real_T #define INPUT_2_COMPLEX COMPLEX_NO #define IN_2_FRAME_BASED FRAME_NO #define IN_2_DIMS 1-D #define INPUT_2_FEEDTHROUGH 1 #define IN_2_ISSIGNED 0 #define IN_2_WORDLENGTH 8 #define IN_2_FIXPOINTSCALING 1 #define IN_2_FRACTIONLENGTH 9 #define IN_2_BIAS 0 #define IN_2_SLOPE 0.125 #define NUM_OUTPUTS 1 /* Output Port 0 */ #define OUT_PORT_0_NAME u #define OUTPUT_0_WIDTH 1 #define OUTPUT_DIMS_0_COL 1 #define OUTPUT_0_DTYPE real_T #define OUTPUT_0_COMPLEX COMPLEX_NO #define OUT_0_FRAME_BASED FRAME_NO #define OUT_0_DIMS 1-D #define OUT_0_ISSIGNED 1 #define OUT_0_WORDLENGTH 8 #define OUT_0_FIXPOINTSCALING 1 #define OUT_0_FRACTIONLENGTH 3 #define OUT_0_BIAS 0 #define OUT_0_SLOPE 0.125

159

160
#define NPARAMS 3 /* Parameter 1 */ #define PARAMETER_0_NAME Kp #define PARAMETER_0_DTYPE real_T #define PARAMETER_0_COMPLEX COMPLEX_NO /* Parameter 2 */ #define PARAMETER_1_NAME Ki #define PARAMETER_1_DTYPE real_T #define PARAMETER_1_COMPLEX COMPLEX_NO /* Parameter 3 */ #define PARAMETER_2_NAME Kd #define PARAMETER_2_DTYPE real_T #define PARAMETER_2_COMPLEX COMPLEX_NO #define #define #define #define #define SAMPLE_TIME_0 NUM_DISC_STATES DISC_STATES_IC NUM_CONT_STATES CONT_STATES_IC 0.001 1 [1] 0 [0]

CHAPTER 1. MATLAB AND ITS TOOLS

#define SFUNWIZ_GENERATE_TLC 1 #define SOURCEFILES "__SFB__" #define PANELINDEX 6 #define USE_SIMSTRUCT 0 #define SHOW_COMPILE_STEPS 0 #define CREATE_DEBUG_MEXFILE 0 #define SAVE_CODE_ONLY 0 #define SFUNWIZ_REVISION 3.0 /* %%%-SFUNWIZ_defines_Changes_END --- EDIT HERE TO _BEGIN */ /*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ #include "simstruc.h" #define PARAM_DEF0(S) ssGetSFcnParam(S, 0) #define PARAM_DEF1(S) ssGetSFcnParam(S, 1) #define PARAM_DEF2(S) ssGetSFcnParam(S, 2) #define IS_PARAM_DOUBLE(pVal) (mxIsNumeric(pVal) && !mxIsLogical(pVal) &&\ !mxIsEmpty(pVal) && !mxIsSparse(pVal) && !mxIsComplex(pVal) && mxIsDouble(pVal)) extern void sfun_PID_Outputs_wrapper(const real_T *yd, const real_T *y, const real_T *ydot, real_T *u , const real_T *xD, const real_T *Kp, const int_T p_width0, const real_T *Ki, const int_T p_width1, const real_T *Kd, const int_T p_width2); extern void sfun_PID_Update_wrapper(const real_T *yd, const real_T *y, const real_T *ydot, const real_T *u , real_T *xD, const real_T *Kp, const int_T p_width0,

1.3. SIMULINK
const real_T *Ki, const int_T p_width1, const real_T *Kd, const int_T p_width2); /*====================* * S-function methods * *====================*/ #define MDL_CHECK_PARAMETERS #if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE) /* Function: mdlCheckParameters ============================================= * Abstract: * Validate our parameters to verify they are okay. */ static void mdlCheckParameters(SimStruct *S) { #define PrmNumPos 46 int paramIndex = 0; bool validParam = false; char paramVector[] ={1,2,3}; static char parameterErrorMsg[] ="The data type and/or complexity of parameter does not match the information " "specified in the S-function Builder dialog. For non-double parameters you will need to cast them using int8, int16," "int32, uint8, uint16, uint32 or boolean."; /* All parameters must match the S-function Builder Dialog */

161

{ const mxArray *pVal0 = ssGetSFcnParam(S,0); if (!IS_PARAM_DOUBLE(pVal0)) { validParam = true; paramIndex = 0; goto EXIT_POINT; } } { const mxArray *pVal1 = ssGetSFcnParam(S,1); if (!IS_PARAM_DOUBLE(pVal1)) { validParam = true; paramIndex = 1; goto EXIT_POINT; } } { const mxArray *pVal2 = ssGetSFcnParam(S,2); if (!IS_PARAM_DOUBLE(pVal2)) { validParam = true; paramIndex = 2; goto EXIT_POINT; }

162
}

CHAPTER 1. MATLAB AND ITS TOOLS

EXIT_POINT: if (validParam) { parameterErrorMsg[PrmNumPos] = paramVector[paramIndex]; ssSetErrorStatus(S,parameterErrorMsg); } return; } #endif /* MDL_CHECK_PARAMETERS */ /* Function: mdlInitializeSizes =============================================== * Abstract: * Setup sizes of the various vectors. */ static void mdlInitializeSizes(SimStruct *S) { DECL_AND_INIT_DIMSINFO(inputDimsInfo); DECL_AND_INIT_DIMSINFO(outputDimsInfo); ssSetNumSFcnParams(S, NPARAMS); /* Number of expected parameters */ #if defined(MATLAB_MEX_FILE) if (ssGetNumSFcnParams(S) == ssGetSFcnParamsCount(S)) { mdlCheckParameters(S); if (ssGetErrorStatus(S) != NULL) { return; } } else { return; /* Parameter mismatch will be reported by Simulink */ } #endif ssSetNumContStates(S, NUM_CONT_STATES); ssSetNumDiscStates(S, NUM_DISC_STATES); if (!ssSetNumInputPorts(S, NUM_INPUTS)) return; /*Input Port 0 */ ssSetInputPortWidth(S, 0, INPUT_0_WIDTH); /* */ ssSetInputPortDataType(S, 0, SS_DOUBLE); ssSetInputPortComplexSignal(S, 0, INPUT_0_COMPLEX); ssSetInputPortDirectFeedThrough(S, 0, INPUT_0_FEEDTHROUGH); ssSetInputPortRequiredContiguous(S, 0, 1); /*direct input signal access*/ /*Input Port 1 */ ssSetInputPortWidth(S, 1, INPUT_1_WIDTH); /* */ ssSetInputPortDataType(S, 1, SS_DOUBLE); ssSetInputPortComplexSignal(S, 1, INPUT_1_COMPLEX); ssSetInputPortDirectFeedThrough(S, 1, INPUT_1_FEEDTHROUGH); ssSetInputPortRequiredContiguous(S, 1, 1); /*direct input signal access*/ /*Input Port 2 */ ssSetInputPortWidth(S, 2, INPUT_2_WIDTH); /* */ ssSetInputPortDataType(S, 2, SS_DOUBLE);

1.3. SIMULINK
ssSetInputPortComplexSignal(S, 2, INPUT_2_COMPLEX); ssSetInputPortDirectFeedThrough(S, 2, INPUT_2_FEEDTHROUGH); ssSetInputPortRequiredContiguous(S, 2, 1); /*direct input signal access*/

163

if (!ssSetNumOutputPorts(S, NUM_OUTPUTS)) return; ssSetOutputPortWidth(S, 0, OUTPUT_0_WIDTH); ssSetOutputPortDataType(S, 0, SS_DOUBLE); ssSetOutputPortComplexSignal(S, 0, OUTPUT_0_COMPLEX); ssSetNumSampleTimes(S, 1); ssSetNumRWork(S, 0); ssSetNumIWork(S, 0); ssSetNumPWork(S, 0); ssSetNumModes(S, 0); ssSetNumNonsampledZCs(S, 0); /* Take care when specifying exception free code - see sfuntmpl_doc.c */ ssSetOptions(S, (SS_OPTION_EXCEPTION_FREE_CODE | SS_OPTION_USE_TLC_WITH_ACCELERATOR | SS_OPTION_WORKS_WITH_CODE_REUSE)); } # define MDL_SET_INPUT_PORT_FRAME_DATA static void mdlSetInputPortFrameData(SimStruct *S, int_T port, Frame_T frameData) { ssSetInputPortFrameData(S, port, frameData); } /* Function: mdlInitializeSampleTimes ========================================= * Abstract: * Specifiy the sample time. */ static void mdlInitializeSampleTimes(SimStruct *S) { ssSetSampleTime(S, 0, SAMPLE_TIME_0); ssSetOffsetTime(S, 0, 0.0); } #define MDL_INITIALIZE_CONDITIONS /* Function: mdlInitializeConditions ======================================== * Abstract: * Initialize the states */ static void mdlInitializeConditions(SimStruct *S) { real_T *xD = ssGetRealDiscStates(S);

xD[0] =

0.0 ;

} #define MDL_SET_INPUT_PORT_DATA_TYPE

164

CHAPTER 1. MATLAB AND ITS TOOLS

static void mdlSetInputPortDataType(SimStruct *S, int port, DTypeId dType) { ssSetInputPortDataType( S, 0, dType); } #define MDL_SET_OUTPUT_PORT_DATA_TYPE static void mdlSetOutputPortDataType(SimStruct *S, int port, DTypeId dType) { ssSetOutputPortDataType(S, 0, dType); } #define MDL_SET_DEFAULT_PORT_DATA_TYPES static void mdlSetDefaultPortDataTypes(SimStruct *S) { ssSetInputPortDataType( S, 0, SS_DOUBLE); ssSetOutputPortDataType(S, 0, SS_DOUBLE); } /* Function: mdlOutputs ======================================================= * */ static void mdlOutputs(SimStruct *S, int_T tid) { const real_T *yd = (const real_T*) ssGetInputPortSignal(S,0); const real_T *y = (const real_T*) ssGetInputPortSignal(S,1); const real_T *ydot = (const real_T*) ssGetInputPortSignal(S,2); real_T *u = (real_T *)ssGetOutputPortRealSignal(S,0); const real_T *xD = ssGetDiscStates(S); const int_T p_width0 = mxGetNumberOfElements(PARAM_DEF0(S)); const int_T p_width1 = mxGetNumberOfElements(PARAM_DEF1(S)); const int_T p_width2 = mxGetNumberOfElements(PARAM_DEF2(S)); const real_T *Kp = mxGetData(PARAM_DEF0(S)); const real_T *Ki = mxGetData(PARAM_DEF1(S)); const real_T *Kd = mxGetData(PARAM_DEF2(S)); sfun_PID_Outputs_wrapper(yd, y, ydot, u, xD, Kp, p_width0, Ki, p_width1, Kd, p_width2); } #define MDL_UPDATE /* Change to #undef to remove function */ /* Function: mdlUpdate ====================================================== * Abstract: * This function is called once for every major integration time step. * Discrete states are typically updated here, but this function is useful * for performing any tasks that should only take place once per * integration step. */ static void mdlUpdate(SimStruct *S, int_T tid) { real_T *xD = ssGetDiscStates(S); const real_T *yd = (const real_T*) ssGetInputPortSignal(S,0); const real_T *y = (const real_T*) ssGetInputPortSignal(S,1); const real_T *ydot = (const real_T*) ssGetInputPortSignal(S,2); real_T *u = (real_T *)ssGetOutputPortRealSignal(S,0); const int_T p_width0 = mxGetNumberOfElements(PARAM_DEF0(S)); const int_T p_width1 = mxGetNumberOfElements(PARAM_DEF1(S));

1.3. SIMULINK
const const const const int_T real_T real_T real_T p_width2 = mxGetNumberOfElements(PARAM_DEF2(S)); *Kp = mxGetData(PARAM_DEF0(S)); *Ki = mxGetData(PARAM_DEF1(S)); *Kd = mxGetData(PARAM_DEF2(S));

165

sfun_PID_Update_wrapper(yd, y, ydot, u, }

xD, Kp, p_width0, Ki, p_width1, Kd, p_width2);

/* Function: mdlTerminate ===================================================== * Abstract: * In this function, you should perform any actions that are necessary * at the termination of a simulation. For example, if memory was * allocated in mdlStart, this is the place to free it. */ static void mdlTerminate(SimStruct *S) { } #ifdef MATLAB_MEX_FILE #include "simulink.c" #else #include "cg_sfun.h" #endif /* Is this file being compiled as a MEX-file? */ /* MEX-file interface mechanism */ /* Code generation registration function */

/**********************************************************************************************/ /* * * --- THIS FILE GENERATED BY S-FUNCTION BUILDER: 3.0 --* * This file is a wrapper S-function produced by the S-Function * Builder which only recognizes certain fields. Changes made * outside these fields will be lost the next time the block is * used to load, edit, and resave this file. This file will be overwritten * by the S-function Builder block. If you want to edit this file by hand, * you must change it only in the area defined as: * * %%%-SFUNWIZ_wrapper_XXXXX_Changes_BEGIN * Your Changes go here * %%%-SFUNWIZ_wrapper_XXXXXX_Changes_END * * For better compatibility with the Real-Time Workshop, the * "wrapper" S-function technique is used. This is discussed * in the Real-Time Workshop Users Manual in the Chapter titled, * "Wrapper S-functions". * * Created: Thu Jun 24 12:31:59 2010 */

/* * Include Files

166

CHAPTER 1. MATLAB AND ITS TOOLS

* */ #if defined(MATLAB_MEX_FILE) #include "tmwtypes.h" #include "simstruc_types.h" #else #include "rtwtypes.h" #endif /* %%%-SFUNWIZ_wrapper_includes_Changes_BEGIN --- EDIT HERE TO _END */ #include <math.h> /* %%%-SFUNWIZ_wrapper_includes_Changes_END --- EDIT HERE TO _BEGIN */ #define u_width 1 #define y_width 1 /* * Create external references here. * */ /* %%%-SFUNWIZ_wrapper_externs_Changes_BEGIN --- EDIT HERE TO _END */ /* extern double func(double a); */ /* %%%-SFUNWIZ_wrapper_externs_Changes_END --- EDIT HERE TO _BEGIN */ /* * Output functions * */ void sfun_PID_Outputs_wrapper(const real_T *yd, const real_T *y, const real_T *ydot, real_T *u , const real_T *xD, const real_T *Kp, const int_T p_width0, const real_T *Ki, const int_T p_width1, const real_T *Kd, const int_T p_width2) { /* %%%-SFUNWIZ_wrapper_Outputs_Changes_BEGIN --- EDIT HERE TO _END */ /** This is the line edited (added) by the developer for the PID algorithm**/

u[0]=Kp[0]*(yd[0]-y[0])+Ki[0]*xD[0]+ Kd[0]*(-ydot[0]);

/* %%%-SFUNWIZ_wrapper_Outputs_Changes_END --- EDIT HERE TO _BEGIN */ } /* * Updates function * */ void sfun_PID_Update_wrapper(const real_T *yd, const real_T *y,

1.3. SIMULINK
const real_T *ydot, const real_T *u , real_T *xD, const real_T *Kp, const int_T p_width0, const real_T *Ki, const int_T p_width1, const real_T *Kd, const int_T p_width2) { /* %%%-SFUNWIZ_wrapper_Update_Changes_BEGIN --- EDIT HERE TO _END */ /** This is the line edited (added) by the developer for the PID algorithm**/

167

xD[0] = xD[0] + (yd[0]-y[0]) ;

/* %%%-SFUNWIZ_wrapper_Update_Changes_END --- EDIT HERE TO _BEGIN */ }

168 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.70: Writing an S-Function le by directly modifying a template C-MEX le

1.3. SIMULINK Creating MEX-type S-Functions in C-language using Legacy Code

169

Matlabs Legacy Code Tool (LCT) is used integrate existing C-code as an S-function into Simulink. It is, however, recommended to use the S-Function Builder or Hand Written Code method to integrate C-code into your Simulink models using S-functions instead of LCT. Using M-script le commands that use LCT function calls and some data structure assignments, existing C code is transformed into S-function C-MEX les. The S-function development using Legacy Code Tool (LCT) involves four basic steps using a script *.m le, 1. specifcy the legacy code interface (source les and associated data). This is typically done via a Matlab m-script le involving legacy_code(....) function calls to Legacy Code Tool with various arguments. 2. generate the C S-function le. 3. compile the C S-function le into MEX le, *.mexw32. 4. generate a masked block for the S-function to include in Simulink. This is an optional step since masking a block is an option, not a requirement in Simulink. In order to use the S-function in a Simulink model, the generated *.mexw32 le is then linked to an S-function block using the dialog box. Specify the legacy code interface (source les and associated data): Functions developed with Legacy Code Tool (LCT) take a specic data structure as the argument. The data structure describes all the information needed to integrate with the legacy code. First, we must create LCT data structure, i.e. named def, by entering the following command in the Matlab (in command-line or in M-script le),

>> def = legacy_code(initialize)

The data structure def displays its elds in the Matlab command window as follows,
def = SFunctionName: OutputFcnSpec: StartFcnSpec: TerminateFcnSpec: HeaderFiles: SourceFiles: IncPaths: {} {} {} /* name of the S-function to be generated by LCT /* name of the function that S-function calls at /* .......................................... at /*............................................at /* Names of header files */ /* Names of source files */ /* Include File Paths */ */ each step */ the start */ the end */

170
SrcPaths: LibPaths: SampleTime: Options:

CHAPTER 1. MATLAB AND ITS TOOLS


{} /* Source File Paths {} /* Library file Paths inherited [1x1 struct] */ */

After initializing this data structure, the developer has to assign its properties to values corresponding to the legacy code that is being integrated into Simulink as an S-function block. These steps should be put into an *.m le and executed or entered directly in the Matlab command window.
% filename: LCT_Test.m def=legacy_code(initialize); % def.SourceFiles = {PID1.c} ; % def.HeaderFiles = {PID1.h} ; % def.SFunctionName = sfun_PID1 ; % def.OutputFcnSpec = double u=PID1(double legacy_code(sfcn_cmex_generate,def) ; % This step generates: ex_sfun_PID1.c file. legacy_code(compile,def); % % This step compiles the above file and generates MEX file: ex_sfun_PID1.mexw32 Initialize the LCT data structure: def C-Source file: *.c C-Header file: *.h Populate the data structure. yd, double y, double ydot,double Kp, double Ki, double Kd) ;

legacy_code(slblock_generate, def) ; % Creates a Masked Block for the S-function, and displays the % function prototype to show the usage. % You can add the block to your Simulink model with % copy/paste.

Once this step is completed successfully, the S-function can be included in any Simulink model using the S-function block. Notice that in this case, for the PID controller example, the parameters Kp, Ki, Kd and input signals yd, y, ydot should be provided as input signals (inport) to the S-function block. The output signal u should be connected to other part of the Simulink model. The parameters list in the S-function block interface should not be used. The source les can have the following content. The following LCT function calls are provided for reference purposes;

1.3. SIMULINK

171

legacy_code(help) def = legacy_code(initialize) legacy_code(sfcn_cmex_generate, def) legacy_code(slblock_generate, def, modelname) legacy_code(compile, def, compilerOptions) legacy_code(sfcn_tlc_generate, def) % generates a TLC file for the S-function generated by % based on the data structure. This option is relevant % a) Force Accelerator mode in Simulink to use the TLC % code of the generated S-function. % b) Use Real-Time Workshop to generate code from your

the Legacy Code Tool if you want to inlining Simulink model.

legacy_code(rtwmakecfg_generate, def) % generates an rtwmakecfg.m file for the S-function generated % by the Legacy Code Tool based on the data structure. % This option is relevant only if you use Real-Time Workshop to generate code % from your Simulink model. legacy_code(backward_compatibility) % automatically updates syntax for using Legacy Code Tool, % as made available from MATLAB Central in releases before R2006b, % to the supported syntax described in this reference page and in % Integrating Existing C Functions into Simulink Models % with the Legacy Code Tool in Writing S-Functions.
/***********************************/ /* Filename: PID1.c */ #include "PID1.h" double PID1(double yd, double y, double ydot, double Kp, double Ki, double Kd) { static double e_i = 0.0 ; double u ; e_i = e_i + (yd - y) ; u = Kp * (yd-y) + Ki * e_i + Kd * (-ydot) ; return(u) ; }

172
/***********************************/ /* Filename: PID1.h */ #ifndef _PID1_H #define _PID1_H

CHAPTER 1. MATLAB AND ITS TOOLS

double PID1(double yd, double y, double ydot, double Kp, double Ki, double Kd) ; #endif /***********************************/

Example: Creating and Using S-Function via Legacy Code Tool Example of creating an S-function using Legacy Code Tool (LCT) and the use of the Sfunction in a Simulink model is shown in Figure ??. The rst step is to create S-function MEX le, in this case lename is ex sfun myfun.mexw32. This involves a script M-le using the LCT commands, the source code for the C-le, and running the M-script le to generate the S-function MEX le (ex sfun myfun.mexw32). The second step is to link the S-function in a Simulink model through the use of S-Function Block.

1.3. SIMULINK

173

Figure 1.71: Writing an S-Function le by use of Legacy Code Tool (LCT): C source and header les.

174

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.72: Writing an S-Function le by use of Legacy Code Tool (LCT) to generate and compile the S-function les.

1.3. SIMULINK Figure 1.73: Example of les involved in writing an S-function using Legacy Code Tool (LCT): on the left, the Simulink model les using the S-function created by the LCT. On the right, the text fource les for creating the S-function MEX le: the script-m le to create MEX le for S-function, and C-source le which the script le uses to create a another source le ex sfun myfun, and Matlab command line command to run the script-m le. On the far right corner, the result of the simulation of the Simulink model is shown which conrms the correct operation of the S-function. 175

176

CHAPTER 1. MATLAB AND ITS TOOLS

1.4

Stateow

Stateow (SF) is the graphical modeling software as part of the Matlab that is used to model event-driven systems. Stateow is basically a Matlab/Simulink tool to model the so called nite state machine algorithms. Control logic or process dynamic models, which have various modes of operation and are event-driven, are best expressed in Stateow rather than in Simulink (Fig.??). In typical usage, a SF model is a block in a Simulink model. The SF model is called the chart. The chart is used to represent various modes of operation. Supervisory aspects of a control algorithm is best implemented in Stateow charts, whereas dynamic input-output relationships (dierential equations, dierence equations, transfer functions) are best described in Simulink blocks. The mathematical modeling paradigm in Stateow is based on the concept of operating modes, which are called the states in SF, and the events, conditions which dene the transitions between states, as well as actions taken in the states and during transitions. The programmer need to express the problem at hand in these terms; states, events, conditions, transitions, and actions. Before a simulation or target code generation, Stateow performs the following steps on a SF model, 1. Check (parse) the model for its consistency and for errors. 2. Generate C-code from the model for simulation or RTW target. 3. Process the C-code to generate the MEX le for simulation . The prerequisite programs for Stateow are; 1. Matlab 2. Simulink 3. Stateow Coder 4. C Compiler (LCC compiler is included with Matlab installation). For the compiler to work, run the following once in your Matlab command window, >> mex -setup

and select the desired C- compiler from the available list. Stateow Coder works with RTW to generate portable C code for Simulink models that includes Stateow charts. Stateow is started from Matlab command window by typing (Fig.??) >> stateflow

1.4. STATEFLOW

177

Figure 1.74: Stateow and its relationship to Simulink.

178

CHAPTER 1. MATLAB AND ITS TOOLS

This brings up the sib (Stateow library) window. By double clicking on the Chart icon, we bring up the StateFlow Editor window, where a SF chart is designed (Fig.??). A pop-up menu can be displayed and content changed for any SF chart component by pointing on the component and right-clicking the mouse. Stateow Chart and Truth Table blocks can also be accessed under Simulink toolboxes, named Stateow. Double clicking on a SF chart in a Simulink model also brings up the Stateow Editor with the details of the SF model in the editor. Stateow Editor window and its various menu options are shown in Figs. ?? and ??. In the File > Chart Properties, select Classic, Inherited and enable C-bit operations. Checking this box instructs the Stateow to interpert C bitwise operators ( &, |, >>, and , , so on) in action language statements and encode them as C bitwise operations. If this box is not selected, the following occurs: & and | are interpreted as logical operators. In the File > Machine Properties provides a window that allows us to provide documentation for the chart. The development tools for Stateow includes the 1. Stateow Editor 2. Debugger, and 3. Model Explorer. The Stateow Editor is used to graphically build the SF model. The Debugger is used to debug the SF model during simulation, and also allows animation of states in order to visually assist the developer evaluate the operation of the SF chart. Model Explorer is used to view the non-graphical components of a SF chart: data and events. It is important to recognize the graphical components (states, transitions, action statements) and nongraphical components (data and events) of a SF chart.

1.4. STATEFLOW

179

Figure 1.75: Stateow windows in Matlab.

180

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.76: Stateow Editor window and its tools. On the Object palette the graphical components of the Stateow chart are displayed: state, history junciton, default transition, connective junction, truth table, function call (may used to implement Actions), embedded Matlab functions (may be used to implement Actions), and box for graphical grouping.

1.4. STATEFLOW

181

Figure 1.77: Stateow Editor Menu.

182

CHAPTER 1. MATLAB AND ITS TOOLS

1.4. STATEFLOW

183

A Stateow chart may be triggered at each sampling period or by events. The source and nature of each event can be dened in the SF chart. In control applications, the most common source of trigger method for Stateow charts is a periodic timer, i.e. at a constant sampling period such as every 10msec. Each mode can be considered as a state. The whole logic, or the chart, is a collection of states plus the actions and conditions that may be executed in each state. The actions and conditions are also used to dene the transitions between states. SF state concept support hiearchy: states can be grouped in a hierarchy. The group of states can be exclusive (also called OR states, meaning only one of the states in the group can be active at any given time, i.e. a switch state can be either ON or OFF, not both at the same time) or parallel (also called AND states, meaning the states in the parallel group can be active concurrently during the same same sampling period. For instance, assume we have ON and OFF states for a FAN motor and a HEATER. The FAN can be ON and the HEATER can be ON at the same time. The states of FAN motor and HEATER motor are parallel states. The states of FAN motor (ON state and OFF state) are exclusive (OR states), clearly meaning that a FAN motor can not be ON and OFF at the same time. Same thing applies for the HEATER motor. Grouping states is a graphical visual aid, it does not make any dierence in the logic of the chart. It simply hides the sub-states in the hierarchy, making the visual display less crowded. To group a state and hide its sub-states graphically, right-clicking on the state, and then select Make Contents > Grouped from the resulting shortcut menu. You must ungroup a superstate to select objects within the superstate. To ungroup a state, double-click it or its border or select Make Contents > Ungrouped from the shortcut menu. Once the code is auto-code generated, both Simulink and StateFlow graphical programs are converted to C-language and then compiled/linked into an executable code. This code in reality is executed sequentially in the target hardware or during the o-line simulation. However, within a given sampling period parallel states can all be executed and be active. Hence giving the illusion that they are executed at the same time concurrently. This is the same case when multi-tasking is implemented on a microcomputer. The typical steps involved in developing a SF chart is shown in Fig.??. Step 1: Input and outputs between SF and Simulink. The rst step in designing a typical SF chart, is to plan it as part of a Simulink model, and then decide on the inputoutput data and events between the SF block and Simulink model. SF chart interacts with Simulink through its input and output signals. The input and output signals can be data

184

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.79: Typical steps involved in designing a Stateow chart as part of a Simulink model. or events needed by SF and Simulink. In Simulink, select Stateow from the Simulink Library Browser, then double-click on it. This will bring up the Stateow blocks: Chart, Truth Table. Select Chart and dragand-drop it in the Simulink model. Now double-click on the Chart bock in the Simulink model to edit its content using Stateow Editor. In order to dene I/O between SF and Simulink, use Stateow Editor > Add > Data > Input from Simulink or Stateow Editor >Add > Data > Output to Simulink menu items in SF editor window. The user then will need to ll in the data in the user interface provided, i.e. provide the name of the data variable, data type, scope etc. Then, Stateow adds input and output ports for each Input from Simulink and Output to Simulink data denitions. The port number is assigned in the order they are created, but can be changed by explicitly specifying the port number in the denition menu. Step 2: States, their hierarchy and decomposition. How many states are needed, their hierarchy in terms of super-states and sub-states (parent-child relationship), and whether they are exclusive (OR-states) or parallel (AND-states, concurrent) should be de-

1.4. STATEFLOW

185

cided. Consider the operation of your control logic or process model, and decide on modes of operation. In general, each mode of operation is assigned a state. It certainly is possible to build SF charts without states, but that is a rare case. Then decide on the number of states, their hiearchy (super states, sub-states, like a parent-child relation) using a tree structure analogy. Then, decide on the decomposition of each state, meaning whether they are exclusive (OR) or parallel (AND) states (Fig.??). In a state hierarchy, among the collection of OR states, only one of them can be active at a given time, whereas multiple AND states can be active concurrently (although they are executed still sequentially. The order of the sequential execution of parallel states (AND states) can be left to default or specied by the designer. In order to dene the states as parallel in a hierarchy, right-click mouse inside the super state where the parallel states will be dened, then select Decomposition > Parallel (AND) options from pop-up menu, then save the model. Then when you add new states at the level, they will be added as parallel states. In SF editor, exclusive (OR) states are displayed with solid lined rectangles, whereas parallel (AND) states are displayed with dotten lined rectangles. Step 3: Dene State Actions and Variables. The hierarchy of states describe the tree type structure of the logic. The actual logic (actions) and the data acted on in each state denes the details of the algorithm. Actions can be present either in the state logic or in the transitions. A transition can support two dierent actions a condition action, and a transition action. There are four dierent categories of actions in each state (Fig.??) : entry: action1(); during: action21(); action22(); exit: action3(); on_"EventName1": action41(); action42(); on_"EventName2": action43(); action44(); action45(); % executed when transition from that state to another state % occurs and this state is exited % executed on every occurance of the named event % executed once when the state is activated % executed every sampling period while the state is active

% executed on every occurance of the named event

186

CHAPTER 1. MATLAB AND ITS TOOLS

When a state is active, those actions are executed depending on the condition of the state. For instance, on the rst entry to the state, the actions in the entry: block are executed. After that, the actions in the during: block are executed during the next sampling period. When a transition occurs from the currently active state, then the actions in the exit: block are executed before the program transitions to another state. Multiple function calls can be dened for each category. Multiple on EventName blocks can be dened. This allows us to dene a unique set of actions for each event. In addition to actions, we may need to dene variables (local or persistent) in each state to keep track of data. It may be that we only need the input and output data, and no local (or persistent) data may be needed. Step 4: Dene the Transistions Between States. So far we dened a state hiearchy and actions within those states. We also need to dene the logic (actions and conditions) to make the transitions between those states. Transitions are the logical ow paths between dierent states. To simplify the logic, it is adviseable to exercise modular programming practice and plan transitions between states at the same hiearchy level. Otherwise, the transition logic may look like a spaghetti code which means it is dicult to understand and maintain. Each transition may have a condition which must be true for the transition to occur, and an action that is executed during the transition before the control is passed to the next state. These transition conditions and actions are expressed with a notation on the transition path in text format. At every hierarcy of states, there should be a default transition dened. This transition would be used in case of ambiguity on which state to activate. This often happens on start-up conditions. For every level of exclusive OR-states, there should be a default transions dened as a good programming practice. Although this is strictly not required, it is a good programming practice to clearly dene which state will be activated under unclear conditions, i.e. on power-up. Transition labels are dened in the following syntax (Fig.??),

event [condition]{condition_action}/transition_action

where event denes the event that triggers the transition, [condition] must be true in order for the transition to take place. Then the two sets of actions are performed, if dened. You can specify some, all, or none of the parts of the transition label. Use ... to continue on the next line in dening the transition labels. The condition action is executed as soon as event occurs and condition is true, before determining the target state. The transition action is executed after the target state is detemined. The following rules apply for determining a valid transion from one state to another.

1.4. STATEFLOW

187

Transition Label

Valid Transition If

1. 2. 3. 4. 5.

Event only Event and condition Condition only Action only Nothing specied

Specied event occurs Specied event occurs and the condition is TRUE Any event occurs and the condition is TRUE Any event occurs Any event occurs

Connection junctions are used to provide multiple branch paths for a transition between more than two states. They are equivalent to if-elseif-else decision blocks (Fig.??). History junction provides the information on the most recent active sub-state in a super state or a chart. When a transition occurs to a super state which has its sub states and history junction, the transition occurs to the substate that was active most recently, as a result of the history junction component in the model. History junction remembers the last active sub-state. In other words, history junction overrides the default transition if they both exist in the same state hierarchy (Fig.??). History junction applies only at the hierarchy in which it is placed. Conditions are boolean logical expressions that must result in true or false result. For a transition to occur, the transition condition must be true. Events and data are non-graphical components of the SF chart. Events are dened using the Add > Event menu item in the SF editor. Events can be dened to trigger SF chart, trigger a transition to occur, trigger an action to be executed. Data is signal or local information needed and logic operations are applied to. Data need to be dened in SF charts using Stateow > Add > Data menu item in SF editor. These non-graphical elements of a state can be viewed and displayed by using the Model Explorer. To do so, point to the state, right-click, and select Explorer from the pop-up menu. Step 5: Dene Triggers to the SF Chart. Stateow chart can be executed at a specied rate or can be triggered by an external signal. Triggers are dened as part of events. In SF editor, use Stateow > Add > Event > Input from Simulink to dene a trigger event from Simulink to the SF chart. The signal source and the conditions at which it causes a trigger (i.e. rising edge, falling edge, or both) can be dened. Simulation parameters are set under Stateow > Simulation > Conguration Parameters. Step 6: Simulate . SF chart is normally simulated as part of the Simulink model. However it can also be simulated with its own simplied input and output for debugging purposes.

188

CHAPTER 1. MATLAB AND ITS TOOLS

Step 7: Debug. Graphical animation tools can be enabled to display the active or inactive states as debugging tools. Breakpoints can be set at various points in the SF, such as at the wake-up of the chart, the entry of a state, event occurance . To set break points, enable animation and set the speed of animation, select Stateow Editor > Tools > Debug This brings up a new window with options to set breakpoints, enable/disable animation and the speed of the animation. Most common breakpoints are set at the Chart Entry and State Entry by checking those option boxes. Then the program execution can be controlled with Start, Stop, Step, Break buttons. Example: Consider the Stateow chart in Fig.??. Assume that State X and sub-state X1 is currently active. Then, event bf Ev 1 occurs. Let us review the sequence of execution. 1. Check if condition Cond 1 is TRUE. If it is, execute condition action Cond1 Act. If the Cond 1 is FALSE, nothing further happens. 2. Since event and condition is true, a valid transition exists from state X1 to Y1. 3. State X, during: duringX Action() is executed and completed. 4. State X.X1, exit: exitX X1 Action() is executed and completed. 5. State X.X1 becomes inactive. 6. State X, exit: exitX Action() is executed and completed. 7. State X becomes inactive. 8. Transition action Trans1 Action() is executed and completed. 9. State Y becomes active. 10. State Y, entry: entryY Action() is executed and completed. 11. State Y.Y1 becomes active. 12. State Y.Y1, entry: entryY Y1 Action() is executed and completed. 13. Chart goes back to sleep until it is awakend by another event. The awakening (activation) method of the chart could be a discrete event source or a periodic timer event. 14. When the chart is activated again (i.e. due to a periodic timer event that was setup to activate the chart), then

1.4. STATEFLOW 15. State Y becomes active again. 16. State Y becomes active. 17. State Y, during: duringY Action() is executed and completed. 18. State Y.Y1 becomes active. 19. State Y.Y1, during: duringY Y1 Action() is executed and completed.

189

20. Chart goes back to sleep until it is awakend by another event. This loop continues, until 21. Event Ev 2 occurs. This is a valid transition from state Y.Y1 to state X. 22. State Y, during: duringY Action() is executed and completed. 23. State Y.Y1, exit: exitY Y1 Action() is executed and completed. 24. State Y.Y1 becomes inactive. 25. State Y, exit: exitY Action() is executed and completed. 26. State Y becomes inactive. 27. State X becomes active. 28. State X, entry: entryX Action() is executed and completed. 29. Chart goes back to sleep until it is awakend by another event. The awakening (activation) method of the chart could be a discrete event source or a periodic timer event. In summary, the basic components used in building a Stateow chart can be divided into two categories: 1. Graphical Components (see Fig.??): (a) states (b) transions between states (including the default transitions) (c) actions, some function or logic (used in the states and transitions). User dened functions, embedded Matlab functions and truth tables may be used to implement various action logic. (d) conditions, some logical condition (used in the states and transitions) (e) junctions: connective junctions, history junctions. 2. Non-graphical Components (see Fig.?? under Add menu item):

190

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.80: Two states: X and Y, each with sub-states X1 and Y1, and two transitions dened between them, along with conditions and actions. The states X and Y are exclusive (OR type) states which meabs only one of them can be active at a given time.

1.4. STATEFLOW (a) events (b) data A Stateow char can be triggered by 1. at specied or inherited sampling rate, 2. by a signal used for trigger

191

In order to congure the trigger method of the chart, while on the highest level of the chart, select Stateow Editor > Add > Event , then select a desired trigger method from the given options. When a trigger is added to a Stateow chart, a triggered system symbol is added to the chart graphical box.

1.4.1

Accessing Matlab Data and Matlab Functions from Stateow Chart

Matlab, Simulink and Stateow work together to model and simulate controlled dynamic systems. Therefore, these three components must be able to access data in each others workspace in order to apply logic to it. Matlab maintains all its data variables in its Workspace. Data sharing between Simulink and Stateow is generally accomplished by the input and the output signals in the block diagram. This is the recommended method of exchanging data between Matlab, Simulink and Stateow. It shows clearly in graphical form what data is passed between Simulink and Stateow. It is that graphical display of information and logic that makes Simulink and Stateow attractive programming tools. Therefore, this method of data exchange is consistent with the proper use of these tools. Below are also other methods of accessing data in Matlab workspace. Accessing Matlab Data: One way to access Matlab data and functions from Stateow is to use ml namespace operator and ml function. Using ml namespace operator we can access data in Matlab workspace. The ml acts like an object name, followed by a dot operator and variable name in Matlab workspace. For instance, let us assume there is variable x in Matlab workspace and we want to assign it to variable a in Stateow. a = ml.x ; % Stateflow variable a is assigned % to the value of Matlab workspace variable x.

192

CHAPTER 1. MATLAB AND ITS TOOLS

Likewise, we can assign a Stateow variable to a Matlab workspace variable. If the Matlab workspace variable was not created before, it will be automatically created. The following accomplishes that, ml.x = a ; % % % % Matlab workspace variable x is assigned to the value of Stateflow variable a. If Matlab workspace variable does not exit, it is created automatically.

Accessing Matlab Built-in Functions: We can use the same operator to access Matlab functions: a = ml.sin(ml.x) ; % Stateflow variable a is assigned to % the value of Sin of Matlab workspace variable x. % ..................b ............... % ........... Sin of Stateflow variable a.

b = ml.sin(a)

Notice the dierence between the above two examples: in the rst one the data variable x in Matlab workspace is used for the sine function. In the second example, the data variable a in the Stateow is used in the sine function. Another way of accessing Matlab functions is to use ml(....) function. Examples below illustrate the usage. a = ml(sin(x)) ; % Sin of Matlab workspace variable x % is assigned to Stateflow variable a. b = ml(sin(%f), a) ; % Sin of a is Stateflow data is % assigned to Stateflow data b. c = ml(matfunc(%g, "abc", x , %f), d1, d2) ; % Stateflow datas d1 and d2 are substituted in % the format specified, Matlab function executes and result % is assigned to the Stateflow variable c. d = ml(interp2(x,y,z,%g, %g), d1 ,d2) ; % 2-D function interpolation. Sampled values of z=z(x,y) % given in the x, y , z data in Matlabworspace. % interpolation at data points d1 (x-coordinate) and % d2 (y-coordinate) values which as Stateflow data,

1.4. STATEFLOW

193

Figure 1.81: Decomposition of states: exclusive (OR) or parallel (AND) states. At a super state, only one of the exclusive states can be active, whereas multiple parallel states (AND states) can be concurrently active. % is returned and assigned to Stateflow data d.

Example: Stateow Example to Illustrate Accessing Matlab Data and Built-in Functions In the example shown in Fig.??, we show the use of how to access a Matlab workspace variable (both to read from and to write to, in this case variable Kp) and how to access a built-in Matlab function, in this case disp(...) function. In the gure window labeled 1 shows the Matlab command window, and launching of simulink and stateow with command line statements, which activates the windows 2 and 3 for Simulink and Stateow, respectively. The Matlab variable Kp = 100; is dened in the Matlab workspace. Window 4 shows the simple Simulink model with a Stateow chart, where we copy the Stateow chart from the Window 3 with copy and paste. Double-clicking the Stateow Chart in

194

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.82: Graphical components of a Stateow diagram: state (parallel and exclusive), transitions (normal transitions, default transitions), actions, junctions (connective and history types), conditions.

1.4. STATEFLOW

195

window 4 brings up the window 5, which is the Stateow Editor. Here we build the basic Stateow Chart logic. It has one input, variable u (Input from Simulink) and one output, variable y (Output to Simulink) which are dened by Add > Data > Input from Simulink Add > Data > Output to Simulink Then, using View > Model Explorer, we can conrm the input and output data of the Chart (Window 6). Notice how we access the Matlab workspace variable Kp both for reading and writing purposes in the chart using the ml.Kp statements. Similarly, we access the Matlab built-in function disp(...) with ml.disp(...). Finally, to conrm the results, we open the Scope in Window 7, and set the input signal to step function with initial value of 0.5 and step change to value of 1.5 at time 1.0sec. We run the simulation under Debugger control as shown in window 8. By controlling the breakpoints, we can step through the execution of the program and observe the results in the Scope as well as in the Matlab Command Window since we send the ml.disp(...) outputs to that window by default.

196 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.83: Example Stateow model: illustration of accessing Matlab workspace data (for read and write) and Matlabs built-in functions in Stateow chart.

1.4. STATEFLOW

197

1.4.2

Function Calls from Stateow Chart

User Written C Functions User-written C functions, which return scalar value, can be called from Stateow charts transition actions and state actions (Fig.??). The C-function call is made just like in a C language program, that is

function_name (argument1, ... ) ;

The string parameters are passed using single quotes, i.e. string1 or Hello in the argument list. Function calls can be nested, that is one function call can include another function call it is argument list (Fig.??). Arguments can be passed by address using pointer notation. However, data from Input from Simulink should not be passed by address. If it is necessary, then a local copy should be created in the Stateow and that data should be passed by address. f(&x) ; % Call to function f(), pass data by address (reference) g(&(z[0])) ; % Passing array z[0], z[1], ... g(&(z[1])) ; % Passing array z[1], z[2], ...

To specify the custom C-code, for Simulation Target Stateow Editor > Tools > Open Simulation Target, or for RTW Target, Stateow Editor > Tools > Open RTW Target, which brings up the Conguration Parameters window (Fig. ?? and ??). In the left pane window, under Real-Time Workshop, select Custom Code, then enter the custom C-code les on the right pane. In the Source Files pane, enter the C-source le names separated by commas, space or new line.

198

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.84: Calling User-Written C-functions from Stateow Charts: calls from transition actions and state actions.

1.4. STATEFLOW

Figure 1.85: Including User-Written C-functions from Stateow Charts for Simulation Target. 199

200 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.86: Including User-Written C-functions from Stateow Charts for RTW Target.

1.4. STATEFLOW Example: Stateow Example to Illustrate Use of C-Functions

201

The purpose of this example is to illustrate how to incorporate C-functions into Stateow charts. Let the example, and user dialog windows are shown in Fig. ?? and ??.

202 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.87: Example to illustrate how to include user-written C-functions from Stateow Charts for Simulation Target: Illustrative gure 1 of 2. Windows 1 thru 6 shows the development process involved in order.

1.4. STATEFLOW 203 Figure 1.88: Example to illustrate how to include user-written C-functions from Stateow Charts for Simulation Target: Illustrative gure 2 of 2. Windows 7 thru 11, including the location of the C-source le in the directory, how it is specied in the dialog window of Stateow Editor, and the C-source le content.

204 Embedded MATLAB Functions

CHAPTER 1. MATLAB AND ITS TOOLS

Action items in Stateow charts may call functions to execute a logic instead of explicitly typing that action in the chart. An Embedded Matlab Function can be added by selecting the Embedded Matlab Function icon on the left pane of the Stateow Editor, and drag and drop it in the chart, then type the name of the function. Then double click on the box just created automatically to bring up the text editor and edit the content of the function. Input and output arguments from the function can be any Matlab data type of the form scalar, vector or matrix. This is a convenient way to code actions that are more than a single line. Fig.?? shows the windows on how to add an embedded Matlab function in a Stateow chart. The function is used to dene an action. 1. We draw the transitions and actions which calls an embedded Matlab function in the usual way. 2. Then use Embedded Matlab Function icon on the left pane of Stateow Chart, copy it into the chart. 3. Then type the name of the function in the created rectangle. 4. Double-clicking on the rectangle block for the function brings up the Embedded Matlab Editor. 5. From the Embedded MATLAB Editor, use Tool > Model Explorer, then edit the input-output data type and size, as well as local variables as needed. 6. Then simply type the logic of the function in the editor. Fig.?? shows the window for the Model Explorer that allows us to edit the data for the function. Embedded Matlab Functions support a subset of all Matlab functions, not all of the Matlab functions. When processed, embedded Matlab functions are converted to ecient Ccode. Those functions of the Matlab not supported by Embedded Matlab functions are not supported to C-code generation, hence not useable for embedded target applications. Any non-covered Matlab functions (those Matlab functions that are not supported in Embedded Matlab Functions) can still be access for simulation target. In order to access those functions for simulation targets (not for RTW targets), declare them as extrinsic in the function using the following syntax, eml.extrinsic(min) ; z=min(x,y) ; % Declare extrinsic in order access min function % Then use it as normally you would.

If the embedded Matlab function calls yet another function(s), that function(s) can be included in the same le below the embedded Matlab function le. g

1.4. STATEFLOW 205 Figure 1.89: Adding an Embedded Matlab Function in a Stateow chart: 1. Type the name of the function in an action (i.e a transition action). 2. Uing Embedded Matlab Function icon from the Stateow Chart Editor, copy one to the Chart, and type the name on it. 3. Double-click on the Embedded Matlab Function rectangle to bring up the text editor for the function, 4. Type in the logical code in text le, 5. from the Embedded Matlab Editors tool menu, select Model Explorer, and dene the input-output data (as well as local data) to the function.

206 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.90: Adding an Embedded Matlab Function in a Stateow chart: from the Embedded Matlab Editors tool menu, select Model Explorer, and dene the input-output data as well as local variables to the function.

1.4. STATEFLOW Example: Stateow Example to Illustrate Embedded Matlab Functions

207

The purpose of this example is to illustrate how to include Embedded Matlab Functions in a SF model. Fig. ?? and Fig. ?? shows the user interface windows for the development. Fig. ?? shows the windows 1, 2 and 3 for Matlab, Simulink, and Stateow respectively. Then from Simulink we start a model, shown in window 4. In this model, we include a Stafeow chart. Double-clicking on the SF chart in the model, brings up the Stateow Editor window 5. In this case we dene two states, X and Y for the SF model, and two transitions between them. In each state, and for each transition, we dene an action, which calls an Embedded Matlab Function. Hence, we have four Embedded Matlab Functions for this example. In order to make the function calls, simply click on the state X, and type the name of the function to be called. In this case, the actions are dened for the during: stage of the states status. Repeat the same for the state Y, and transitions. Then pick-and-drag four copies of the Embedded Matlab Function icon from the left pane into the Stateow Editor window. Then select each one-by-one, and type the name of the function on the box. Then double-click on each one-by-one (Fig. ??). This will bring up the Embedded Matlab Function Editor. Now, enter your code here. The editor already has the function declaration line. The editor shows one le at a time. For convenience, we copies all the les for illustration purposes here in the gure. Note that this is a Matlab Function of embedded kind. Only data visible to it are the ones passed in its argument list. The ml operator we used in the Stateow graphical model le is not available to access Matlab workspace data. If we need to access Matlab workspace data which are not passed by the function call arguments, then we must use global declaration. For instance, in the function StateX Action9u), we dene the Kp as a local variable. The Kp of the Matlab workspace can not be accessed via ml.Kp. If it is desired to access the Kp of the Matlab workspace instead of using a local Kp, then global declaration must be used.

208 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.91: Adding an Embedded Matlab Function in a Stateow chart: one of two (1/2) sets of windows.

1.4. STATEFLOW

Figure 1.92: Adding an Embedded Matlab Function in a Stateow chart: two of two (2/2) sets of windows.

209

210

CHAPTER 1. MATLAB AND ITS TOOLS

Example: Liquid Level in a Tank Control Problem with Multiple Modes of Controller Operation Let us revisit the liquid level control example we discussed in the Simulink section. For the purpose of illustrating how a typical Stateow chart can be used as part of a Simulink model, let us assume that the controller logic is now dierent than the one implemented in the Simulink example. The new controller we want to implement here has multiple modes of operation. Let us consider that the controller has three modes of operation. In each mode, a dierent control algorithm logic is implemented with dierent parameters. A supervisory control logic is to monitor the sensor signal for the measured liquid height and the desired height data, then decide on an output value that selects one of three desired modes of controller. Using that information, the Simulink part of the code is to execute the selected control algorithm. The supervisory control logic will be as follows, expressed in Matlab text language, and will be implemented in Stateow. For the purpose of illustration, we select a simple supervisory controller that can equally be implemented in Matlab or Simulink with ease. However, as supervisory logic gets more complicated, Stateow programming model provides advantages in ease of programming.

% Supervisory control logic to select controller mode of operation, err_th1 = 10.0 ; err_th2 = 25.0 ; % Percentage of liquid height error, threshold value 1 % Percentage of liquid height error, threshold value 2 ; % Current error, as percentage of desired height.

err = ((hd - h)/hd )* 100

if (err < err_th1) % Supervisory control logic: select controller mode. control_mode = 1 ; elseif (err >= err_th1 and err < err_th2 ) control_mode = 2 ; elseif (err >= err_th2) control_mode = 3 ; end

Figures ?? and ?? show the new Simulink block diagram of the liquid level control system as well as the Stateow chart for this very simple supervisory controller. A simulation result is shown in gure ??. The simulation was run for the following parameters (i.e. this data can be placed in an m-le, and executed before a simulation is run), err_band = 1.0 ; % for the Relay function.

1.4. STATEFLOW

211

Figure 1.93: Liquid level control example using Stateow chart for supervisory control logic. K2 = 1.0 ; % Controller mode 2 gain K3 = 4.0 ; % Controller mode 3 gain Ka = 1.0 ; % Amplifier current/voltage gain Kv = 1.0 ; % Valve flowrate/currrent gain Qin_max = 100.0 ; % Valve saturation values: maximum flow rate out of valve Qin_min = 0.0 ; % Minimum flow rate: valve closed, so zero. A = 1.0 ; % Tank cross sectional area R = 10.0 ; % Outflow rate resistance as function of liquid % height: Q_out = (1/R) * h Notice the change in the controller output discontinuity as the supervisory controller switches from one controller mode to another.

212

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.94: Liquid level control example using Stateow chart for supervisory control logic: Stateow chart details. This Stateow chart implements the supervisory logic shown in Matlab text programming language form shown in the previos page.

1.4. STATEFLOW

213

Figure 1.95: Simulation results for the liquid level control example using Stateow chart for supervisory control: Scope 1 top: Desired Liquid Level, Scope 1 botom: Measured Liquid Level, Scope 2 top: Supervisory Controller Output: Control Mode (1, 2, 3), Scope 2 bottom: Control Signal to Valve Amplier.

214

CHAPTER 1. MATLAB AND ITS TOOLS

Simulink and Stateow Example: Automatic Transmission Controller and Powertrain Simulation Figure ?? shows the components of an automotive powertrain in block diagram representation. The main components are engine, automatic transmission, nal drive and shafts between transmission output and nal drive, and tires. We do not model the dierential since we assume straight line motion of the car and no steering. Engine is controlled by its own local electronic control module (ECM). The engine and its ECM is modelled as a torque source and inertia (Fig.??). The torque generated by the engine is function of throttle and engine speed. We also do not simulate the start-up transient dynamics of the engine from initial engine start, but rather assume an initial speed. The automatic transmission has two components: torque converter and gear train (Fig.??). Torque converter provides a hydrodynamic coupling between the engine crankshaft and transmission gear set input shaft. The torque converter has the major components: impeller which is directly connected to the engine crankshaft, turbine which is connected to the gear set input shaft, and stator which guides the uid ow between impeller and turbine. As the engine moves the impeller, it transfers power to the stator thru the centrifugal momentum of the uid circulated in the torque converter. Torque converter is a uid based coupling. It provides a exible coupling between engine and transmission where the slip and transmitted torque in coupling is variable as function of relative speed between input and output shaft of it. The amount of torque transmitted by the torque convertor is a nonlinear function of the input shaft speed (impeller shaft speed which is equal to engine crankshaft speed) and output shaft speed (turbine speed). As the speed ratio between input and output shafts of the torque converter increases, the transmitted torque increases. When the two speeds are equal, no torque is transmitted. We model the rest of the powertrain as a nal drive gear ratio and vehicle inertia. We assume no slip between tires and ground. Engine input-output dynamics is expressed as (Fig.??, ??) (Jeng + Jimp )w(t) = Teng (t) Timp (t) (1.156) (1.157)

Teng (t) = f1 (t (t), weng (t))

where f1 (t(t), weng (t)) represents the so-called lug curve for the engine, which is a steadystate two dimensional function (also called engine torque map) which denes the engine output torque as function of throttle position and the engine speed. Transmission torque converter input-output dynamics is expressed as (Fig.??) wimp (t) = weng (t) Timp (t) = (wimp(t)/(f2 (wturb /wimp)) Tturb (t) = f3 (wturb/wimp) Timp
2

(1.158) (1.159) (1.160) (1.161)

1.4. STATEFLOW where the following assumptions are made:

215

engine output shaft is rigidly connected to the torque converters impeller shaft and that they have the same speed, torque converters impeller torque is a nonlinear static function of turbine and impeller speed ratios, torque converters torque gain between impeller to turbine is dened by a nonlinear static function, f3 () which is a function of the turbine and impeller speed ratios. The nonlinear functions f2 (), f3(), which are both function of the turbine speed to impeller speed ratios, denes the torque conversion characteristics of the torque converter. Transmission gear set is modeled as a kinematic gear ratio, with 100% power tranmission eciency, and its inertia is neglected,

Pin = Pout Tturb wturb = Ttran wtran

(1.162) (1.163) (1.164)

Hence, the torque and speed input-output ratio for the gear-box (typically a planetary gear set) section of the transmission

wturb(t) = Ntran wtran(t) Ttran(t) = Ntran Tturb (t) Ntran = f4 (Gear)

(1.165) (1.166) (1.167) (1.168)

wtran(t) = Nf d ww (t)

where Gear is the selected gear number (1, 2, 3, 4) and Ntran = f4 (Gear) = [4element vector] is the corresponding gear ratios at the gear-box of the transmission at the selected gears. Initially, the speed of the transmission output, wtran is determined from the initial speed of the wheel which is derived from the initial speed of the vehicle assuming zero slip condition. The remaining part of powertrain is modeled as a nal drive gear ratio, vehicle inertia, tire without slip, (Fig.??)

Jv ww (t) = Nf d (Ttran Tbrake Tload ) Tbrake (t) = f5 (b (t)) Tload (t) = f6 (ww (t)) Vv (t) = Rw ww (t)

(1.169) (1.170) (1.171) (1.172) (1.173)

216

CHAPTER 1. MATLAB AND ITS TOOLS

where f5 () represents the gain between the brake pedal angle and brake torque. Simulink block diagram implementation of the nal drive and vehicle dynamic is shown in Fig.??. The throttle t (t) command and brake pedal b (t) are under the control of the operator. The Jeng , Jimp, Jv is the rotary moment of inertia of the engine (we assume it to be constant), impeller, and vehicles equivalent moment of inertia reected on the wheels. The equivalent vehicle inertia is a mass being carried by a rolling wheel, neglecting the tire inertia relative the the vehicle inertia,

Jv = mv R2 w

(1.174) (1.175)

where mv is vehicle mass, Rw is the nominal wheel radius. Linear vehicle speed, Vv (t) is calculated assuming zero slip between the wheels and road, The weng , wimp, wturb, wtran, ww are angular speed of engine, impeller, turbine, transmission output shaft and wheel. Teng , Timp.Tturb, Ttran, Tbrake, Tload are the torques generated by the engine, the torque at the impeller shaft that acts as a load on the engine, torque tranmitted to turbine, torque at the gear set output shaft, torque generated by brakes, and road resistance torque. The nonlinear static functions f1 (), f2 (), f3(), f4 (), f5 (), f6() are used to model the engine torque map (f1 ), torque converter torque and speed gain functions (f2 and f3 ), gear ratios at any selected gear (i.e. at gear 1, 2, 3, 4 what are the gear rations at the transmission gear sets, f4 ), brake pedal to actual brake torque generated relationship (f5 ), and load torque due to road and aerodynamic resistance (f6 ). Transmission control logic works based a look up table using two major sensor signals: throttle and vehicle speed. Using these two measurements as input signals, and current gear setting, the logic determines whether the gear should stay same, up-shifts, or down-shifts (Fig.??). At a given current gear (i.e. currently we are at gear 2), the control logic reads the current throttle, then determines the up-shift and down-shift thresholds for vehicle speed. For instance, if the car is currently at gear 2, then using shift-curves 2-1 and 2-3, and current throttle position, the algorithm determines the low-threshold and high-threshold values of the vehicle speed. If the actual vehicle speed is between these two values, not gear shift is commanded. If it is smaller than the low-threshold, a down-shift is commanded (i.e if current gear is 2, then 2 to 1 down-shift is commanded). If the actual vehicle speed is larger than the high-threshold, then an up-shift is commanded (i.e. if the current gear is 2, then 2 to 3 up-shift is commanded). In order to eliminate gear shifts too often due to noise, the gear shift condition must be satised for a period of time, i.e. twait which is typically 100msec = 0.1sec, (Fig.??). Simulated parameters for the vehicle;

Jeng

= 0.02 kgm2

(1.176)

1.4. STATEFLOW Jimp = 0.002 kgm2 mv = 4000 kg Rw = 0.2 m Nf d = 10.0 f1 (weng , t) = f2 (wturb /weng ) = f3 (wturb /weng ) = ; engine torque map ; speed f actor ; torque ratio

217 (1.177) (1.178) (1.179) (1.180) (1.181) (1.182) (1.183) (1.184) (1.185) (1.186)

f4 (Gear) = [12.5; 21.5; 31.0; 40.5] ; gear set ratios f5 (b (t)) = 0.0 ; brake pedal to torque f6 (ww (t)) = 50.0 + 0.01 ww (t) The engine torque map is
2

; load torque

weng = [800 1200 1600 2000 4000]; t = [0


(1.187) (1.188)

f1 (weng , t) =

25 40 260 270 270 270

50 75 100]; 50 60 75 80 220 190 150 90 290 300 260 190 ; 320 330 335 270 350 380 340 275

(1.189)

(1.190)

Torque converter speed and torque conversion characteristics are wturb /weng 0 0.2 0.4 0.6 0.8 0.9 f2 () 0.2 0.2 0.2 0.2 0.2 0.2 * * * * * * 150.0 165 175.0 190.0 220.0 270.0 f3 () 2.0 1.9 1.7 1.4 1.0 0.9

And the physical gear ratios at the gear-box (typically a planetary gear set) of the transmission at gear selections 1, 2, 3, 4

218

CHAPTER 1. MATLAB AND ITS TOOLS

Gear Number 1 2 3 4

f4 : Gear Ratio 2.5 1.5 1.0 0.5

and for the transmission control algorithms,

twait = 0.1 sec (or4 sample periods f or 25ms sampling); wait time (1.191) T hrottle Samples = [ 0 5 25 50 90 100 ]; Shif t States = [ 2 1 5 5 20 20 30 30 Shif t T able = 10 10 25 25 50 50 3 2 4 3 1 2 2 3 3 4 ]; 5 5 30 30 f or 2 1 25 35 50 50 f or 3 2 40 50 75 75 f or 4 3 15 25 40 40 f or 1 2 25 40 70 70 f or 2 3 50 75 100 100 f or 3 4 (1.192) (1.193)

(1.194)

(1.195)

where Shif t T able data represents the sampled vehicle speed thresholds for up-shift and down-shift in the following order: row 1 holds the down-shift threshold values for 2-1 shift, row 2 holds the same for 3-2 shift, row 3 for 4-3 shift, row 4 holds the threshold values for up-shift for 1-2, row 5 for 2-3 and row 6 for 3-4. Column values in the table are for throttle values of 0%, 5%, 25%, 50% , 90%, 100%. In the gure ??, the x-axis holds the throttle values, y-axis vehicle speed. Each curve is the row data and represents the vehicle speed threshold values for a gear shift (i.e. 2-1 or 2-3 or 1-2 ) as function of throttle input. Simulated input functions and initial conditions for throttle and brake;

weng0 = 1200rpm ; inital engine speed ww0 = 0 ; inital wheel(vehicle) speed t (t) = Def ined in Simulink; throttle pedal b (t) = Def ined in Simulink; brake pedal

(1.196) (1.197) (1.198) (1.199)

The Matlab m-le that holds the above parameters and simulation initial conditions is as follows,

1.4. STATEFLOW

219

% % Filename: parameters1.m % Parameters and simulation initial conditions for automatic transmission % control and powertrain simulation example. % % In order to run this file and make the numeric data available in Matlab workspace, henc % in Simulink and Stateflow, in Matlab command window, type % >> parameters1 % % Then refresh the Simulink model of the automotive powertrain to make these numerical % data effective in the Simulink/Stateflow model environment. J_eng = 0.02 ; J_imp = 0.002 ; m_v = 4000.0 ; R_w = 0.2 ; N_fd = 10.0 ;

% Numerical data for the engine torque (lug-curve) w_eng_vec = [ 800 1200 1600 2000 4000] ; % row index throttle_vec=[ 0 25 50 75 100] ; % column index f1_vec= [ -40 -50 -60 -75 -80 % f1(row, col) 2D lookup table 260 220 190 150 90 270 290 300 260 190 270 320 330 335 270 270 350 380 340 275 ] ; % Numerical data for speed_ratio_vec = [ f2_vec = 0.2* [ f3_vec = [ torque 0.0 150. 2.0 converter model 0.2 0.4 0.6 165 175 190 1.90 1.7 1.4

0.8 220 1.0

0.9 ] ; 270 ] ; 0.9 ] ;

% Numerical data for the transmissions planetary gear set gear_vec = [ 1 2 3 4 ] ; f4_vec = [ 2.5 1.5 1.0 0.5 ] ; % Brake load f5 = 0.0 ; % Road load

220 f6_0 = 150.0 ; f6_1 = 0.0 ;

CHAPTER 1. MATLAB AND ITS TOOLS

% Transmission control logic data... t_wait = 4 ; % 4 sampling periods, sampling period for T-ECU is 25 msec. % In Stateflow, t_wait is implemented as the number of sampling periods. throttle_samples = [ 0 shift_table = [ 5 20 30 10 25 50 ] ; 5 5 20 30 10 25 50 25 5 25 40 15 25 50 50 5 35 50 25 40 75 90 30 50 75 40 70 100 100 ] ; 30 % for 2-1 50 % for 3-2 75 % for 4-3 40 % for 1-2 70 % for 2-3 100 % for 3-4

% Initial conditions for states for the simulations. w_eng0 = 1200 * 2*pi/60 ; % Initial engine speed w_w0 = 0.0 ; % Initial wheel (vehicle) speed % % % % Throttle pedal position (driver input) is defined as function of time using "Signal Builder Block" Brake pedal position (driver input) is defined as function of time using "Signal Builder Block"

Notice that everytime transmission up-shifts, the reected load torque on the engine increases suddenly and that results in drop in engine speed (Fig.??). When transmission down-shifts, the reected load torque on the engine decreases suddenly and engine speed increases immediately. Torque converter, acting like a exible coupling, provides some isolation between engine and transmission. So, when engine speed changes suddenly, the vehicle speed does not have to change so suddenly.

1.4. STATEFLOW

221

Figure 1.96: Automotive powertrain components: engine, transmission (torque converter and gear set), nal drive and wheel.

Figure 1.97: Look-up table for gear shift logic for a 4-speed automatic transmission.

222 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.98: Simulink and Stateow model of the automatic transmission control and powertrain.

1.4. STATEFLOW 223

Figure 1.99: Simulink model details of engine and transmission.

224 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.100: Simulink model details of transmission.

1.4. STATEFLOW 225

Figure 1.101: Stateow chart for the automatic transmission control logic.

226 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.102: Simulink models of vehicle dynamics: considered as inertia with nal gear ratio, tire radius, and road resistance.

1.5. REAL-TIME AUTO CODE GENERATION: RTW AND SFC

227

1.5

Real-time Auto Code Generation: RTW and SFC

One most powerful, versatile and widely used MATLAB feature is code generation from model using RTW. The use of RTW signicantly reduces the development time for embedded systems. Lot of companies is exploring the possibility of using MATLAB in their product development cycle. Its being talked that Very high level language based on models will soon replace middle level language C like the way C replaced assembly language programming long time back. Real-time Workshop (RTW) is the auto-code generation tool for Simulink. The corresponding tool for StateFlow charts is the StateFlow Coder (SFC). Using the RTW and SFC, a Simulink and StateFlow model can be automatically translated into a C-code. The C-code is generated specic to a target processor. The target congurations are selected for the RTW and SFC, before the code generation process is run, using a set of options presented in respective conguration windows. Using RTW and SFC involves making a few conguration selections in a window for RTW and SFC. It does not involve text or graphical programming. The RTW and its conguratoin windows are the congure the auto-code generation process for a desired target. Stateow options and Stateow Coder (SFC) are included in the RTW windows. We do not congure SFC in its own windows. All of the target conguration and Build process is dened in RTW windows. In the background, RTW handles the aut-code generation for Simulink blocks, while SFC handles the auto-code generation for Stateow blocks. For ecient use Real-Time Workshop technology, reader of this chapter need to be familiar with the use of Simulink and Stateow to create both continuous of event based models. Running such simulations in Simulink is also needed and knowledge of how to manage these models outputs to MATLAB workspace. The reader also need to have some good idea about high-level programming language concepts especially for real-time systems. Also the reader in some application will not need to program in C or other programming languages to create and test a real-time systems using the Real-Time Workshop software, successful handling and execution of real-time systems requires familiarity with parameters and design constraints. This chapter assumes you have a basic understanding of real-time system concepts, terminology, and environments. For a real-time implementation target, a typical Simulink/StateFlow algorithm should be modied to remove all non-real time components as follows. 1. Remove all input and output components (Function generator, Display, Scope, etc.) which are included for the purpose of analysis and debug (Fig.??). 2. Connect Simulink I/O driver blocks (such as ADC, DAC, DIO, CAN blocks) to the input/output ports. The external I/O will be handled by these blocks. 3. Provide initial values in the Matlab workspace for the parameters and variables so that these initialization values can be included in the generated auto-code.

228

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.103: Simulation results of automotive powertrain and automatic transmission control.

1.5. REAL-TIME AUTO CODE GENERATION: RTW AND SFC

229

4. Congure the RTW and SFC for the selected target embedded controller and run auto-code generation process. This is done from the model window using Simulation > Conguration Parameters menu option, which brings up the conguration window. An example of RTW and SFC coder conguration settings before auto-code generation is shown in Figure ??.

230 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.104: RTW and SFC conguration example. For dierent target CPUs, dierent settings are used. Many third party target CPU hardware suppliers provide tools to congure RTW and SFC for their particular target hardware.

1.5. REAL-TIME AUTO CODE GENERATION: RTW AND SFC

231

Auto-code generation process from Simulink and StateFlow environment is congured for xPC target harware with from Simulation > Conguration Parameters > RTW > xPC Target option. An example of this conguration window is shown in Fig.??.

232 CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.105: Conguring the auto-code generation process in Simulink and Stafeow for xPC Target Hardware.

1.6. XPC TARGET:

233

1.5.1

Target language compiler (TLC)

TLC or Target language compiler is one of the most advanced features of RTW. TLC is an advanced feature of MATLAB which can be used to customize the way code is generated by MATLAB. TLC les are asci les which control the way code is generated with real time workshop. TLC les are written in a language which has some similarity to html, m-le or C/C++. So experience with one of these language (C/C++ is preferable) is recommended for proper understanding of the TLC les. There are two types of TLC les modelwide TLC Block TLCs Block TLC is concerned with code generation for a specic block. MATLAB provides set of block TLCs for all the blocks supplied by SIMULINK. For user custom made blocks (S-functions) separate TLC les has to be written by user for ecient code generation. Modelwide TLC describes the general structure of code generation for a model. For each Target environment of RTW there is exists a set of modelwide TLCs which controls the code generation.

1.6

xPC Target:

xPC Target software component of Matlab allows us to generate code and run it on an xPC Target Hardware. xPC Target Hardware is a PC with DOS plus xPC Target Kernel. Any PC hardware with DOS operating system can be used as the embedded hardware to implement the real-time controller. We only need to add the xPC Target Kernel to the software setup. The I/O cards used must be selected from the list of xPC Target supported I/O cards. There are over 200 I/O cards supported currently and the list is growing. The xPC Target is run from the Matlab command window and it brings up the xPC Target Explorer Window (Fig.?? >> xpcexplr ; % Start xPC Target software...

The xPC Target Explorer window provides the user interface on the host PC to establish communication with the target PC, to create boot-disks, and interact with the target PC. xPC Target (harware and software) operates in three modes: 1. BootFloppy Mode: This mode requires only the xPC Target, not xPC Target Embedded Option. The xPC target hardware has DOS plus the xPC Kernel. It must be boot-up from 3.5 oppy disk. That disk must be prepared in the Matlab environment for BootFloppy Mode option for xPC Target hardware. This is called the xPC Target Boot Disk. After the boot, the xPC hardware waits for Host PC to download the application program.

234

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.106: An example model in Simulink: Simulation version (non-real time) and realtime version with appropriate I/O software drivers for the target ECU.

1.6. XPC TARGET:

235

2. DosLoader Mode: This more requires xPC Target and xPC Target Embedded Option. It allows us to boot the xPC hardware from a hard disk drive (HDD) or compact ash (CF) memory card instead of using 3.5 oppy. The xPC hardware still waits for the application code to be downloaded from the Host PC. 3. Stand-alone Mode: This mode requies xPC Target and xPC Target Embedded Option. It is intended for rapid deployment of the controller for low to medium volume applications. The Host computer is not needed. the xPC target can operate as a black box controller without host or keyboard or monitor interface. Of course, if desired those interface devices can still be used. In this mode, the boot process is handled from the HDD or CF memory, and the application is stored at the same storage device and automatically started its execution upon the completion of the boot process. The necessary boot les for all three modes are prepared in Matlab environment. Regardless of the mode, the target PC is booted with DOS from any boot device (i.e. oopy disk or HDD or CF), then xPC Target Kernel is started from DOS. After that point, DOS is no longer available on the target PC and the Kernel is in control. It is possible to book the PC with DOS and not start the Kernel, in which case DOS is available for the user. Most users will use DosLoader Mode while developing programs and debugging them, and Stand-alone Mode when the development is done and nal deployment or minor parameter tuning to be done. A boot disk for anyone of the above modes is created in Matlab environment (Fig.??). For BootFloppy mode boot disk creation, follow the steps: 1. Format a 3.5 disk and copy DOS on it.

C:\> Format A: C:\> sys A:

2. In Matlab Command Window, type: xpcexplr 3. In the new xPC Target Explorer Window, make the following selections: xPC Target Explorer > xPC Target Hierarchy > Target PC1 > Conguration > Target boot mode > BootFloppy, and Select the communication method (RS-232 or Ethernet), then click CreateDisk. For DosLoader mode boot disk creation, follow the steps: 1. Format a 3.5 disk and copy DOS on it.

236 C:\> Format A: C:\> sys A:

CHAPTER 1. MATLAB AND ITS TOOLS

2. In Matlab Command Window, type: xpcexplr 3. In the new xPC Target Explorer Window, make the following selections: xPC Target Explorer > xPC Target Hierarchy > Target PC1 > Conguration > Target boot mode > DosLoader for DosLoader mode (or select the appropriate mode desired), then click CreateDisk. For Stand-alone mode, 1. Target PC boot device (HDD or CF) should have the DOS. 2. Create a standard (Floppyboot mode) boot disk and boot Target PC. 3. In Matlab Command Window, type: xpcexplr 4. In the new xPC Target Explorer Window, make the following selections: xPC Target Explorer > xPC Target Hierarchy > Target PC1 > Conguration > Target boot mode > StandAlone . 5. Selec and build the real-time application on the host PC. This creates a directory modelname xpc emb. Copy the content of this directory to Target PC boot device (HDD or CF). Notice that for Stand-alone mode, a boot disk is not created, rather a BootFloppy disk is used as shown Step 2 and application les are copied to the Target PCs boot disk. 6. When you re-boot the Target PC, it will load DOS, then xPC Target Kernel, then the application program and run it. Figure ?? shows the components of a xPC which is various PC-104 cards (power supply, CPU card, I/O cards) and connectors. There are three major activities during development and debug process of a real-time controller implementation on xPC: 1. control the execution of the application program, i.e. run, stop. 2. change parameters of the controller, 3. gather data and plot results The host interface for xPC Target (xPC Target Explorer) provides the interface for controlling the program execution. In order to tune parameters, the RTW should be congured so that it does not inline parameters. If the parameters are inlined during auto-code generation, they are replaced with constants for optimization values and can not be changed on

1.6. XPC TARGET:

237

Figure 1.107: xPC Hardware: (top view) - components shown separately in PC-104 form factor: DC power supply, CPU card, I/O card(s) and connectors, bottom view) - components assembled in PC-104 stack (without the enclosure)

238

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.108: xPC Target Explorer Window and target boot oppy creation.

1.6. XPC TARGET:

239

the target. Two of the recommended modes of tuning paramters are : 1) use xPC Target Explorer Window, 2) use Simulink in External Mode. In order to tune parameters using xPC Target Explorer, download the application to the xPC hardware. In xPC Target Explorer window, right-click the downloaded target application, then select Start. List the parameters of the application by expanding in the Model Hierarchy under the target application. This shows the list of parameters and signals. Select the parameter you want to change, double-click the parameter and change the value in the dialog box, i.e. changing a gain, then hit Enter key. Then click the Update Parameter button to update the target application. Notice that we are able to change the parameter while the target application is running. It is also possible to stop the application. Update parameters, then run the applications. Simulink used in External Mode acts as an interface between the Host and Target PC. Once the Simulink is Connected to the xPC, the models Simulink block diagram acts as the GUI (graphical user interface). If the user changes a parameter on the host, in the Simulink blocks of the model in External mode, then these values are immediately downloaded to the target xPC, as soon as Apply button is pressed. If the Simulink is Disconnected from the target, no changes are updated to the target xPC. In order to display selected signals from the target application, again, select the target application on the host, right pane displays the properties of the application. Signals can also be displayed by gathering the data, uploading it to host and displaying on the host while the target is running. This can be done conveniently with Host Scopes. It is not recommended to to use scopes on the target xPC since its sole task should be to execute the control code, not displaying data for debug purposes. Under xPC Target Explorer Window, xPC Scopes, expand it, select host Scope and right-click, and add as many scopes to be displayed on the host as desired. Then, select the host scope created, right-click and select View Scopes to display it on the host. Then select desired signals in model hiearchy and drop them on the desired scope. Alternatively, select a signal, rigcht click on it, choose Add to Scopes option to add the signal to a scope (Fig.??). Signal tracing can also be done in Simulink External Mode. In that mode, Simulink block diagram model is the GUI to the target application, which is a very eective method. For each Simulink scope, xPC Target adds an xPC Target scope for the host. There is a limit of 10 Simulink scopes for xPC Target. Each scope can handle maximum of 10 signals. Download the application to target xPC. Set Simulink in External Mode. Then, Tools > External Mode Control Panel > Signal and Triggering , then in set the following in the dialog box - Source: manual, Mode: normal, Duration: 1000 , Delay: 0, the click Apply. Build and download application: Tools > Real-Time Workshop > Build Model. Then, select Simulation > External . Double click on Scope block to display it. Then, select Simulation > Connect to Target , then Simulation > Start Real-Time Code. The application will run on the xPC target hardware and host displays the data on Simulink scopes. Signal (data) logging is dierent than tracing in that logging is simply capture

240

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.109: Host PC and target xPC: parameter tunning and signal logging or tracing.

and upload the data, and display it later, whereas tracing captures, uploads and displays while target application is running in real-time (Fig.??). For logging signals from host in Simulink, the Simulink model must have Outport block and Data Import/Export in Conguration Parameters dialog box must be selected for data logging to work. In the Logging pane, check the boxes of the signals you would like to record and display (logging), then click Apply. Then Start the target application. Then run it as long as needed. Then Stop the application. Then send the logged data to Matlab workspace (click Send to Matlab Workspace button in the Logging pane of xPC Target Explorer Window) and plot/analyze in Matlab environmet using plot(...) functions. Custom graphical user interface (GUI) can be designed to run on the host PC and communicate with the target xPC. This interface can use used as an alternative to the above methods (Fig.??). It typically requires add-on Matlab components such as Virtual

1.6. XPC TARGET:

241

Figure 1.110: Host PC and target xPC: Signal (data) logging.

242

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.111: Host PC and target xPC: Graphical User Interface (GUI) Reality Toolbox or Altia Design Toolbox. xPC Target provides two key blocks to facilitate the communication between the GUI and xPC: the To xPC Target Block used to send data from GUI to xPC and From xPC Target Block used to receive data from xPC to GUI.

1.6.1

xPC Target Application Example: Testing CAN Bus

The objective of this example is to show the process of developing a Simulink/Stateow program, auto-code generation, download to target PC, run the application on the target PC and monitor the results to conrm that the application runs properly. This example shows how to develop and test a CAN bus test program. It requires a xPC-compatible target hardware and a CAN bus card. In this example, we use CAN bus card PC104-AC2by Softing Inc, which is an I/O card supported by xPC Target. Any other CAN bus card that is supported by xPC Target can also be used. In addition, the PC/104 CPU (target PC) should be connected to a VGA monitor so that we can monitor the real-time activity on it conveniently. The PC/104 CPU (target PC) must be connected to the development PC (Host PC)that has the Matlab development environment running. The communication between the host PC and target PC can be either through TCP/IP Ethernet connection or Serial port connection. Before trying this example, the communication method between host PC and target PC must be established and working. xPC Target supports PC/104 CPUs with certain Ethernet chips. Not all Ethernet chips are supported. The supported Ethernet chip list varies between dierent release versions of the xPC Target. Again, make sure your version of the xPC Target supports the Ethernet chip on the PC/104 CPU board. xPC Target Ex-

1.6. XPC TARGET:

243

plorer is used to communicate between the host PC and target PC (xPC) to run, monitor and debug the real-time application. xPC Target Explorer is launched from Matlab with the following command,

>> xpcexplr

Fig.?? shows the required hardware setup: 1. notebook PC (host PC with Matlab development environment), 2. PC/104 based xPC Target (target PC): CPU and CAN bus boards, 3. Ethernet connection cable between host PC and target PC, 4. VGA monitor connected to the target PC. Fig.?? shows the Simulink test program for testing the CAN bus. In this application, we have two CAN ports and one CAN bus. Basically, two CAN devices connected to one CAN Bus. The target CPU will send a signal to the CAN port 1. That signal source is a Simulink Source block for simplicity. The signal will travel and be received in CAN port 2. And the received signal will be displayed. If the CAN ports are working properly, the signal sent to CAN port 1 and signal received at CAN port 2 should be same. This is monitored on the target PCs monitor using Target Scope blocks on the Simulink test program. Now, select Tools > Real-time Workshop > Options option. Setup the target conguration for the xPC target hardware. Tools > Real-time Workshop > Build option. The program should generate executable code and download to target PC. When the download process is successfully completed, the status on the target PCs monitor is indicated. Now, using xpcexplr (xPC Target Explorer) program, we can communicate with the target PC, and host PC acting as a comminication terminal. Then Run the target application on the target PC with the Run command from xPC Explorer window. Now, the real-time application should run on the target PC. Signal of the CAN port 1 and CAN port 2 should be displayed on the VGA monitor. Also, the user should monitor the execution time counter in the VGA monitor to make sure the program is running steady (Fig.??).

1.6.2

xPC Target Application Example: Digital and Analog I/O Using Diamond DMM-AT-32X Card

This example shows how to perform digital and analog input-output from a real-time controller, using xPC harware which has an I/O card on its stack. Such I/O card must be from a list supported by xPC Target so that its driver blocks can be conveniently included in the Simulink program. Diamond DMM-AT-32X I/O card is one such card. It has both digital and analog input-output channels. For more information on the cards harware features, see its users manual. Simulinks xPC Target I/O library blocks include the driver blocks to connect the digital and analog I/O into the program data. As in previous example,

244

CHAPTER 1. MATLAB AND ITS TOOLS

Figure 1.112: xPC Target application example: 1. the xPC hardware (PC/104 based CPU board, CAN bus Card, DC power supply card), 2. Host PC is a notebook PC which hosts the Matlab development environment, 3. Ethernet connection cable between the two PCs, 4. VGA monitor connected to the xPC for monitoring and debugging purposes. for real-time xPC Target hardware applications, a Simulink program simply needs to be modied with I/O blocks instead of Source and Sink blocks. We assume the following hardware connections are made to the I/O card: 1. connect a single ON/OFF switch to one of the digital input channels of the I/O card. 2. connect a single LED (in series with a resistor to limit the current draw) to one of the digital output lines of the I/O card 3. connect an analog potentiometer to one of the analog input (ADC) channels of the I/O card. The potentiometer will need three point connection: supply voltage, ground, signal voltage. Connect those to the I/O card provided pins. 4. connect one of the analog output channels to the oscilloscope so that we can monitor the voltage output. For the purpose of illustration, we will implement a simple logic: simply copy the digital input to digital output (if the Switch is ON, LED will be ON, whatever the analog input voltage value is, same voltage value will be output on the analog output channel. Notice that the driver blocks to support the read/write and setup functions for the I/O board are included in the Simulink program and properly has been setup. The target scope is connected to display the status of all of these four signals on the target VGA monitor. We will also monitor the analog signals with dual-channel digital storage oscilloscope. The status of digital input and output will be visually observed from the ON/OFF status of the mechanical switch and the ON/OFF status light of the LED.

1.6. XPC TARGET:

245

Host Computer

EPC1

RS232 / TCP/IP

EPC2

CAN-1 CAN BUS


(CAN-AC2-104)

CAN-1 CAN BUS


(CAN-AC2-104)

CAN-2

CAN-2

model1

model2

Figure 1.113: Example Simulink program to test CAN bus communication.

246

CHAPTER 1. MATLAB AND ITS TOOLS

EPC

Digital I/O

DMM-32-AT RS232 Host Computer Analog I/O

Oscilloscope

Figure 1.114: A picture of the VGA monitor screen while running the CAN bus test application program on the target PC (xPC hardware) in real-time.

EPC

Digital I/O

DMM-32-AT RS232 Host Computer Analog I/O

Oscilloscope

Figure 1.115: xPC Target application example: 1. the xPC hardware (PC/104 based CPU board, I/O Card by Diamond DMM-32-ATX, DC power supply card), 2. Host PC is a notebook PC which hosts the Matlab development environment, 3. Ethernet connection cable between the two PCs, 4. VGA monitor connected to the xPC for monitoring and debugging purposes.

1.6. XPC TARGET:

247

Figure 1.116: Example Simulink program to test digital and analog I/O.

248 CHAPTER 1. MATLAB AND ITS TOOLS Figure 1.117: A picture of the VGA monitor screen and the digital storage oscilloscope, while running the digital I/O test application program on the target PC(xPC hardware) in real-time.

You might also like