Real-Time Workshop ® For Use with SIMULINK ® Modeling Simulation Implementation User’s Guide Version 3
How to Contact The MathWorks: ☎ ✉ 508-647-7000 Phone 508-647-7001 Fax The MathWorks, Inc. 24 Prime Park Way Natick, MA 01760-1500 Mail http://www.mathworks.com Web Anonymous FTP server Newsgroup ftp.mathworks.com comp.soft-sys.matlab @ support@mathworks.com suggest@mathworks.com bugs@mathworks.com doc@mathworks.com subscribe@mathworks.com service@mathworks.com info@mathworks.
Contents Foreword Related Products and Documentation . . . . . . . . . . . . . . . . . . . . . xvi Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi What Is MATLAB? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii What Is Simulink? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii What Is Stateflow? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix How to Use This Guide . . . . . . . . . . . . . . . .
The Rapid Prototyping Process . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6 Key Aspects of Rapid Prototyping . . . . . . . . . . . . . . . . . . . . . . . . 1-6 Rapid Prototyping for Digital Signal Processing . . . . . . . . . . . . 1-9 System Simulation and Algorithm Design . . . . . . . . . . . . . . . 1-9 Analyzing Results, Parameter Tuning, and Signal Monitoring Using External Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9 Rapid Prototyping for Control Systems . . .
4. Validating Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 5. Incorporating Generated Code into Legacy Code . . . . . . . . . . 6. Incorporating Legacy Code into Generated Code . . . . . . . . . . 7. Communicating With Device Drivers . . . . . . . . . . . . . . . . . . . 8. Code Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9. Automatic Build Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. Parameter Tuning . . . . . . . . . .
Targeting dSPACE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Real-Time Interface (RTI) . . . . . . . . . . . . . . . . . . . . . . . . . . . Building a Real-Time Executable with dSPACE’s RTI . . . . dSPACE Control Desk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dSPACE COCKPIT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-28 2-30 2-30 2-31 2-32 Code Generation and the Build Process 3 Introduction . . . . . . . . . . . . . . . . . . . .
File and Function Splitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . File Splitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Function Splitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . File and Function Splitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38 3-38 3-40 3-41 External Mode 4 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating an External Mode Communication Channel . . . . . . 4-27 Rebuilding the ext_comm MEX-file . . . . . . . . . . . . . . . . . . . . . 4-27 Data Logging and Signal Monitoring 5 MAT-File Data Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 To File Block MAT-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 Singletasking versus Multitasking MAT-File Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rapid Prototyping System Dependent Components . . . . . . . . The main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Model Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Program Termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Rapid Prototyping Application Modules for System Dependent Components . . . . . . . . . . . . . . . . . . . .
Executing Models in Real-Time . . . . . . . . . . . . . . . . . . . . . . . . . 7-9 Multitasking Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10 Singletasking Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10 Sample Rate Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Faster to Slower Transitions in Simulink . . . . . . . . . . . . . . . . Faster to Slower Transitions in Real-Time . . . . . . . . . . . . . . .
Interactively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Connecting to the VxWorks Target . . . . . . . . . . . . . . . . . . . Downloading the Real-Time Program . . . . . . . . . . . . . . . . . Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19 8-19 8-19 8-19 Targeting DOS for Real-Time Applications 9 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Targeting Custom Hardware 10 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2 Run-Time Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4 Creating System Target Files and Template Makefiles . . . 10-5 Implementing Device Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-7 Device Driver Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-8 The S-Function Format . .
Real-Time Workshop Libraries 11 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2 Custom Code Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Custom Model Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Example of How to Use a Custom Code Block . . . . . . . . . . . Custom Subsystem Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-4 11-4 11-5 11-7 Interrupt Handling .
Choosing a Target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7 xii Contents Real-Time Code Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Unsupported Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . System Target Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Template Makefiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-10 12-10 12-10 12-11 Real-Time malloc Code Format . .
Real-Time Workshop Rapid Simulation Target 13 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2 Building for the Rapid Simulation Target . . . . . . . . . . . . . . . . 13-4 Running a Rapid Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4 <-f> Specifying a New Signal Data File for a From File Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-5 <-o> Specifying a New Output Filename for the Simulation . . . . .
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-6 Setting Options for Ada Code Generation . . . . . . . . . . . . . . 14-7 Generating Ada Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-8 Generated Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-9 Models with S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-9 Generating the Ada Code . . . . . . . . . . . . . . . . . . . . .
Foreword Related Products and Documentation . . . . . . . . xvi Requirements . . . . . . . . . . . . . . . . . . . . xvi How to Use This Guide . . . . . . . . . . . . . . . xxi Typographical Conventions . . . . . . . . . . . . . . xxi Installation . . . . . . . . . . . . . . . . . . . . xxii Third-Party Compiler Installation on Windows . . . . . . xxiii Supported Compilers . . . . . . . . . . . . . . . . . xxiv Where to Go from Here . . . . . . . . . . . . . . .
Foreword Related Products and Documentation Requirements The Real-Time Workshop® is a multiplatform product, running on Microsoft Windows 95, Windows 98, Windows NT, and UNIX systems. The Real-Time Workshop requires: • MATLAB® 5.3 (Release 11) • Simulink® 3.0 (Release 11) In addition, you can use Stateflow® to add finite-state machine models to your model. The Real-Time Workshop generates production quality code for models that consist of elements from MATLAB, Simulink, and Stateflow.
Related Products and Documentation What Is MATLAB? MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation.
Foreword What Is Simulink? Simulink is a software package for modeling, simulating, and analyzing dynamic systems. It supports linear and nonlinear systems, modeled in continuous time, sampled time, or a hybrid of the two. Systems can also be multirate, i.e., have different parts that are sampled or updated at different rates. For modeling, Simulink provides a graphical user interface (GUI) for building models as block diagrams, using click-and-drag mouse operations.
Related Products and Documentation Stateflow machine. This S-function is the agent Simulink interacts with for simulation and analysis. The control behavior that Stateflow models complements the algorithmic behavior modeled in Simulink block diagrams. By incorporating Stateflow diagrams into Simulink models, you can add event-driven behavior to Simulink simulations. You create models that represent both data and control flow by combining Stateflow blocks with the standard Simulink blocksets.
Foreword diagrams. Stateflow brings system specification and design closer together. It is easy to create designs, consider various scenarios, and iterate until the Stateflow diagram models the desired behavior. The Stateflow® Coder is an add-on to Stateflow that supports code generation. It works in conjunction with Real-Time Workshop in these ways: • Stateflow Coder generates high quality integer-based code (runs on a fixed-point processor; a floating-point processor is not required).
How to Use This Guide How to Use This Guide Typographical Conventions To Indicate... This Guide Uses... Example New terms Italics An array is an ordered collection of information. Keys, menu names, items, and GUI controls Boldface with an initial capital letter Choose the File menu. Function names, variables, example code, user-entered text Monospace type The sfopen command opens a model.
Foreword Installation Your platform-specific MATLAB Installation Guide provides essentially all of the information you need to install the Real-Time Workshop. Prior to installing the Real-Time Workshop, you must obtain a License File or Personal License Password from The MathWorks. The License File or Personal License Password identifies the products you are permitted to install and use.
Installation If you experience installation difficulties and have Web access, connect to The MathWorks home page (http://www.mathworks.com). Look for the license manager and installation information under the Tech Notes/FAQ link under Tech Support Info. Third-Party Compiler Installation on Windows Several of the Real-Time Workshop targets create an executable that runs on your workstation. When creating the executable, the Real-Time Workshop must be able to access a compiler.
Foreword Microsoft Visual C/C++ Define the environment variable MSDevDir to be MSDevDir= MSDevDir=\SharedIDE MSDevDir=\Common\MSDev98 for Visual C/C++ 4.2 for Visual C/C++ 5.0 for Visual C/C++ 6.0 Out-Of-Environment Error Message If you are receiving out-of-environment space error messages, you can right-click your mouse on the program that is causing the problem (for example, dosprmpt or autoexec.bat) and choose Properties. From there choose Memory.
Where to Go from Here Where to Go from Here Chapter 1, “Introduction to the Real-Time Workshop,” is a quick introduction to the rapid prototyping process and the open architecture of the Real-Time Workshop. Chapter 2, “Getting Started with the Real-Time Workshop,” discusses basic concepts and terminology of the Real-Time Workshop.
Foreword Chapter 12, “Configuring Real-Time Workshop for Your Application,” compares and contrasts various targets, including the generic real-time, embedded-C, and RTW S-function targets. Chapter 13, “Real-Time Workshop Rapid Simulation Target,” discusses the Rapid Simulation Target (rsim), which executes your model in nonreal-time on your host computer.
1 Introduction to the Real-Time Workshop Introduction . . . . . . . . . . . . . . . . . . . . 1-2 The Real-Time Workshop . . . . . . . . . . . . . . 1-3 Real-Time Workshop Applications . . . . . . . . . . . . 1-3 The Generated Code . . . . . . . . . . . . . . . . . 1-4 The Rapid Prototyping Process . . . . . Key Aspects of Rapid Prototyping . . . . . . Rapid Prototyping for Digital Signal Processing Rapid Prototyping for Control Systems . . . . . . . . . . . .
1 Introduction to the Real-Time Workshop Introduction The Real-Time Workshop, for use with MATLAB and Simulink, produces code directly from Simulink models and automatically builds programs that can be run in a variety of environments, including real-time systems and stand-alone simulations. With the Real-Time Workshop, you can run your Simulink model in real-time on a remote processor.
The Real-Time Workshop The Real-Time Workshop The Real-Time Workshop provides a real-time development environment that features: • A rapid and direct path from system design to implementation. • Seamless integration with MATLAB and Simulink. • A simple, easy to use interface. • An open and extensible architecture. • A fully configurable code generator — virtually every aspect of the generated code can be configured by using the Target Language Compiler™.
1 Introduction to the Real-Time Workshop • High-speed stand-alone simulations. • Generation of portable C code for export to other simulation programs. The Generated Code The generated code (i.e., the model code) is by default highly optimized and fully commented C code that can be generated from any Simulink model, including linear, nonlinear, continuous, discrete, or hybrid models.
The Real-Time Workshop a fixed, user-specified sample rate. Continuous time models are incorporated into this code with the simple provision that their states are propagated using fixed-step size integration algorithms. • A high-performance stand-alone simulation — use the generated code with the generic real-time system target file to produce an executable for stand-alone simulations. At the end of the simulation, the executable produces a model.
1 Introduction to the Real-Time Workshop The Rapid Prototyping Process The Real Time Workshop allows you to do rapid prototyping, a process that allows you to conceptualize solutions using a block diagram modeling environment and take an early look at system performance prior to laying out hardware, writing any production software, or committing to a fixed design. By using rapid prototyping, you can refine your real-time system by continuously iterating your model.
The Rapid Prototyping Process The traditional approach to real-time design and implementation typically involves multiple teams of engineers, including an algorithm design team, software design team, hardware design team, and an implementation team. When the algorithm design team has completed its specifications, the software design team implements the algorithm in a simulation environment and then specifies the hardware requirements. The hardware design team then creates the production hardware.
1 Introduction to the Real-Time Workshop The figure below shows the rapid prototyping process in more detail.
The Rapid Prototyping Process This highly productive development cycle is possible because the Real-Time Workshop is closely tied to MATLAB and Simulink.
1 Introduction to the Real-Time Workshop You can monitor signals using Scope blocks while running external mode. Simply connect Scope blocks to signals that you want to monitor. You can then view signals changing as you tune parameters on-the-fly.
The Rapid Prototyping Process Algorithm Design and Analysis From the block diagrams developed during the modeling stage, you can extract state-space models through linearization techniques. These matrices can be used in control system design.
1 Introduction to the Real-Time Workshop Open Architecture of the Real-Time Workshop The Real-Time Workshop is an open and extensible system designed for use with a wide variety of operating environments and hardware types.
Open Architecture of the Real-Time Workshop C-MEX S-functions Simulink MATLAB model.mdl Real-Time Workshop Real-Time Workshop Build system.tmf model.rtw TLC program: • System target file • Block target files Target Language Compiler • Target Language Compiler function library Run-time interface support files model.c model.h model_export.h model.prm model.reg model.mk make model.
1 Introduction to the Real-Time Workshop Target Language Compiler To generate code, the Real-Time Workshop invokes the Target Language Compiler (TLC). The Target Language Compiler transforms an intermediate model description generated by the Real-Time Workshop of your Simulink block diagram into target specific code. The intermediate description of your model is saved in an ASCII file called model.rtw. The Target Language Compiler allows you to modify most aspects of the generated code.
Open Architecture of the Real-Time Workshop S-Functions S-functions allow you to add custom code to your Simulink model. You can embed the code directly into the generated code or, by default, allow the S-function Application Program Interface (API) to call the S-function. Embedding the S-function code directly into the generated code is called inlining the S-function. The default is called noninlined. For more information on S-functions, see Using Simulink.
1 Introduction to the Real-Time Workshop options, and additional information for the destination (target) of the generated executable. The model.mk file is created by copying the contents of system.tmf and expanding out tokens describing your model’s configuration. You can fully customize your build process by modifying an existing template makefile or providing your own template makefile. After the model.mk file is created, the make command is invoked to create your executable.
Open Architecture of the Real-Time Workshop A First Look at Real-Time Workshop Files An example of a Simulink model is this block diagram: sin_out Sine Wave 1 gain_out Gain 1 Out Figure 1-4: A Simple Simulink Model This model is saved in a file called example.mdl. Generating C code from example.mdl is done by using the Real-Time Workshop user interface for generating code and executables. The next chapter, “Getting Started with the Real-Time Workshop,” explains the details of the user interface.
1 Introduction to the Real-Time Workshop example.rtw, which is the .rtw file associated with “A Simple Simulink Model” on page 1-17: CompiledModel { Name . . . System { Type . . . } NumBlocks . . . } Block { Type . . . } Block { Type . . . } Block { Type . . . } } All compiled information is placed "example" within the CompiledModel record. This parameter value pair identifies the name of your model. root Your model consists of one or more system records.
Open Architecture of the Real-Time Workshop Language Compiler Reference Guide, which contains detailed descriptions of the contents of model.rtw files. Basic Features of example.c Using the example.rtw file and target files, the Target Language Compiler creates C code that you can use in stand-alone or real-time applications. The generated C code consists of procedures that must be called by your target’s execution engine. These procedures consist of the algorithms defined by your Simulink block diagram.
1 Introduction to the Real-Time Workshop assigning buffers to each input and output. Compare this to the MdlOutputs function generated with buffer optimizations turned off. void MdlOutputs(int_T tid) { /* Sin Block: /Sine Wave */ rtB.sin_out = rtP.Sine_Wave_Amp * sin(rtP.Sine_Wave_Freq * ssGetT(rtS) + rtP.Sine_Wave_Phase); /* Gain Block: /Gain */ rtB.gain_out = rtB.sin_out * rtP.Gain_Gain; /* Outport Block: /Out1 */ rtY.Out1 = rtB.
Open Architecture of the Real-Time Workshop Using Stateflow and Blocksets with the Real-Time Workshop Stateflow is a graphical design and development tool for complex control and supervisory logic problems. It supports flow diagram notation as well as state transition notation. The Stateflow Coder is an add-on to Stateflow that supports code generation and seamless integration with the Real-Time Workshop.
1 Introduction to the Real-Time Workshop 1-22
2 Getting Started with the Real-Time Workshop Introduction . . . . . . . . . . . . . . . . . . . . 2-2 Where to Find Information in This Manual . . . . . . 2-3 Basic Concepts in the Real-Time Workshop . . . . . . 2-8 Building Generic Real-Time Programs . . . . . . . . 2-12 Blocks That Depend on Absolute Time . . . . . . . . 2-21 Code Validation . . . . . . . . . . . . . . . . . . 2-23 Targeting dSPACE . . . . . . . . . . . . . . . . .
2 Getting Started with the Real-Time Workshop Introduction This chapter begins a discussion of basic concepts used in real-time development and relates them to concepts in the Real-Time Workshop. You can use the first section as a road map to the rest of the documentation. After defining a map from real-time development tasks to sections of this book, the chapter discusses generic real-time in more detail and includes an example of how to generate stand-alone C code from your Simulink block diagram.
Where to Find Information in This Manual Where to Find Information in This Manual This section discusses typical requirements for producing real-time software and provides a road map to areas in this documentation that address key real-time issues. The Real-Time Workshop has support for all the following tasks that real-time engineers need to do. Each item below has a corresponding subsection that tells you where to find the information necessary to accomplish your tasks using the Real-Time Workshop.
2 Getting Started with the Real-Time Workshop • Write a harness program (i.e., main) • Install a C compiler A bundled harness program is supplied for the Tornado and DOS operating systems. That is, these harnesses can be used without modification. More generic harnesses are supplied as starting points for targeting a different operating system.
Where to Find Information in This Manual LibMdlRegCustomCode, LibSystemInitializeCustomCode, LibSystemOutputCustomCode, LibSystemUpdateCustomCode, LibSystemDerivativeCustomCode, LibSystemEnableCustomCode, LibSystemDisableCustomCode, LibSystemUserCodeIsEmpty Alternatively, you can look at hookslib.tlc and cachelib.tlc for brief descriptions of these functions. The TLC files are located in matlabroot/rtw/c/tlc. 3.
2 Getting Started with the Real-Time Workshop 6. Incorporating Legacy Code into Generated Code Legacy code, or hand-written code, is existing code that you want to interface with Real-Time Workshop generated code. To interface legacy code with the Real-Time Workshop, you can use an S-function wrapper to do this; see Chapter 4 of Writing S-Functions for more information. 7. Communicating With Device Drivers S-functions provide a flexible method for communicating with device drivers.
Where to Find Information in This Manual • External mode — you can tune parameters from Simulink while running the generated code on a target processor. See Chapter 4, “External Mode,” for information on this mode. • External C application program interface (API) — you can write your own C API interface using support files provided by The MathWorks. See “C API for Parameter Tuning” on page 3-19 for more information.
2 Getting Started with the Real-Time Workshop Basic Concepts in the Real-Time Workshop Before going through a step-by-step example of how to target specific hardware using the Real-Time Workshop, it is important to understand concepts basic to the product.
Basic Concepts in the Real-Time Workshop target environments and the system target files and template makefiles associated with each example environment: Table 2-1: Target Systems and Associated Support Files Target System Target File Template Makefile Generic real-time grt.tlc grt_default.tmf Embedded-C ert.tlc ert_default.tmf DOS (4GW) real-time drt.tlc drt_watc.tmf Tornado (VxWorks) real-time tornado.tlc tornado.tmf Rapid Simulation rsim.tlc rsim_default.
2 Getting Started with the Real-Time Workshop the Real-Time Workshop page. Finally, if the host on which you are running matches the HOST macro specified in the template makefile, make is invoked to create a program from the generated code. See Chapter 3, “Code Generation and the Build Process,” for more information on the build process. Template Makefiles The Real-Time Workshop uses template makefiles to build an executable from the generated code.
Basic Concepts in the Real-Time Workshop and program building. Therefore, before you generate code and build a program, you must verify that the model parameters have been set correctly in the Simulation Parameters dialog box.
2 Getting Started with the Real-Time Workshop Building Generic Real-Time Programs This example describes how to generate C code from a Simulink model and create a generic real-time program. This program: • Executes as a stand-alone program, independent of external timing and events • Saves data in a MATLAB MAT-file for later analysis • Is built in the UNIX and PC environments It also demonstrates how to use data logging to validate the generated code.
Building Generic Real-Time Programs This is the Simulink model that appears: w Pilot Pilot g force (g) q Stick Input Nz pilot calculation 1 u 2 Stick Input (in) alpha (rad) Elevator Command (deg) 1 Ta.
2 Getting Started with the Real-Time Workshop Setting Program Parameters After displaying the f14 model, select Parameters from the Simulation pull-down menu. This displays the Simulation Parameters dialog box with the Solver page selected by default: The Simulation Parameters dialog box allows you to set options, select a template makefile, generate code, and build the program.
Building Generic Real-Time Programs Note Alternatively, you can select RTW Options from the Tools pull-down menu. This brings you directly to the Real-Time Workshop page of the Simulation Parameters dialog box. Building the Program To build the program, select the Real-Time Workshop page in the Simulation Parameters dialog box: Click the Build button to generate C code from the f14 model. The build command calls a system target file, grt.
2 Getting Started with the Real-Time Workshop When you click on the Build button in the Simulation Parameters dialog box, the Real-Time Workshop invokes the make command, which in turn: • Compiles the block diagram to produce the model.rtw file (in this example, f14.rtw) • Invokes the Target Language Compiler, which in turn compiles the TLC program, starting with grt.tlc, and operates on model.rtw to produce the generated code • Creates a makefile called model.mk (e.g., f14.
Building Generic Real-Time Programs substitute the numerical values of the model parameters in place of the variable names. It also instructs Simulink to propagate constant sample times, which improves performance by placing constant operations into the start-up code. You can also customize the template makefile and the make commands; these options are discussed later in this chapter.
2 Getting Started with the Real-Time Workshop a MATLAB MAT-file. You can load this data into MATLAB for analysis. See “Blocks That Depend on Absolute Time” on page 2-21 for more information. Inputs to models cannot be saved using the Workspace I/O page. To save inputs, you can use Scope block and click the Properties button. Alternatively, you can use a To Workspace block. See Using Simulink for more information about saving data to the MATLAB workspace using either of these methods.
Building Generic Real-Time Programs grt_unix.tmf is designed to be used by GNU Make, which is located in matlabroot/bin/arch/make (except for Linux systems, which provide GNU Make by default). PC Template Makefiles The template makefiles grt_vc.tmf and grt_msvc.tmf are designed to be used with the Microsoft Visual C/C++ compiler. To use either of these template makefiles, you must verify that the Visual C/C++ environmental variables are defined and that nmake is on your search path. To use grt_vc.
2 Getting Started with the Real-Time Workshop Generic Real-Time Modules These source modules are automatically linked by the makefile, model.mk. The modules used to build this example are: Generated Code f14.c f14.h f14_export.h f14.prm f14.reg Main Program One of These Template Makefiles: grt_unix.tmf grt_vc.tmf grt_msvc.tmf grt_watc.tmf grt_main.c Model Execution Makefile rt_sim.c f14.mk Executable File f14[.exe] Integration Module ode5.c Data Logger rtwlog.c Simulink Data Structure simstruc.
Blocks That Depend on Absolute Time Blocks That Depend on Absolute Time Some Simulink blocks use the value of absolute time (i.e., the time from the beginning of the program to the present time) to calculate their outputs. If you are designing a program that is intended to run essentially forever, then you cannot use blocks that have a dependency on absolute time. The problem arises when the value of time reaches the largest value that can be represented by a double precision number.
2 Getting Started with the Real-Time Workshop Sources Chirp Signal Pulse Generator Clock Ramp Digital Clock Repeating Sequence Discrete Pulse Generator Signal Generator From Workspace Sine Wave From File Step In addition, data logging time (in the Workspace I/O page of the Simulation Parameters dialog box) also requires absolute time.
Code Validation Code Validation After completing the build process, the stand-alone version of the f14 model is ready for comparison with the Simulink model. The MAT-file data logging options selected with the Workspace I/O page of the Simulation Parameters dialog box cause the program to save the pilot G forces, aircraft angle of attack, and simulation time. You can save the Stick Input signal to the MATLAB workspace by setting options in the Scope block.
2 Getting Started with the Real-Time Workshop Then look at the workspace variables: who Your variables are: rt_Pilot_G_force rt_tout rt_Angle_of_attack rt_xout rt_Stick_input rt_yout The variables rt_tout, rt_xout, and rt_yout were logged because the appropriate time, states, and outputs buttons were clicked on the Workspace I/O page. The variables rt_Pilot_G_force, rt_Angle_of_attack, and rt_Stick_input were saved using the Properties page of the Scope blocks in the f14 model.
Code Validation Comparing Simulation and Generic Real-Time Results Your Simulink simulations and generic real-time code should produce nearly identical output. Let’s compare the f14 model output from Simulink to the results achieved by the Real-Time Workshop. Follow these steps to do a correct comparison: • First, make sure that you’ve selected the same (fixed-step) integration scheme for both the Simulink run and the Real-Time Workshop build process (for example, ode5 (Dormand-Prince).
2 Getting Started with the Real-Time Workshop Comparing Pilot_G_force to rt_Pilot_G_force produces: max(abs(rt_Pilot_G_force-Pilot_G_force)) ans = 1.0e-012 * 0 0.1007 So overall agreement is within 10-12. This slight error is caused by many factors, including: • Different compiler optimizations • Statement orderings • Run-time libraries For example, sin(2.0) may differ depending on which C library you are using.
Code Validation Use the MATLAB open_system command to trace the generated code back to the model. For example, open_system('') opens system 3 and open_system('/Kp') opens and selects Gain block Kp which resides in S3.
2 Getting Started with the Real-Time Workshop Targeting dSPACE dSPACE, a company that specializes in real-time hardware and software products, markets a complete set of tools for use with the Real-Time Workshop. These tools are primarily intended for rapid prototyping of control systems and hardware-in-the-loop applications. This section provides a brief example of how to use dSPACE’s RTI (real-time interface) with the Real-Time Workshop.
Targeting dSPACE Motherboard “host” Embedded cards (target system) Monitor/keyboard PC chassis Figure 2-3: A PC Setup Including a Target System bu s digital I/O s encoder interface or PH S D/A or s/ ac tu at A/D se ns DSP PC/AT expansion bus Figure 2-4: The dSPACE PHS Bus 2-29
2 Getting Started with the Real-Time Workshop Real-Time Interface (RTI) When using the Real-Time Workshop with dSPACE hardware, you must generate target-specific software. The key software component for this configuration is the dSPACE Real-Time Interface to Simulink. The RTI, with special versions available for various dSPACE processor boards (C31, C40, DEC Alpha, etc.), is available directly from dSPACE and dSPACE distributors.
Targeting dSPACE system target file and template makefile. For the current example, in the Real-Time Workshop page of the dialog box, specify: • System target file: rti1102.tlc • Template makefile: rti1102.tmf With this configuration, you can now generate a real-time executable and download it to the dSPACE processor board. You can do this by clicking the Build button on the Real-Time Workshop page.
2 Getting Started with the Real-Time Workshop This picture shows the Control Desk Control Panel and a sample of Control Desk plots: Figure 2-5: The Control Desk Control Panel and Sample Control Desk Plots. dSPACE COCKPIT COCKPIT provides a virtual instrument panel on the host PC. It provides an interface for editing parameters while the generated code executes on the dSPACE processor boards.
3 Code Generation and the Build Process Introduction . . . . . . . . . . . . . . . . . . . . 3-2 Automatic Program Building . . . . . . . . . . . . 3-3 The Real-Time Workshop User Interface . . . . . . . 3-6 The System Target File Browser . . . . . . . . . . . . 3-11 Configuring the Generated Code . . . . . . . . . . . 3-22 Template Makefiles . . . . . . . . . . . . . . . . . 3-23 Generic Real-Time Templates . . . . . . . . . . . . 3-32 File and Function Splitting File Splitting . . . . . . .
3 Code Generation and the Build Process Introduction The Real-Time Workshop simplifies the process of building application programs. One of the Real-Time Workshop’s features is automatic program building, which provides a standard means to create programs for real-time applications in a variety of host environments. It does this in a uniform and controlled manner, yet is customizable to different applications.
Automatic Program Building Automatic Program Building The Real-Time Workshop automates the task of building a stand-alone program from your Simulink model. When you click on the Build button on the Real-Time Workshop page of the Simulation Parameters dialog box, the make command, which starts with make_rtw, is invoked. The build process consists of three main steps that are controlled by an M-file, make_rtw.m: 1 Generating the model code. 2 Generating a makefile that is customized for a given build.
3 Code Generation and the Build Process The shaded box in the figure below outlines these steps: Simulink Model Your Template Makefile User-Developed Model and Template Makefile system.tmf Generate Code Automated Build Process Model Model Code Code model.c model.c model.h model.h model_export.h model.prm model.prm model.reg model.reg Generate Makefile make_rtw.m Custom Makefile model.mk make –f model.mk make –f model.mk Executable C Program Program model.
Automatic Program Building When you click the Build button on the Real-Time Workshop page on the Simulation Parameters dialog box, these steps are carried out automatically. This diagram illustrates the logic that controls this process: Press Build Button Simulink Model Generate Code Template Makefile Generate Makefile Does HOST equal model.c model.h model_export.h model.prm model.reg Custom Makefile model.
3 Code Generation and the Build Process The Real-Time Workshop User Interface You work with the Real-Time Workshop by interacting with and modifying fields of the Simulation Parameters dialog box of your Simulink model. One page of this dialog box is exclusively for the Real-Time Workshop. The other pages apply to both Simulink simulations and the Real-Time Workshop. To access the Simulation Parameters dialog box, you can select the Parameters item of the Simulation menu.
The Real-Time Workshop User Interface System Target File Use the System target file field to specify the type of code and target for which you are generating code. For a complete table of available targets, see “Targets Available from the System Target File Browser” on page 3-13. After you have selected the system target file, you can specify options for the Target Language Compiler (TLC). The common options are shown in the table below.
3 Code Generation and the Build Process This table lists the options available. Table 3-2: Target Language Compiler Optional Variables Variable Description −aMaxStackSize=N When local block outputs is enabled, this limits the number of local variables that are declared in a function to not exceed the MaxStackSize (in bytes). N can be any positive integer.
The Real-Time Workshop User Interface Table 3-2: Target Language Compiler Optional Variables (Continued) Variable Description −aFunctionInlineType= "mode" Controls how functions are inlined. There are two modes: • CodeInsertion • PragmaInline Using CodeInsertion, the code is actually inserted where the function call would have be made. PragmaInline directs the Target Language Compiler to declare the function when the appropriate compiler directive occurs.
3 Code Generation and the Build Process Table 3-2: Target Language Compiler Optional Variables (Continued) Variable Description −aWarnNonSaturatedBlocks = value Flag to control display of overflow warnings for blocks that have saturation capability, but have it turned off (unchecked) in their dialog.
The Real-Time Workshop User Interface Retaining the model.rtw File When modifying the target files, you will need to look at the model.rtw file. To prevent the model.rtw file from being deleted after the build process is completed, select the Retain .rtw file check box. Template Makefile The template makefile is used when the Generate code only check box is not selected. The template makefile uniquely identifies the target for which you are creating an executable.
3 Code Generation and the Build Process select the target appropriate to your application. This is a picture of the browser with the generic real-time target selected. Selecting a system target file and clicking OK tells the Real-Time Workshop to use the selected target. The Real-Time Workshop automatically chooses the system target file, template makefile, and make command for the selected target.
The Real-Time Workshop User Interface Table 3-3: Targets Available from the System Target File Browser Target/Code Format System Target File Template Makefile Make Command Relevant Chapters DOS (4GW) drt.tlc drt_watc.tmf make_rtw 9 and 12 Embedded-C for PC or UNIX ert.tlc ert_default_tmf make_rtw 12 Embedded-C for Watcom ert.tlc ert_watc.tmf make_rtw 12 Embedded-C for Visual C/C++ ert.tlc ert_vc.tmf make_rtw 12 Embedded-C for Visual C/C++ Project Makefile ert.tlc ert_msvc.
3 Code Generation and the Build Process Table 3-3: Targets Available from the System Target File Browser (Continued) Target/Code Format System Target File Template Makefile Make Command Relevant Chapters Generic Real-Time for UNIX grt.tlc grt_unix.tmf make_rtw 3 and 12 Generic Real-Time (dynamic) for PC/ UNIX grt_malloc.tlc grt_malloc_default_ tmf make_rtw 3 and 12 Generic Real-Time (dynamic) for Watcom grt_malloc.tlc grt_malloc_watc.
The Real-Time Workshop User Interface Table 3-3: Targets Available from the System Target File Browser (Continued) Target/Code Format System Target File Template Makefile Make Command Relevant Chapters Rapid Simulation Target for Watcom rsim.tlc rsim_watc.tmf make_rtw 12 Rapid Simulation Target for Visual C/C++ rsim.tlc rsim_vc.tmf make_rtw 12 Rapid Simulation Target for Borland rsim.tlc rsim_bc.tmf make_rtw 12 Rapid Simulation Target for UNIX rsim.tlc rsim_unix.
3 Code Generation and the Build Process Generation Options dialog box that varies depending on which system target file configuration you selected in the System Target File Browser. This picture shows an example for grt.tlc.
The Real-Time Workshop User Interface Verbose builds. This feature forces command line display of code generation stages and compiler output. Invariant signals. Note that “invariant constants” are not the same things as “invariant signals.” Invariant signals are block output signals that do not change during Simulink simulation. For example, the signal S3 in this block diagram is an invariant signal.
3 Code Generation and the Build Process Online Help. Placing your mouse over any of these field names or check boxes activates a Help facility that explains what the feature is. This picture shows the Help facility in use. Figure 3-5: Using the Online Help on the Code Generation Options Dialog Box Tunable Parameters If you select Inline parameters on the Real-Time Workshop page, the Tunable parameters button activates. Clicking this button opens the RTW Tunable Parameters dialog box.
The Real-Time Workshop User Interface The RTW Tunable Parameters dialog box supports the following features: • Parameter tuning — de-inline any model parameter by placing its name in the Variable field and clicking Add. This effectively negates the Inline parameters check box for the variables you select. All other model parameters remain inlined. • Storage Class — you can change the storage class of the selected variable.
3 Code Generation and the Build Process your Simulink model; then select Signal Properties under the Edit menu of your model. This opens the Signal Properties dialog box. Refer to Using Simulink for information about these options. The options relevant to the Real-Time Workshop are located in the Signal monitoring and code generation options panel in the bottom half of the dialog box.
The Real-Time Workshop User Interface - Imported Extern — declares the signal as extern. It must then be declared from outside the generated code. - Imported Extern Pointer — declares the signal as an extern pointer. It must then be declared from outside the generated code. These cases are useful if you want to link Real-Time Workshop generated code to other C code (that is, code that the Real-Time Workshop did not generate). Note that you are responsible for correctly linking code modules together.
3 Code Generation and the Build Process Configuring the Generated Code As an alternative to using the Code Generation Options dialog box, you can configure the generated code by appending Target Language Compiler options to the system target filename in the System Target file field on the Real-Time Workshop page of the Simulation Parameters dialog box (see “System Target File” on page 3-7). Your target configuration may have additional options.
Template Makefiles Template Makefiles This section contains a description of how to work with and modify the template makefiles that are used with the Real-Time Workshop. Template makefiles are essentially makefiles in which certain tokens are expanded to create a makefile for your model (model.mk). model.
3 Code Generation and the Build Process Table 3-4: Template Makefile Tokens Expanded by make_rtw (Continued) 3-24 Token Expansion |>MEXEXT<| MEX-file extension. See the MATLAB mexext command. |>MODEL_NAME<| Name of the Simulink block diagram currently being built. |>MODEL_MODULES<| Any additional generated source (.c) modules. For example, you can split a large model into two files, model.c and model1.c. In this case, this token expands to model1.c. |>MODEL_MODULES_OBJ<| Object filenames (.
Template Makefiles Table 3-4: Template Makefile Tokens Expanded by make_rtw (Continued) Token Expansion |>TID01EQ<| Either 1 or 0: Are the sampling rates of the continuous task and the first discrete task equal? |>NCSTATES<| Number of continuous states. |>BUILDARGS<| Options passed to make_rtw. This token is provided so that the contents of your model.mk file will change when you change the build arguments, thus forcing an update of all modules when your build options change.
3 Code Generation and the Build Process Typically, build options are specified as a comment at the top of the template makefile you are using. You need to configure your template makefile if the options that can be passed to make do not provide you with enough flexibility. The Real-Time Workshop uses make since it is a very flexible tool. It lets you control nearly every aspect of building the generated code and run-time interface modules into your real-time program.
Template Makefiles then the make command that will be invoked is: mymake −f model.mk HOST — What platform this template makefile is targeted for. This can be HOST=PC, UNIX, computer_name (see the MATLAB computer command), or ANY. BUILD — This tells make_rtw whether or not (BUILD=yes or no) it should invoke make from the Real-Time Workshop build procedure. SYS_TARGET_FILE — Name of the system target file.
3 Code Generation and the Build Process • The third section defines the tokens make_rtw expands. • The fourth section contains the make rules used in building an executable from the generated source code. The build rules are typically specific to your version of make. The general structure of a template makefile is shown in Figure 3-7 on page 3-29.
Template Makefiles #-- Section 1: Comments ------------------------------------------------------# # Description of what type of target and version of make this template makefile # is for and any optional build arguments. # #-- Section 2: Macros read by make_rtw ---------------------------------------# # The following macros are read by the Real-Time Workshop build procedure: # # MAKE - This is the command used to invoke the make utility. # HOST - What platform this template makefile is targeted for # (i.
3 Code Generation and the Build Process Customizing and Creating Template Makefiles To customize or create a new template makefile, you can copy an existing template makefile to your local working directory and modify it. The make utility processes the model.mk makefile and generates a set of commands based upon dependencies defined in model.mk. For example, to build a program called test, make must link the object files.
Template Makefiles You can use pattern matching expressions to make the dependency rules more general. For example, using GNU Make you could have replaced the two "file1.o: file1.c" and "file2.o: file2.c" rules with the single rule: %.o : %.c cc −c $< The $< is a special macro that equates to the dependency file (i.e., file1.c or file2.c). Thus, using macros and the “%” pattern matching character, the above example can be reduced to: SRCS = file1.c file2.c OBJS = $(SRCS:.c=.
3 Code Generation and the Build Process Generic Real-Time Templates The Real-Time Workshop includes a set of built-in template makefiles that are set up for generic real-time code generation. These template makefiles allow you to simulate your fixed-step models on your workstation. This section discusses these template makefiles: • grt_unix.tmf — targets UNIX platforms using any ANSI C compiler (cc is the default on all platforms except SunOS, where gcc is the default). • grt_vc.
Generic Real-Time Templates • USER_SRCS — Additional user sources, such as files needed by S-functions. For example, suppose you have an S-function called my_sfcn.c, which is built with sfcn_lib1.c, and sfcn_lib2.c. (library routines for use with many S-functions). You can build my_sfcn.c using: mex my_sfcn.c sfcn_lib1.c sfcn_lib2.c In this case, the make command for the Real-Time Workshop should be specified as: make_rtw USER_SRCS="sfcn_lib1.c sfcn_lib2.
3 Code Generation and the Build Process • USER_SRCS — Additional user sources, such as files needed by S-functions. For example, suppose you have an S-function called my_sfcn.c, which is built with sfcn_lib1.c, and sfcn_lib2.c.(library routines for use with many S-functions). You can build my_sfcn.c using: mex my_sfcn.c sfcn_lib1.c sfcn_lib2.c In this case, the make command for the Real-Time Workshop should be specified as: make_rtw USER_SRCS="sfcn_lib1.c sfcn_lib2.
Generic Real-Time Templates built with sfcn_lib1.c, and sfcn_lib2.c. (library routines for use with many S-functions). You can build, my_sfcn.c using: mex my_sfcn.c sfcn_lib1.c sfcn_lib2.c In this case, the make command for the Real-Time Workshop should be specified as: make_rtw USER_SRCS="sfcn_lib1.c sfcn_lib2.c" You can avoid using USER_SRCS by specifying set_param('block','SFunctionModules','sfcn_lib1 sfcn_lib2') See “Using S-Functions with the Real-Time Workshop” in Chapter 3 of Writing S-Functions.
3 Code Generation and the Build Process • USER_OBJS — Additional object (.obj) files, which are to be created from user sources, such as files needed by S-functions.For example, suppose you have an S-function called my_sfcn.c, which is built with sfcn_lib1.c, and sfcn_lib2.c. (library routines for use with many S-functions). You can build, my_sfcn.c using: mex my_sfcn.c sfcn_lib1.c sfcn_lib2.c In this case, the make command for the Real-Time Workshop should be specified as: make_rtw "USER_OBJS=sfcn_lib1.
Generic Real-Time Templates • OPTS — User-specific options, for example, make_rtw OPTS="−DMYDEFINE=1" • OPT_OPTS — grt_bc.tmf optimization options. To turn off optimization and add debugging symbols, specify the −v compiler switch in the make command: make_rtw OPT_OPTS="−v" • USER_SRCS — Additional user sources, such as files needed by S-functions. For example, suppose you have an S-function called my_sfcn.c, which is built with sfcn_lib1.c, and sfcn_lib2.c.
3 Code Generation and the Build Process File and Function Splitting To support compilers with file size limitations, the Real-Time Workshop provides support for splitting the source code whenever the code size exceeds a specified threshold. This option is available with the generic real-time (grt), embedded-C (ert), and rapid simulation (rsim) targets. These targets support: • File splitting • Function splitting • File and function splitting Both file and function splitting require at least Perl v5.000.
File and Function Splitting You must turn off the TLC variable ShowEliminatedStatements for file splitting to work. This is required because the #if ... #endif constructs that surround eliminated statements do not cross file boundaries. Files will only be split at function boundaries. If a source file contains a few long functions, file splitting by itself may not be effective. In this case, you can choose to use both function and file splitting.
3 Code Generation and the Build Process Function Splitting Sometimes a file may not be too large, but a single function contained in the file might be too long. Because of this, your compiler may not be able to perform code optimizations. To solve this problem, you can use function splitting to create smaller functions. You can control function splitting by using the Code Generation Options dialog box. Select Function Splitting from the Function Management pull-down menu.
File and Function Splitting incrementing by one each time the function is split. For example, if your original function is MdlOutput, the split functions will be MdlOuput1 MdlOutput2 and so on. File and Function Splitting You can perform function and file splitting together. To do this, select Function and File Splitting from the Function Management pull-down menu. The rest of the steps are the same as described in the function and file splitting sections respectively.
3 Code Generation and the Build Process 3-42
4 External Mode Introduction . . . . . . . . . . . . . . . . . . . . 4-2 External Mode . . . . . . . . . . . . . . . . . . . . 4-3 Getting Started with External Mode Using grt Setting Up the External Mode Host Environment . Setting External Mode Features . . . . . . . . Running External Mode on Your Target . . . . . . . . . . . . . . . . . . . . . 4-4 4-4 4-5 4-9 External Mode GUI . . . External Mode Control Panel Parameter Tuning . . . . External Mode Operation . The Download Mechanism .
4 External Mode Introduction External mode is a simulation mode provided by the Real-Time Workshop that supports on-the-fly parameter tuning in a real-time environment. “External” refers to the fact that this mode involves two separate computing environments, a host and a target. The host is the computer where MATLAB and Simulink are executing, and the target is the computer where the executable that you create with the Real-Time Workshop runs.
Introduction External Mode Simulink external mode is a mechanism that manages communication between Simulink and stand-alone programs built with the Real-Time Workshop. This mechanism allows you to use a Simulink block diagram as a graphical front end to the corresponding program (i.e., the program built from code generated for that block diagram). In external mode, whenever you change parameters in the block diagram, Simulink automatically downloads them to the executing program.
4 External Mode Getting Started with External Mode Using grt This section provides a step-by-step set of instructions for getting started with external mode. Since the example presented is shown using the generic real-time (grt) target, you don’t need any hardware other than your basic computer setup to get the example running. This process, running the generated executable on the host computer, is known as self-targeting.
Getting Started with External Mode Using grt the Stop Time set to its default value. Set the Decimation to 1 (no decimation). 3 On the Workspace I/O page, select Time and Output. By default the variable names should be tout and yout. 4 On the Real-Time Workshop page, click the Browse button and select the generic real-time target (default for PC and UNIX). For a description of the System Target File Browser, see “The System Target File Browser” on page 3-11.
4 External Mode select External Mode Control Panel under the Tools menu. This dialog box opens. These three buttons open three separate dialog boxes. The top four buttons for use after you have started your real-time program on your target. The three lower buttons open three separate dialog boxes: • The Target Interface button opens the External Target Interface dialog box, which configures the external mode communications channel.
Getting Started with External Mode Using grt To open the External Target Interface dialog box, click the Target Interface button. The dialog box should look like this. Specify ext_comm here. This is the MEX-file that provides TCP communication for the executable created by the grt target. Signals & Triggering The model is nearly ready to build. Click the Signal & triggering button on the External Mode Control Panel. This opens the External Data Logging Configuration dialog box.
4 External Mode The dialog box should look like this when you’re finished. Prior to building your model, you must select values for gains A and B. The example discussed here uses A=2 and B=3. Once you’ve selected two values, click the Build button to generate code in external mode. Note: You do not need to specify any data archiving options for this example. See “External Mode GUI” on page 4-10 for a complete description of all available options for external model.
Getting Started with External Mode Using grt Running External Mode on Your Target To run external mode, you must open an MS-DOS command prompt (on UNIX systems, an Xterm window). At the MS-DOS command prompt, type modelname -tf 0 and the model that you’ve created will execute. The -tf switch overrides the stop time set for the model in Simulink. The 0 value directs the model to run indefinitely. Under the Simulation menu of your model, select Connect to target.
4 External Mode External Mode GUI The Real-Time Workshop provides an extensive graphical user interface (GUI), which includes four separate windows, that supports a wide variety of features in external mode. The four windows include the following: • External Mode Control Panel • External Target Interface dialog box • External Signal & Triggering dialog box • External Data Archiving dialog box The next sections discuss each of these in turn.
External Mode GUI Target Interface Pressing the Target Interface button activates the External Target Interface dialog box. Specify ext_comm here for grt and Tornado targets, win_tgt for the Real-Time Windows Target, or the name of a third party external mode link. By default, leave this blank.
4 External Mode External Signal & Triggering Pressing the Signal & Triggering button activates the External Signal & Triggering dialog box. This windows provides support for: • Signal selection — specify which Scope blocks are active in external mode • Trigger selection — select the signal that defines when to display data in Scope blocks. • Trigger options — configure how and when to display data in Scope blocks Signal Selection. External mode currently supports Scope blocks for signal selection.
External Mode GUI Trigger Signal Selection. You select a trigger signal by choosing it from the Signal selection list and pressing the Trigger signal button. A ‘T’ appears to the left of the block’s name if you have chosen it as a trigger. Note that this setting only applies when the Trigger source has been set to signal. Trigger Options. There are various options available under the Trigger panel located at the bottom of the External Signal & Triggering dialog box: • Source — manual or signal.
4 External Mode If you have selected a trigger, the Trigger signal panel activates. The Trigger signal panel By default, any element of the first input port of the specified block can cause the trigger to fire (i.e., Port 1, any element). You can modify this behavior by adjusting the Port and Element fields located on the right side of the Trigger panel. The Port field accepts a number or the keyword last. The Element field accepts a number or the keywords any and last.
External Mode GUI Data Archiving Pressing the Data Archiving button opens the External Data Archiving dialog box. This panel supports various features in external mode, including: • Directory notes — directory level annotation • File notes — file level annotation • Data archiving — Automated data logging and storage Directory Notes. Pressing the Edit directory note button opens the MATLAB editor. Place comments in this window that you want saved in the specified directory. File Notes.
4 External Mode intermediate result. Since the trigger can fire at any time, writing intermediate results to the workspace generally results in unpredictable overwriting of the workspace variables. For this reason, the default behavior is to write only the results from the final one-shot to the workspace. The intermediate results are discarded.
External Mode GUI This picture shows the External Data Archiving dialog box with enabled archiving. Unless you select Enable archiving, entries for the Directory and File fields are not accepted. Parameter Tuning You can set parameter tuning options on the External Mode Control Panel. The batch download check box enables/disables batch parameters changes. When batch mode is enabled, changes made to block parameters are stored locally and sent only after you have pressed the Download button.
4 External Mode This picture shows the External Mode Control Panel with the batch download option activated: “Parameter changes pending” appears here if you have unsent parameter value changes. External Mode Operation When external mode is enabled, Simulink does not simulate the system represented by the block diagram. Instead, it performs an Update Diagram and downloads current values of all parameters as soon as you start external mode.
External Mode GUI The Simulink side initiates the parameter download operation by calling a procedure on the external program side. In the general terminology of client/ server computing, this means the Simulink side is the client and the external program is the server. The two processes can be remote, in which case a communication protocol is used to transfer data, or they can be local and employ shared memory to transfer data. The following diagram illustrates this relationship.
4 External Mode Limitations In general, you cannot change a parameter if doing so results in a change in the structure of the model. For example, you cannot change: • The number of states, inputs, or outputs of any block • The sample time or the number of sample times • The integration algorithm for continuous systems • The name of the model or of any block • The parameters to the Fcn block If you cause any of these changes to the block diagram, then you must rebuild the program with newly generated code.
External Mode GUI The following section discusses how to use external mode with real-time programs on a UNIX or PC system. Chapter 8, “Targeting Tornado for Real-Time Applications,” illustrates the use of external mode in the Tornado environment.
4 External Mode Using the TCP Implementation This section describes how to use the TCP-based client/server implementation provided with the Real-Time Workshop. In order to use Simulink external mode, you must: • Specify the name of the external interface MEX-file in the External Target Interface dialog box. • Configure the template makefile so that it links the proper source files for the TCP server code and defines the necessary compiler flags when building the generated code.
Using the TCP Implementation UNIX or PC Host Target Simulink in External Mode Target Code Process block parameter ext_server.c Update block ext_comm.mex TCP/IP on Ethernet External Mode Message Format header data in target format Figure 4-2: TCP-based Client/Server Implementation for External Mode The following sections discuss the details of how to use the external mode of Simulink.
4 External Mode The External Interface MEX-File You must specify the name of the external interface MEX-file in the External Target Interface dialog box: Enter the name of the external interface MEX-file in the box (you do not need to enter the .mex extension). This file must be in the current directory or in a directory that is on your MATLAB path. You may be required to provide arguments to the MEX-file.
Using the TCP Implementation You must specify these options in order. For example, if you want to specify the verbosity level (the second argument), then you must also specify the target host name (the first argument). Note that you can also specify verbosity level and port number as options in the external program. See “Running the External Program” on page 4-25 for more information. External Mode Support The generic real-time and Tornado targets have support for external mode.
4 External Mode Enabling External Mode To enable external mode, display the Simulink block diagram and select External from the Simulation menu: Next, select Start from the Simulation menu, as you would to begin a simulation and change parameters as desired. Possible Error Conditions If the Simulink block diagram does not match the external program, Simulink displays an error box informing you that the checksums do not match (i.e., the model has changed since you generated code).
Using the TCP Implementation Creating an External Mode Communication Channel The Real-Time Workshop provides support for TCP/IP through ext_comm. When creating your own custom target for a new board, you may choose to use another communications protocol.
4 External Mode 4-28
5 Data Logging and Signal Monitoring MAT-File Data Logging . . . . . . . . . . . . . . . 5-2 Singletasking versus Multitasking MAT-File Logging . . . . . . . . . . . . . . . . 5-3 C API for Signal Monitoring . . . . . . . . . . . . . 5-4 Using BlockIOSignals to Obtain Block Outputs . . . .
5 Data Logging and Signal Monitoring MAT-File Data Logging For the Real-Time Workshop targets that have access to a disk, you can use MAT-file logging to examine the results of the real-time program. Real-Time Workshop targets can create a MAT-file that logs system states and outputs at each model execution time step. Some provide more options than others; for example, the rapid simulation target (rsim) provides enhanced logging configurations.
MAT-File Data Logging Singletasking versus Multitasking MAT-File Logging When logging data you will notice differences in the logging of: • Noncontinuous root outports • Discrete states in singletasking vs. multitasking environments. In multitasking mode, the logging of states and outputs is done after the first task execution (and not at the end of the first time step). In singletasking mode, the Real-Time Workshop logs states and outputs after the first time step.
5 Data Logging and Signal Monitoring C API for Signal Monitoring Signal monitoring provides a second method for accessing block outputs in an externally running program. All block output data is written to the SimStruct with each time step in the model code. However, to access the output of any given block in the SimStruct, you must know the address of the BlockIO vector where the data is stored, how many output ports the block has, and the width of each output.
Using BlockIOSignals to Obtain Block Outputs Using BlockIOSignals to Obtain Block Outputs The BlockIOSignals data structure is declared as follows: typedef struct BlockIOSignals_tag { char_T *blockName; /* Block's full pathname (mangled by the Real-Time Workshop) */ char_T *signalName; /* Signal label (unmangled) */ uint_T portNumber; /* Block output port number (start at 0) */ uint_T signalWidth; /* Signal's width */ void *signalAddr; /* Signal's address in the blockIO vector */ char_T *dtName; /* The C l
5 Data Logging and Signal Monitoring The model code file model.bio defines an array of BlockIOSignals structures, for example: #include "bio_sig.h" /* Block output signal information */ const BlockIOSignals rtBIOSignals[] = { /* blockName, signalName, portNumber, signalWidth, signalAddr, dtName, dtSize */ { "simple/Constant", NULL, 0, 1, &rtB.Constant, "double", sizeof(real_T) }, { "simple/Constant1", NULL, 0, 1, &rtB.Constant1, "double", sizeof(real_T) }, { "simple/Gain", "accel", 0, 2, &rtB.
Using BlockIOSignals to Obtain Block Outputs You must then write code that walks through the rtBIOSignals array and chooses the signals to be monitored based on the blockName and signalName or portNumber. How the signals are monitored is up to you. For example, you could collect the signals at every time step or just sample them asynchronously by a separate, lower priority task. For example, the Tornado source file, rt_main.
5 Data Logging and Signal Monitoring continue; } } /*install/remove the signals*/ for (w = 0; w < blockInfo->signalWidth; w++) { sprintf(name, "%s_%d_%s_%d", blockName, blockInfo->portNumber, (blockInfo->signalName==NULL)?"":blockInfo->signalName, w); if (install) { /*install*/ if (!ScopeInstallSignal(name, "units", (void *)((int)blockInfo->signalAddr + w*blockInfo->dtSize), blockInfo->dtName, 0)) { fprintf(stderr,"rtInstallRemoveSignals: ScopeInstallSignal " "possible error: over 256 signals.
Using BlockIOSignals to Obtain Block Outputs Below is an excerpt from an example routine that collects signals taken from the main simulation loop: /******************************************* * Step the model for the base sample time * *******************************************/ MdlOutputs(FIRST_TID); #ifdef MAT_FILE if (rt_UpdateTXYLogVars(S) != NULL) { fprintf(stderr,"rt_UpdateTXYLogVars() failed\n"); return(1); } #endif #ifdef STETHOSCOPE ScopeCollectSignals(0); #endif MdlUpdate(FIRST_TID);
5 Data Logging and Signal Monitoring 5-10
6 Program Architecture Introduction . . . . . . . . . . . . . . . . . . . . 6-2 Model Execution . . . . . . . . . . Program Timing . . . . . . . . . . . Program Execution . . . . . . . . . . External Mode Communication . . . . . Data Logging . . . . . . . . . . . . Logging Differences Between Singletasking and Multitasking Model Execution . Differences Between Rapid Prototyping and Embedded Model Execution . . Rapid Prototyping Model Functions . . . Embedded Model Functions . . . . . . . . . . . . . . . .
6 Program Architecture Introduction The Real-Time Workshop generates two styles of code. One code style is suitable for rapid prototyping (and simulation via code generation). The other style is suitable for embedded applications. This chapter discusses the program architecture, that is, the structure of the Real-Time Workshop generated code, associated with these two styles of code. The table below classifies the targets shipped with the Real-Time Workshop.
Introduction Table 6-1: Code Styles Listed By Target Target Code Style (using C unless noted) S-function Target Rapid prototyping — creates a C-MEX S-function for simulation of your model within another Simulink model. Tornado (VxWorks) Real-Time Target Rapid prototyping — runs model in real-time using the VxWorks real-time operating system tasking primitives. Also useful as a starting point for targeting a real-time operating system.
6 Program Architecture Model Execution Before looking at the two styles of generated code, you need to have a high-level understanding of how the generated model code is executed. The Real-Time Workshop generates algorithmic code as defined by your model. You may include your own code into your model via S-functions. S-functions can range from high-level signal manipulation algorithms to low level device drivers.
Model Execution a given simulation time step. In minor time steps, the run-time interface integrates the derivatives to update the continuous states. • ModelUpdate — Calling all blocks in your model that have a sample hit at the current point in time and having them update their discrete states or similar type objects. • ModelDerivatives — Calling all blocks in your model that have continuous states and having them update their derivatives. ModelDerivatives is only called in minor time steps.
6 Program Architecture During the ModelOutputs and ModelUpdate phases of model execution, only blocks that have hit the current point in time execute. They determine if they have hit by using a macro (ssIsSampleHit, or ssIsSpecialSampleHit) that checks for a sample hit. The pseudocode below shows the execution of a model for a multitasking simulation (nonreal-time). main() { Initialization While (time < final time) ModelOutputs(tid=0) -- Major time step. LogTXY -- Log time, states, and root outports.
Model Execution Note that the multitasking execution assumes that all tasks are multiples of the base rate. Simulink enforces this when you have created a fixed-step multitasking model. The multitasking execution loop is very similar to that of singletasking, except for the use of the task identifier (tid) argument to ModelOutputs and ModelUpdate. The ssIsSampleHit or ssIsSpecialSampleHit macros use the tid to determine when blocks have a hit.
6 Program Architecture The pseudocode below shows the execution of a model in a real-time singletasking system where the model is run at interrupt level. rtOneStep() { Check for interrupt overflow Enable "rtOneStep" interrupt ModelOutputs -- Major time step. LogTXY -- Log time, states and root outports. ModelUpdate -- Major time step. Integrate -- Integration in minor time step for models -- with continuous states.
Model Execution continuous blocks, then the integration step size determines the base sample rate. For example, if the model code is a controller operating at 100 Hz, then every 0.01 seconds the background task is interrupted. During this interrupt, the controller reads its inputs from the analog-to-digital converter (ADC), calculates its outputs, writes these outputs to the digital-to-analog converter (DAC), and updates its states. Program control then returns to the background task.
6 Program Architecture This code shows how a model executes in a real-time multitasking system (where the model is run at interrupt level). rtOneStep() { Check for interrupt overflow Enable "rtOneStep" interrupt ModelOutputs(tid=0) -- Major time step. LogTXY -- Log time, states and root outports. ModelUpdate(tid=0) -- Major time step. Integrate -- Integration in minor time step for -- models with continuous states.
Model Execution Running models at interrupt level in real-time multitasking environment is very similar to the previous singletasking environment, except that overlapped interrupts are employed for concurrent execution of the tasks. The execution of a model in a singletasking or multitasking environment when using real-time operating system tasking primitives is very similar to the interrupt-level examples discussed above.
6 Program Architecture occurs. The clock tick gives a clockSem (clock semaphore) to the model task (tSingleRate). The model task will wait for the semaphore before executing. The clock ticks are configured to occur at the fundamental step size (base rate) for your model. The pseudocode below is for a multitasking model using real-time tasking primitives. tSubRate(subTaskSem,i) { Loop: Wait on semaphore subTaskSem.
Model Execution EndMainLoop } main() { Initialization Start/spawn task "tSingleRate". Start clock that does a "semGive" on a clockSem semaphore. Wait on "model-running" semaphore. Shutdown } In this multitasking environment, the model is executed using real-time operating system tasking primitives. In this environment, it is necessary to create several model tasks (tBaseRate and several tSubRate tasks) to run the model code. The base rate task (tBaseRate) has a higher priority than the subrate tasks.
6 Program Architecture The following diagram illustrates interrupt timing. Sample interval is appropriate for this model code execution. time Time to execute the model code Time available to process background tasks Sample interval is too short for this model code execution. time Time to execute the model code Figure 6-2: Task Timing The sample interval must be long enough to allow model code execution between task invocations.
Model Execution Program Execution As the previous section indicates, a real-time program may not require 100% of the CPU’s time. This provides an opportunity to run background tasks during the free time. Background tasks include operations like writing data to a buffer or file, allowing access to program data by third-party data monitoring tools, or using Simulink external mode to update program parameters.
6 Program Architecture that have a task identifier of 0. This results in differences in the logged values between singletasking and multitasking logging. Specifically, consider a model with two sample times, the faster sample time having a period of 1.0 second and the slower sample time having a period of 10.0 seconds. At time t = k*10, k=0,1,2... both the fast (tid=0) and slow (tid=1) blocks have a hit.
Model Execution name, parameter and signal storage class are included as part of the API for the embedded style of code. The single largest difference between the rapid prototyping and embedded style of generated code is that the embedded code does not contain the SimStruct data structure. The SimStruct defines a common API that the rapid prototyping style of generated code relies heavily on.
6 Program Architecture model.reg), execute, the run-time interface starts execution by calling MdlStart. This routine is called once at start-up. The function MdlStart has four basic sections: - Code to initialize the states for each block in the root model that has states. A subroutine call is made to the “initialize states” routine of conditionally executed subsystems. - Code generated by the one-time initialization (start) function for each block in the model.
Model Execution • MdlTerminate(void) — MdlTerminate contains any block shutdown code. MdlTerminate is called by the run-time interface, as part of the termination of the real-time program. The contents of the above functions are directly related to the blocks in your model. A Simulink block can be generalized to the following set of equations: y = f 0 ( t, x c, x d, u ) Output, y, is a function of continuous state, xc, discrete state, xd, and input, u.
6 Program Architecture The general content of the rapid prototyping style of code for C is shown in the following figure. /* * Version, Model options, TLC options, * and code generation information are placed here. */ void MdlStart(void) { /* * State initialization code. * Model start-up code - one time initialization code. * Execute any block enable methods. * Initialize output of any blocks with constant sample times.
Model Execution A flow chart describing the execution of the rapid prototyping generated code is shown below. Start Execution MdlStart MdlOutput MdlDerivatives MdlOutput MdlDerivatives Integration Execution Loop MdlUpdate MdlTerminate End Figure 6-4: Rapid Prototyping Execution Flow Chart Each block places code into specific Mdl routines according to the algorithm that it is implementing. Blocks have input, output, parameters, states, plus other general items.
6 Program Architecture Block outputs can also go to the external output structure (rtY). The following figure shows the general mapping between these items. External Inputs Struct, rtU rtGround External Outputs Struct, Block I/O Struct, rtB rtY Block Work Structs, States Struct, Parameter Struct, rtX rtP rtRWork, rtIWork, rtPWork, .... Figure 6-5: Data View of the Generated Code Structure definitions: • Block I/O Structure (rtB) — This structure consists of all block output signals.
Model Execution The states structure has two sections: the first is for the continuous states; the second is for the discrete states. • Block Parameters Structure (rtP) — The parameters structure contains all block parameters that can be changed during execution (e.g., the parameter of a Gain block). • External Inputs Structure (rtU) —The external inputs structure consists of all root-level Inport block signals.
6 Program Architecture When compared with the rapid prototyping environment, these functions are very similar.
Rapid Prototyping Program Framework Rapid Prototyping Program Framework Generating code for a Simulink model results in at least four files — model.c, model.h, model.prm, and model.reg, where model is the name of the Simulink model. This code implements the model’s system equations, contains block parameters, and performs initialization. The Real-Time Workshop’s program framework provides the additional source code necessary to build the model code into a complete, stand-alone program.
6 Program Architecture Rapid Prototyping Real-Time Program Architecture System Dependent Components Main Program Timing Interrupt handling I/O drivers Data logging System Independent Components Integration solvers: ode1.c — ode5.c Model execution scheduler: rt_sim.c SimStruct: simstruc.h External mode communication Run-Time Interface Application Components Generated (Model) Code MdlOutputs, etc. Inlined S-functions Model parameters Noninlined S-functions mysfun.
Rapid Prototyping Program Framework modules that implement the functions carried out by the system dependent, system independent, and application components. Rapid Prototyping System Dependent Components These components contain the program’s main function, which controls program timing, creates tasks, installs interrupt handlers, enables data logging, and performs error checking. The way in which application modules implement these operations depends on the type of computer.
6 Program Architecture Model Execution • Execute a background task, for example, communicate with the host during external mode simulation or introduce a wait state until the next sample interval. • Execute model (initiated by interrupt). • Log data to buffer (if data logging is used). • Return from interrupt. Program Termination • Call a function to terminate the program if it is designed to run for a finite time — destroy the SimStruct, deallocate memory, and write data to a file.
Rapid Prototyping Program Framework Model Execution At each sample interval, the main program passes control to the model execution function, which executes one step though the model. This step reads inputs from the external hardware, calculates the model outputs, writes outputs to the external hardware, and then updates the states. The following diagram illustrates these steps.
6 Program Architecture Integration of Continuous States The real-time program calculates the next values for the continuous states based on the derivative vector, dx/dt, for the current values of the inputs and the state vector. These derivatives are then used to calculate the next value of the states using a state-update equation. This is the state-update equation for the first order Euler method (ode1).
Rapid Prototyping Program Framework Application Modules for System Independent Components The system independent components include these modules: • rt_sim.c — Performs the activities necessary for one time step of the model. It calls the model function to calculate system outputs and then updates the discrete and continuous states. • ode1.c, ode2.c, ode3.c, ode4.c, ode5.c — These modules implement the integration algorithms supported for real-time applications.
6 Program Architecture • Initialize a vector of sample times and sample time offsets and store this vector in the SimStruct. • Store the values of the block initial conditions and program parameters in the SimStruct. • Compute the block and system outputs. • Update the discrete state vector. • Compute derivatives for continuous models. • Perform an orderly termination at the end of the program (when the current time equals the final time, if a final time is specified).
Rapid Prototyping Program Framework Model Code Main Program Initialization Model registration function — model Initialize sizes in the SimStruct — MdlInitializeSizes Initialize sample times and offsets — MdlInitializeSampleTimes Start model (initialize conditions, etc.
6 Program Architecture automatically incorporates your non-inlined C code S-functions into the program if they adhere to the S-function API described in the Simulink documentation. This format defines functions and a SimStruct that are local to the S-function. This allows you to have multiple instances of the S-function in the model. The model’s SimStruct contains a pointer to each S-function’s SimStruct.
Rapid Prototyping Program Framework Application Modules for Application Components When the Real-Time Workshop generates code, it produces the following files: • model.c — The C code generated from the Simulink block diagram. This code implements the block diagram’s system equations as well as performing initialization and updating outputs. • model.h — Header file containing the block diagram’s simulation parameters, I/O structures, work structures, etc. • model_export.
6 Program Architecture Embedded Program Framework The embedded program framework and architecture is outlined by the following figure. Embedded Real-Time Program Architecture System Dependent Components Main Program Timing Interrupt handling I/O drivers Data logging System Independent Components Integration solvers: ode1.c — ode5.c Model execution scheduler: rt_sim.c Run-time Interface Application Components Generated (Model) Code MdlOutputs, etc.
Embedded Program Framework Note the similarity between this architecture and the rapid prototyping architecture on page 6-26. The main difference is the lack of the SimStruct data structure and the removal of the noninlined S-functions. Using this figure, you can compare the embedded style of generated code with the rapid prototyping style of generated code of the previous section. Most of the rapid prototyping explanations in the previous section hold for the embedded target.
6 Program Architecture 6-38
7 Models with Multiple Sample Rates Introduction . . . . . . . . . . . . . . . . . . . . 7-2 Single Versus Multitasking Environments . Executing Multitasking Models . . . . . . . . Multitasking and Pseudomultitasking . . . . . Building the Program for Multitasking Execution Singletasking . . . . . . . . . . . . . . . Building the Program for Singletasking Execution Model Execution . . . . . . . . . . . . . . Simulating Models with Simulink . . . . . . . Executing Models in Real-Time . . . . . . . . . . . .
7 Models with Multiple Sample Rates Introduction Every Simulink block can be classified according to its sample time as constant, continuous-time, discrete-time, inherited, or variable. Examples of each type include: • Constant — Constant block, Width • Continuous-time — Integrator, Derivative, Transfer Function • Discrete-time — Unit Delay, Digital Filter • Inherited — Gain, Sum, Lookup Table • Variable — These are S-functions blocks that set their time of next hit based upon current information.
Single- Versus Multitasking Environments Single- Versus Multitasking Environments There are two basic ways in which you can execute a fixed-step Simulink model — singletasking and multitasking. You use the Solver options pull-down menu on the Solver page of the Simulation Parameters dialog box to specify how to execute your model. The default is auto, which specifies that your model will use multitasking if your model contains two or more different rates. Otherwise, it will use singletasking.
7 Models with Multiple Sample Rates Real-Time Clock Hardware Interrupt Service Routine Interrupt Save Context Execute Model Program execution using an interrupt service routine (bareboard, with no real-time operating system). See the grt target for an example. Collect Data Restore Context Real-Time Clock Hardware Interrupt Service Routine Context Switch Model Execution Task Interrupt semGive semTake Execute Model Program execution using a real-time operating system primitives.
Single- Versus Multitasking Environments Executing Multitasking Models In cases where the continuous part of a model executes at a rate that is different from the discrete part, or a model has blocks with different sample rates, the code assigns each block a task identifier (tid) to associate it with the task that executes at its sample rate. Certain restrictions apply to the sample rates that you can use: • The sample rate of any block must be an integer multiple of the base (i.e.
7 Models with Multiple Sample Rates The following diagrams illustrate how mixed-rate systems are handled by the Real-Time Workshop in these two environments. t0 t1 t2 t3 t4 rate 1 Highest Priority rate 2 rate 3 Lowest Priority Vertical arrows indicate sample times. Dotted lines with downward pointing arrows indicate the release of control to a lower priority task. Dark gray areas indicate task execution. Hashed areas indicate task preemption by a higher priority task.
Single- Versus Multitasking Environments Interrupt 0 Begins t0 Interrupt 1 t1 Interrupt 2 Begins t2 Interrupt 3 t3 t4 Highest Priority Interrupt 2 Ends Interrupt 0 Ends Lowest Priority Figure 7-3: Pseudomultitasking Using Overlapped Interrupts This diagram illustrates how overlapped interrupts are used to implement pseudomultitasking. Note that in this case, Interrupt 0 does not return until after Interrupts 1, 2, and 3.
7 Models with Multiple Sample Rates Singletasking It is possible to execute the model code in a strictly singletasking manner. While this method is less efficient with regard to execution speed, in certain situations it may allow you to simplify your model. In a singletasking environment, the base sample rate must define a time interval that is long enough to allow the execution of all blocks within that interval.
Single- Versus Multitasking Environments Simulating Models with Simulink Before Simulink simulates a model, it orders all of the blocks based upon their topological dependencies. This includes expanding subsystems into the individual blocks they contain and flattening the entire model into a single list. Once this step is complete, each block is executed in order. The key to this process is the proper ordering of blocks. Any block whose output is directly dependent on its input (i.e.
7 Models with Multiple Sample Rates See “Multitasking and Pseudomultitasking” on page 7–5 for a description of how this works. It is important to understand that section before proceeding here. Multitasking Operation The use of multitasking can improve the efficiency of your program if the model is large and has many blocks executing at each rate. It can also degrade performance if your model is dominated by a single rate, and only a few blocks execute at a slower rate.
Sample Rate Transitions Sample Rate Transitions There are two possible sample rate transitions that can exist within a model: • A faster block driving a slower block • A slower block driving a faster block In singletasking systems, there are no issues involved with multiple sample rates. In multitasking and pseudomultitasking systems, however, differing sample rates can cause problems. To prevent possible errors in calculated data, you must control model execution at these transitions.
7 Models with Multiple Sample Rates In transitioning from slower to faster blocks, you must add Unit Delay blocks between slow to fast transitions and set the sample rate of the Unit Delay to that of the slower block: T = 2 sec T = 1 sec Slower Block Faster Block becomes T = 2 sec T = 2 sec T = 1 sec Unit Delay Slower Block Faster Block Figure 7-7: Transitioning from Slower to Faster Blocks (T = Sample Period) The next four sections describe the theory and reasons why Unit Delay and Zero-Orde
Sample Rate Transitions Simulink does not execute in real-time, which means that it is not bound by real-time constraints. Simulink waits for, or moves ahead to, whatever tasks are necessary to complete simulation flow. The actual time interval between sample time steps can vary. Faster to Slower Transitions in Real-Time In models where a faster block drives a slower block, you must compensate for the fact that execution of the slower block may span more than one execution period of the faster block.
7 Models with Multiple Sample Rates The sample time of the Zero Order Hold block must be set to 2 sec (i.e., the sample time of the slower block). T = 1 sec T = 2 sec Zero-Order Hold Faster Block T = 2 sec Slower Block The Zero Order Hold block executes at the sample rate of the slower block, but with the priority of the faster block. t0 t2 2 Sec Task T=0.5 T=2s t2 t1 t0 1 Sec Task T=0.
Sample Rate Transitions t0 T = 2 sec T = 1 sec Slower Block Faster Block t1 T=2s T=1s t2 t3 T=2s T=1s T=1s T=1s Time As you can see from the preceding diagrams, Simulink can simulate models with multiple sample rates in an efficient manner. However, Simulink does not operate in real-time. Slower to Faster Transitions in Real-Time In models where a slower block drives a faster block, the generated code assigns the faster block a higher priority than the slower block.
7 Models with Multiple Sample Rates This timing diagram illustrates two problems: 1 Execution of the slower block is split over more than one faster block interval. In this case the faster task executes a second time before the slower task has completed execution. This means the inputs to the slower task can change, causing unpredictable results. 2 The faster block executes before the slower block (which is backwards from the way Simulink operates).
Sample Rate Transitions 2 2 Sec Task 1/z update T=2s t1 t0 1 Sec Task 1/z T=1s output t2 1 1 T=1s t3 1 3 1/z update T=2s 1/z T=1s output 1 T=1s Time Three key points about this diagram: 1 Unit delay output runs in 1 sec task, but only at its rate (2 sec). The output of the unit delay block feeds the 1 sec task blocks. 2 The unit delay update uses the output of the 2 sec task in its update of its internal state. 3 The unit delay update uses the state of the unit delay in the 1 sec task.
7 Models with Multiple Sample Rates Note Inserting a Unit Delay block changes the model. The output of the slower block is now delayed by one time step compared to the output without a Unit Delay.
8 Targeting Tornado for Real-Time Applications Introduction . . . . . . . . . . . . . . . . . . . . 8-2 Confirming Your Tornado Setup Is Operational . . . . . . 8-2 VxWorks Library . . . . . . . . . . . . . . . . . . . 8-3 Run-time Architecture Overview . . . . . . . . . . 8-5 Parameter Tuning and Monitoring . . . . . . . . . . . 8-5 Run-Time Structure . . . . . . . . . . . . . . . . . 8-8 Implementation Overview . . . . . . Adding Device Driver Blocks . . . . . . Configuring the Template Makefile . . .
8 Targeting Tornado for Real-Time Applications Introduction This chapter describes how to create real-time programs for execution under VxWorks, which is part of the Tornado environment. The VxWorks real-time operating system is available from Wind River Systems, Inc. It provides many UNIX-like features and comes bundled with a complete set of development tools.
Introduction for additional information about installation and operation of VxWorks and Tornado products. VxWorks Library Selecting VxWorks Support under the Real-Time Workshop library in the Simulink Library Browser opens the VxWorks Support library.
8 Targeting Tornado for Real-Time Applications There is a second sublibrary, the IO Devices library, that contains support for these drivers: • Matrix MS-AD12 • Matrix MS-DA12 • VME Microsystems VMIVM-3115-1 • Xycom XVME-500/590 • Xycom XVME-505/595 Each of these blocks has online help available through the Help button on the block’s dialog box. Refer to the manufacturer’s documentation for detailed information on these blocks.
Run-time Architecture Overview Run-time Architecture Overview In a typical VxWorks-based real-time system, the hardware consists of a UNIX or PC host running Simulink connected to a VxWorks target CPU via Ethernet. In addition, the target chassis may contain I/O boards with A/D and D/A converters to communicate with external hardware. The following diagram shows the arrangement: Host VxWorks Target Simulink Real-Time Workshop Target CPU Tornado Compiler ADC/DAC Boards Ethernet Port model.
8 Targeting Tornado for Real-Time Applications External Mode Simulink external mode provides a mechanism to download new parameter values to the executing program and to monitor signals in your model. In this mode, the external link MEX-file sends a vector of new parameter values to the real-time program via the network connection. These new parameter values are sent to the program whenever you make a parameter change without requiring a new code generation or build iteration.
Run-time Architecture Overview Note You may need to enter a routing table entry into VxWorks if your host is not on the same local network (subnet) as the VxWorks system. See routeAdd in the VxWorks Reference Guide for more information. Configuring Simulink to Use Sockets Simulink external mode uses a MEX-file to communicate with the VxWorks system. The MEX-file is matlabroot/toolbox/rtw/ext_comm.* where * is a host-dependent MEX-file extension. See Chapter 4, “External Mode,” for more information.
8 Targeting Tornado for Real-Time Applications StethoScope With StethoScope, you can access the output of any block in the model (in the real-time program) and display this data on a host. Signals are installed in StethoScope by the real-time program using the BlockIOSignals data structure or, interactively from the WindSh while the real-time program is running. To use StethoScope interactively, see the StethoScope User’s Manual.
Run-time Architecture Overview The program creates VxWorks tasks to run on the real-time system: one communicates with Simulink, the others execute the model. StethoScope creates its own tasks to collect data. Host Processes There are two processes running on the host side that communicate with the real-time program: • Simulink running in external mode.
8 Targeting Tornado for Real-Time Applications Multitasking. Optionally, the model can run as multiple tasks, one for each sample rate in the model. • tBaseRate — This task executes the components of the model code run at the base (highest) sample rate. By default, it runs at a relatively high priority (30), which allows it to execute without interruption from background system activity. • tRaten — The program also spawns a separate task for each additional sample rate in the system.
Implementation Overview Implementation Overview To implement and run a VxWorks-based real-time program using the Real-Time Workshop, you must: • Design a Simulink model for your particular application • Add the appropriate device driver blocks to the Simulink model, if desired • Configure the tornado.
8 Targeting Tornado for Real-Time Applications Generated Code f14.c f14.h f14.prm f14.reg f14.bio Main Program rt_main.c Model Execution rt_sim.c Template Makefile tornado.tmf Integration Module ode5.c Simulink Data Structure simstruc.h Makefile f14.mk Executable File f14.lo Data Logger rtwlog.c External mode ext_svr.c ext_svr.h ext_msg.h Figure 8-3: Source Modules Used to Build the VxWorks Real-Time Program This diagram illustrates the code modules used to build a VxWorks real-time program.
Implementation Overview Adding Device Driver Blocks The real-time program communicates with the I/O devices installed in the VxWorks target chassis via a set of device drivers. These device drivers contain the necessary code that runs on the target processor for interfacing to specific I/O devices. To make device drivers easy to use, they are implemented as Simulink S-functions using C code MEX-files.
8 Targeting Tornado for Real-Time Applications Edit the following lines to reflect your setup. VX_TARGET_TYPE = 68k CPU_TYPE = MC68040 Downloading Configuration In order to perform automatic downloading during the build process, the target name and host name that the Tornado target server will run on must be specified. Modify these macros to reflect your setup.
Implementation Overview Specifying the Real-Time Build Options Set the real-time build options using the Solver and Real-Time Workshop pages of the Simulation Parameters dialog box. To access this dialog box, select Parameters from the Simulink Simulation menu: Solver Page Real-Time Workshop Page For models with continuous blocks, set the Type to Fixed-step, the Step Size to the desired integration step size, and select the integration algorithm.
8 Targeting Tornado for Real-Time Applications Next, use the System Target File Browser to select the correct Real-Time Workshop page settings for Tornado. You can open the browser by pressing the Browse button on the Real-Time Workshop page of the Simulation Parameters dialog box. Selecting “Tornado (VxWorks) Real-Time Target” sets the following: • System target file — tornado.tlc • Template makefile — tornado.
Implementation Overview Build Command Options. You can specify build command options on the Code Generation Options dialog box. Click the Options button on the Real-Time Workshop to activate this dialog box. The Real-Time Workshop provides flags that set the appropriate macros in the template makefile, causing any necessary additional steps to be performed during the build process.
8 Targeting Tornado for Real-Time Applications • MATLAB MAT-file — to enable data logging during program execution, check MAT-file logging. The program will create a file named MODEL.mat at the end of program execution; this file will contain the variables that you specified in the Solver page of the Simulation Parameters dialog box. By default, the MAT-file is created in the root directory of the current default device in VxWorks. This is typically the host file system that VxWorks was booted from.
Implementation Overview Downloading and Running the Executable Interactively If automatic downloading is disabled, you must use the Tornado tools to complete the process.
8 Targeting Tornado for Real-Time Applications external mode during the build procedure.) It also initializes StethoScope if you selected this option during the build procedure. The rt_main function is defined in the rt_main.c application module. This module is located in the matlabroot/rtw/c/tornado directory.
Implementation Overview The following table lists the arguments to this SimStruct. Table 8-1: Arguments to the rt_main SimStruct model A pointer to the entry point function in the generated code. This function has the same name as the Simulink model. It registers the local functions that implement the model code by adding function pointers to the model’s SimStruct. See Chapter 6, “Program Architecture,” for more information.
8 Targeting Tornado for Real-Time Applications Table 8-1: Arguments to the rt_main SimStruct (Continued) model A pointer to the entry point function in the generated code. This function has the same name as the Simulink model. It registers the local functions that implement the model code by adding function pointers to the model’s SimStruct. See Chapter 6, “Program Architecture,” for more information. priority The priority of the program’s highest priority task (tBaseRate).
9 Targeting DOS for Real-Time Applications Introduction . . . . . . . . . . . . . . . . . . . . 9-2 DOS Device Drivers Library . . . . . . . . . . . . . . 9-3 Implementation Overview . . . . . . . . . . . . . . 9-4 System Configuration . . . . . . . . . . . . . . . . . 9-5 Sample Rate Limits . . . . . . . . . . . . . . . . . 9-7 Device Driver Blocks . . . . . . . . Device Driver Block Library . . . . . . Configuring Device Driver Blocks . . . . Adding Device Driver Blocks to the Model . . . . . . . . . .
9 Targeting DOS for Real-Time Applications Introduction This chapter provides information that pertains specifically to using the Real-Time Workshop in a DOS environment. This chapter includes a discussion of: • DOS-based Real-Time Workshop applications • Supported compilers and development tools • Device driver blocks — adding them to your model and configuring them for use with your hardware • Building the program The DOS target creates an executable using Watcom for DOS (i.e.
Introduction DOS Device Drivers Library Selecting DOS Device Drivers under the Real-Time Workshop library in the Simulink Library Browser opens the DOS Device Drivers library. The device drivers discussed in this chapter are located in this library.
9 Targeting DOS for Real-Time Applications Implementation Overview The Real-Time Workshop includes DOS run-time interface modules designed to implement programs that execute in real-time under DOS. These modules, when linked with the code generated from a Simulink model, build a complete program that is capable of executing the model in real time. The DOS run-time interface files can be found in the matlabroot/rtw/c/dos/rti directory.
Implementation Overview This diagram illustrates the code modules that are used to build a DOS real-time program. To execute the code in real time, the program runs under the control of an interrupt driven timing mechanism. The program installs its own interrupt service routine (ISR) to execute the model code periodically at predefined sample intervals. The PC-AT’s 8254 Programmable Interval Timer is used to time these intervals.
9 Targeting DOS for Real-Time Applications Hardware Requirements The hardware needed to develop and run a real-time program includes: • A workstation running Windows 95, Windows 98, or Windows NT and capable of running MATLAB/Simulink. This workstation is the host where the real-time program is built. • A PC-AT (386 or higher) running DOS. This system is the target, where the real-time program executes.
Implementation Overview source code of the device drivers for the Keithley Metrabyte DAS 1600/1400 Series I/O boards. See the “Device Driver Blocks” section for information on how to use these blocks. Simulink Host The development host must have Windows 95, Windows 98, or Windows NT to run Simulink. However, the real-time target requires only DOS, since the executable built from the generated code is not a Windows application. The real-time target will not run in a “DOS box” (i.e.
9 Targeting DOS for Real-Time Applications The fastest sample rate you can define is determined by the minimum value from which the counter can count down. This value is 3, hence the fastest sample rate that the 8254 is capable of achieving is: 1.193 × 10 6 ÷ 3 ≈ 4 × 10 5 Hz This corresponds to a minimum base step size of 1 ÷ 4 × 10 5 ≈ 2.5 × 10 – 6 sec onds However, bear in mind that the above number corresponds to the fastest rate the timer can generate interrupts.
Device Driver Blocks Device Driver Blocks The real-time program communicates with external hardware via a set of device drivers. These device drivers contain the necessary code for interfacing to specific I/O devices. The Real-Time Workshop includes device drivers for commercially available Keithley Metrabyte 1600/1400 Series I/O boards. These device drivers are implemented as C-coded, S-functions to interface with Simulink. This means you can add them to your model like any other block.
9 Targeting DOS for Real-Time Applications To access the device driver blocks, double-click on the sublibrary icon. The blocks in the library contain device drivers that can be used for the DAS-1600/1400 Series I/O boards. The DAS-1601/1602 boards have 16 analog input (ADC) channels, two 12-bit analog output (DAC) channels and 4-bits of digital I/O. The DAS-1401/1402 boards do not have DAC channels.
Device Driver Blocks Analog Input (ADC) Block Parameters • Base I/O Address — The beginning of the I/O address space assigned to the board. The value specified here must match the board’s configuration. Note that this parameter is a hexadecimal number and must be entered in the dialog as a MATLAB string (e.g., '0x300'). • Analog Input Range — This two-element vector specifies the range of values supported by the Analog to Digital Converter. The specified range must match the I/O board’s settings.
9 Targeting DOS for Real-Time Applications • Sample Time (sec) — Device drivers are discrete blocks that require you to specify a sample time. In the generated code, these blocks are executed at the specified rate. Specifically, when the ADC block is executed, it causes the ADC to perform a single conversion on the enabled channels, and the converted values are written to the block output vector.
Device Driver Blocks • Number of Channels — Number of DAC channels enabled. The DAS-1600 Series I/O boards have two 12-bit DAC channels. The DAS-1400 Series I/O boards do not have any DAC channels. The input port width of this block is equal to the number of channels enabled. • Sample Time (sec) — DAC device drivers are discrete blocks that require you to specify a sample time. In the generated code, these blocks are executed at the specified rate.
9 Targeting DOS for Real-Time Applications Digital Output Block Parameters • Base I/O Address — The beginning of the I/O address space assigned to the board. The value specified here must match the board’s configuration. Note that this parameter is a hexadecimal number and must be entered in the dialog as a MATLAB string (e.g., '0x300'). • Low/High Threshold Values — This parameter specifies the threshold levels, [lo hi], for converting the block inputs into 0/1 digital values.
Device Driver Blocks executed at the specified rate. Specifically, when the digital output block is executed, it causes corresponding boolean values to be output from the board’s digital I/O channels. Adding Device Driver Blocks to the Model Add device driver blocks to the Simulink block diagram as you would any other block — simply drag the block from the block library and insert it into the model.
9 Targeting DOS for Real-Time Applications Building the Program Once you have created your Simulink model and added the appropriate device driver blocks, you are ready to build a DOS target application. To do this, select Parameters from the Simulation menu of your Simulink model and display the Real-Time Workshop page of the Simulink parameters dialog box. On the Real-Time Workshop page, specify: • drt.tlc as the System target file • drt_watc.tmf as the Template makefile.
Building the Program workstation. You can verify this by checking the environment variable, WATCOM, which correctly points to the directory where the Watcom files are installed. 2 The program builder invokes the Watcom wmake utility on the generated makefile, so the directory where wmake is installed must be on your path. Running the Program The result of the build process is a DOS 32-bit protected-mode executable. The default name of this is model.exe, where model is the name of your Simulink model.
9 Targeting DOS for Real-Time Applications 9-18
10 Targeting Custom Hardware Introduction . . . . . . . . . . . . . . . . . . . . 10-2 Run-Time Interface . . . . . . . . . . . . . . . . . 10-4 Creating System Target Files and Template Makefiles . 10-5 Implementing Device Drivers . . Device Driver Blocks . . . . . . . The S-Function Format . . . . . . S-Function File Format . . . . . . Conditional Compilations . . . . . Initialization . . . . . . . . . . Calculating Block Outputs . . . . . Additional Include Files . . . . . . Compiling the MEX-File . . .
10 Targeting Custom Hardware Introduction This chapter contains information on targeting custom hardware and implementing device driver blocks. By implementing your own blocks, you can create a library to include blocks for your particular I/O devices. Typically, to target custom hardware, you must: • Create a main program for your target system to execute the generated code. • Create a system target file. This the entry point for the TLC program used to transform the models into generated code.
Introduction Note For examples of device drivers, see the S-functions supplied in matlabroot/rtw/c/tornado/devices and matlabroot/rtw/c/dos/devices.
10 Targeting Custom Hardware Run-Time Interface There are two ways to target custom hardware: • Rapid prototyping • Embedded real-time Rapid prototyping targets have an environment similar to the generic real-time or Tornado target. This section describes how to create a Run-time interface for a rapid prototyping target. To create a run-time interface (i.e., a main program), you can begin with the generic real-time target (grt). The run-time interface for grt consists of: • grt_main.
Creating System Target Files and Template Makefiles Creating System Target Files and Template Makefiles Assuming that you’ve created the directory /applications/mytarget you should copy matlabroot/rtw/c/grt/grt.tlc into it and rename grt.tlc to mytarget.tlc. You can then modify your system target file as needed, based on the requirements of your real-time target. You should modify or remove the first comment lines that define browser information.
10 Targeting Custom Hardware Clicking the Build button causes the Real-Time Workshop to generate code as dictated by mytarget.tlc and compile it as dictated by mytarget.tmf.
Implementing Device Drivers Implementing Device Drivers S-functions can be built into MEX-files or compiled and linked with other code to become part of a stand-alone program. This dual nature is exploited by the device driver blocks. These blocks are implemented as C code S-functions. They are compiled as MEX-files so you can place them in your Simulink block diagram.
10 Targeting Custom Hardware You can add your own blocks to a device driver library by writing S-functions that implement device drivers for your particular I/O board. However, in order for the code generator to generate code that can call your blocks, they must be implemented using the API defined by Simulink. Before beginning the task of creating your own device driver block, you should consult the Simulink documentation for a description of how to write S-functions using the API.
Implementing Device Drivers - Reading values from an I/O device and assigning these values to the block’s output vector y (if it is an ADC) - Writing values from the block’s input vector u, to an I/O device (if it is a DAC) • Terminating the program (e.g.
10 Targeting Custom Hardware Device Driver S-Function Define a name for the entry point function: #define S_FUNCTION_NAME filename Define the S-function as level 2: #define S_FUNCTION_LEVEL 2 Include the definition of the Simulink data structure (SimStruct): #include "simstruc.h" Include the MEX header file: #ifdef MATLAB_MEX_FILE #include "mex.
Implementing Device Drivers S_FUNCTION_NAME Definition The statement #define S_FUNCTION_NAME name defines the name of the function that is the entry point for the S-function code. This function is defined in cg_sfun.h, which is included at the end of the S-function. Note that name must be the name of the S-function file without the .c extension (e.g., dt2811ad for the Data Translation DT2811 A/D block). Also, you must specify the S_FUNCTION_NAME before you include simstruc.h.
10 Targeting Custom Hardware Conditional Compilations In general, you can use an S-function in these environments: • Simulink • Real-Time When you use your S-function in Simulink, you do so by creating a MEX-file from it. In this case, the macro MATLAB_MEX_FILE is defined. When you use your S-function in real-time (for example, with a fixed-step solver and the Real-Time Workshop), the macro RT is defined. Initialization Initialization is performed in three separate steps.
Implementing Device Drivers Next define a variable used to store the integer (which is the number of channels in this example): uint_T num_channels; Finally, extract the value from the argument (which is of type mxArray *), and assign it to a type uint_T (unsigned integer). Since the parameter is a single integer, you need only the first element in the parameter: num_channels = mxGetPr(THIRD_ARGUMENT)[0]; The macro ssGetSFcnParam is part of the S-function API. It is defined in simstruc.
10 Targeting Custom Hardware This list describes the function of each macro in mdlInitializeSizes: • ssSetNumSFcnParams — The number of input parameters is equal to the number of parameters in the block’s dialog box. • ssSetNumInputPorts — The ADC block has no inputs because it reads data from the I/O board. An ADC is a source block (i.e., the block has only output ports). • ssSetNumOutputPorts — The number of outputs equals the number of I/O channels.
Implementing Device Drivers The following example illustrates the definition of mdlInitializeSizes for a DAC: static void mdlInitializeSizes(SimStruct ∗S) { uint_T num_channels = mxGetPr(ssGetSFcnParam(S,0)[0]); uint_T num_sample_times = mxGetPr(ssGetSFcnParams(S,1))[0]) ssSetNumSFcnParams(S, 3); /* Number of expected parameters */ if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) { /* Return if number of expected != number of actual param’s */ return; } ssSetNumInputPorts(S, num_channels); /*Number of
10 Targeting Custom Hardware Initializing the I/O Device Device driver S-functions use the mdlInitializeConditions function to: • Read parameters from the block’s dialog box • Save parameter values in the SimStruct • Initialize the I/O device When reading parameter values, you must be careful to handle data types correctly. The next two examples illustrate how to read two different types of data from the dialog box. Reading the Base Address.
Implementing Device Drivers All S-functions call the mdlOutputs function to calculate block outputs. For a device driver block, this function contains the code that reads from or writes to the hardware. Accessing the Hardware The mechanism you use to access the I/O device depends on your particular implementation. One possibility is to use low level hardware calls that are part of your compiler’s C library. For example, on the PC a device driver could use the following technique.
10 Targeting Custom Hardware The Termination Function The final required function is typically used only in DACs to zero the output at the end of the program. For example: static void mdlTerminate(SimStruct *S) { uint_T num_channels = (uint_t)mxGetPr(ssGetSFcnParams(S,0)[0]); uint_T i; for (i = 0; i < num_channels; i++) { ds1102_da(i + 1, 0.0); } } This for loop simply sets the output of each channel to 0.0. ADCs typically implement this function as an empty stub.
Implementing Device Drivers The Public Registration Function The include file cg_sfun.h defines a function that is the entry point for the S-function code. This function is named by the #define S_FUNCTION_NAME name macro that you specified earlier in your code. This function registers the other local functions by installing pointers to them in the SimStruct. This is the only public function in the S-function and is called by the real-time program’s public registration function during program startup.
10 Targeting Custom Hardware Setting the MATLAB Path The device driver blocks in a library can automatically change your MATLAB path to ensure that Simulink can find the MEX-file. This is accomplished by calling the addpath M-file as part of the masked block’s initialization command. This command is executed whenever you start a simulation or generate code.
11 Real-Time Workshop Libraries Introduction . . . . . . . . . . . . . . . . . . . . 11-2 Custom Code Library . . . . . . . . . . . . . . . . 11-4 Custom Model Code . . . . . . . . . . . . . . . . . 11-4 Custom Subsystem Code . . . . . . . . . . . . . . . 11-7 Interrupt Handling . . . . Asynchronous Interrupt Block Task Synchronization Block . Asynchronous Buffer Block . Rate Transition Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11 Real-Time Workshop Libraries Introduction The Real-Time Workshop provides a library of functions that allow you great flexibility in constructing real-time system models and generated code. The Real-Time Workshop Library is a collection of sublibraries located in the Simulink Library Browser. Note that, depending on which MathWorks products you have installed, your browser may show a different collection of libraries.
Introduction • S-Function Target — This block is intended for use in conjunction with the Real Time W S-function code format. See “S-Function Code Format” on page 12-18 for more information. • VxWorks Support — A collection of blocks that support VxWorks (Tornado). See “Targeting Tornado for Real-Time Applications” in Chapter 8 for information on VxWorks. Note This chapter discusses asynchronous interrupt handling.
11 Real-Time Workshop Libraries Custom Code Library The Real-Time Workshop also provides a Custom Code library containing blocks that allow you to place your own code, in C or in Ada, inside the code generated by the Real-Time Workshop. There are two Custom Code sublibraries in both the C and Ada Custom Code libraries: • Custom Model Code • Custom Subsystem Code Both sublibraries contain blocks that target specific files and subsystems within which you can place your code.
Custom Code Library • model.h — Header File block • model.prm — Parameter File block • model.c — Source File block • model.
11 Real-Time Workshop Libraries Double clicking the Model Start Function block opens a the MdlStart Function Custom Code dialog box. The Real-Time Workshop inserts the code entered here into the MdlStart function in the generated code. You can insert custom code into any or all of the available text fields.
Custom Code Library The code below is the MdlStart function for this example (mymodel). void MdlStart(void) { /* user code (Start function Header) */ The custom code /* System: */ entered in the unsigned int *ptr = 0xFFEE; /* user code (Start function Body) */ /* System: */ /* Initialize hardware */ *ptr = 0; MdlStart Function Custom Code dialog box is embedded directly in the generated code. /* state initialization */ /* DiscreteFilter Block: /Discrete Filter */ rtX.d.
11 Real-Time Workshop Libraries • Subsystem Enable • Subsystem Disable • Subsystem Outputs • Subsystem Update • Subsystem Derivatives The location of the block in your model determines the location of the custom code. In other words, the code is local to the subsystem that you select. For example, the Subsystem Outputs block places code in mdlOutputs when the code block resides in the root model, but the code is placed in the system’s outputs function when it resides in an enabled subsystem.
Interrupt Handling Interrupt Handling The Real-Time Workshop provides blocks in the Interrupt Template library that allow you to model synchronous/asynchronous event handling, including interrupt service routines (ISRs).
11 Real-Time Workshop Libraries subsystem (or Stateflow Chart). The Asynchronous Interrupt block then installs the Task Synchronization block as the ISR, which releases a synchronization semaphore (performs a semGive) to the function-call subsystem and returns. See the VxWorks Task Synchronization block for more information.
Interrupt Handling concept: Plant Controller Library: changes made here affect both models Plant Model (for simulation) Interrupt Block (Sim.
11 Real-Time Workshop Libraries generation on the board. You must match the interrupt level and vector specified in the Asynchronous Interrupt block dialog to the level and vector setup on the I/O board. Asynchronous Interrupt Block Parameters The picture below shows the VxWorks Asynchronous Interrupt block dialog box: Parameters associated with the Asynchronous Interrupt block are: • Mode — in Simulation mode, the ISRs are executed nonpreemptively.
Interrupt Handling • VME Interrupt Offset Number(s) — the Real-Time Workshop uses this number in the call to intConnect(INUM_TO_IVEC(#),...). You should specify a unique vector offset number for each interrupt number. • Preemption Flag(s) — By default, higher priority interrupts can preempt lower priority interrupts in VxWorks. If desired, you can lock out interrupts during the execution of a ISR by setting the preemption flag to 0.
11 Real-Time Workshop Libraries Asynchronous Interrupt Block Example - Simulation Mode This example shows how the Asynchronous Interrupt block works in simulation mode: Simulated Interrupt Signals The Asynchronous Interrupt block works as a “handler” that routes signals and sets priority. If two interrupts occur simultaneously, the rule for handling which signal is sent to which port is left/right and top/bottom.
Interrupt Handling Asynchronous Interrupt Block Example - RTW Mode This example shows the Asynchronous Interrupt block in RTW mode: * Plant is removed Stand-alone functions are installed as ISR’s: Int Vector table Offset 192 &f() Note that the simulated plant signals that were included in the previous example have been omitted. In RTW mode, the Asynchronous Interrupt block receives interrupts directly from the hardware.
11 Real-Time Workshop Libraries Locking and Unlocking ISRs. It is possible to lock ISRs so that they are not preempted by a higher priority interrupt. Configuring the interrupt as nonpreemptive has this effect. This code shows where the Real-Time Workshop places the int_lock and int_unlock functions to configure the interrupt as nonpreemptive: f() { lock = int_lock(); . . . . . . . . .
Interrupt Handling • A semaphore is created to synchronize the downstream system to the execution of the Task Synchronization block. • Code is added to this spawned function-call subsystem to wrap it in an infinite while loop. • Code is added to the top of the infinite while loop of the spawned task to wait on a the semaphore, using semTake(). semTake() is first called with NO_WAIT specified.
11 Real-Time Workshop Libraries VxWorks system. In particular, the default priority of the model code is 30 and, when multitasking is enabled, the priority of the each subrate task increases by one from the default model base rate. Other task priorities in the system should also be considered when choosing a task priority. VxWorks priorities range from 0 to 255 where a lower number is a higher priority. • Stack Size — The function-call subsystem is spawned with the stack size specified.
Interrupt Handling creates and initializes the synchronization semaphore. It also spawns the function-call subsystem as an independent task. /* Create and spawn task: /Faster Rate(.015) */ if ((*(SEM_ID *)rtPWork.s6_S_Function.SemID = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY)) == NULL) ssSetErrorStatus(rtS,"semBCreate call failed " "for block /Faster Rate(.015).\n "); } if ((rtIWork.s6_S_Function.
11 Real-Time Workshop Libraries Asynchronous Buffer Block The VxWorks Double Buffer blocks are meant to be used to interface signals to asynchronous function-call subsystems in a model. This is needed whenever a function-call subsystem has input or output signals and its control input ultimately connects (sources) to the VxWorks Asynchronous Interrupt block or Task Synchronization block.
Interrupt Handling Asynchronous Buffer Block Parameters There are two kinds of Asynchronous Buffer blocks, a reader and a writer. The picture below shows the Asynchronous Buffer block’s dialog boxes (reader and writer): Both blocks require the same parameter: • Sample Time — The sample time should be set to -1 inside a function call and to the desired time otherwise.
11 Real-Time Workshop Libraries Asynchronous Buffer Block Example This example shows how you might use the Asynchronous Buffer block to control the data flow in an interrupt service routine: The ISR() subsystem block, which is configured as a function-call subsystem, contains another set of Asynchronous Buffer blocks: Rate Transition Block The VxWorks Rate Transition block is used to provide a sample time for blocks connected to an asynchronous function-call subsystem when double buffering is not requir
Interrupt Handling This will cause blocks up- or downstream from it, which would otherwise inherit from the function-call subsystem, to use the sample time specified. Note that if the signal width is greater than 1, data consistency is not guaranteed, which may or may not an issue, see next option. The Rate Transition block does not introduce any system delay. It only specifies the sample time of the downstream blocks. This block is typically used for scalar signals that do not require double buffering.
11 Real-Time Workshop Libraries Rate Transition Block Example This picture shows a sample application of the Rate Transition block in an ISR: In this example, the Rate Transition block on the input to the function-call subsystem causes both the In and Gain1 blocks to run at the 0.1 second rate. The Rate Transition block on the output of the function-call subsystem causes both the Gain2 and Out blocks to run at the 0.2 second rate.
Creating a Customized Asynchronous Library for Your System Creating a Customized Asynchronous Library for Your System You can use the Real-Time Workshop’s VxWorks Asynchronous blocks as templates that provide a starting point for creating your own asynchronous blocks.
11 Real-Time Workshop Libraries 11-26
12 Configuring Real-Time Workshop for Your Application Introduction . . . . . . . . . . . . . Interaction between Simulink and the Real-Time Workshop . . . . Choosing a Code Format for Your Application Choosing a Target . . . . . . . . . . . . . . . . . . 12-2 . . . . . . . 12-6 . . . . . . . 12-7 Real-Time Code Format Unsupported Blocks . . System Target Files . . Template Makefiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12 Configuring Real-Time Workshop for Your Application Introduction This chapter discusses how Simulink interacts with the Real-Time Workshop and also describes how to customize the code generated by the Real-Time Workshop for your application. The last section of this chapter describes several optimization techniques that will improve the performance of the generated code. The Real-Time Workshop provides five different code formats.
Introduction One of the key components of Simulink is its engine, which propagates data from one block to the next along signal lines. The data propagated are: • Data type • Line widths • Sample times When generating code, Simulink first compiles the block diagram. This compile stage is analogous to that of a C program. The C compiler carries out type checking and pre-processing.
12 Configuring Real-Time Workshop for Your Application This figure shows the propagation of the signal attributes associated with the Inport block through a simple block diagram. In this example, the Gain and Outport blocks inherit the attributes specified for the Inport block. Inherited sample times in source blocks (e.g., a root inport) can sometimes lead to unexpected and unintended sample time assignments.
Introduction start time and Tf is the simulation stop time. If Tf is infinity, the default sample time is set to 0.2. To ensure a completely deterministic model (i.e, where no sample times are set using the above rules), you should explicitly specify the sample time of all your source blocks. Source blocks include root inport blocks and any blocks without input ports. You do not have to set subsystem input port sample times. You may want to do so, however, when creating modular systems.
12 Configuring Real-Time Workshop for Your Application generator to properly specify the rate at which f() should be executed as shown in the connected_trigger model below. Instead of the function-call generator, you could have any other block that can drive the trigger port. Then, you should call the model’s main entry point to execute the trigger function. For multirate models, a common use of the Real-Time Workshop is to build individual models separately and then hand-code the I/O between the models.
Introduction target throughout development. The real-time format is the most comprehensive code format and supports almost all the built-in blocks. If, however, your application demands that you limit source code size, memory usage, or maintain a simple call structure, then you should choose the embedded-C format. Finally, you should choose the S-function format if you are not concerned about RAM and ROM usage and want to: • Componentize a model for scalability • Create a proprietary S-function .
12 Configuring Real-Time Workshop for Your Application Table 12-1: Features Supported by Real-Time Workshop Targets and Code Formats RealTime Static memory allocation RealTime malloc X Dynamic memory allocation DOS OSEK LE/O Ada Tornado S-Fcn X X X X X X X X X X RSim Real-Time Windows X Continuous time X X X X X X X X C MEX S-functions (not inlined with TLC) X X X X X X X X Any S-function (inlined with TLC) X X X X X X X X Optimized for minimum RAM and ROM
Introduction Table 12-1: Features Supported by Real-Time Workshop Targets and Code Formats (Continued) RealTime RealTime malloc Executes in hard real-time Non real-time executable included Multiple instantiation of one model (provided no Stateflow blocks are in your model) X X X EmbeddedC DOS OSEK LE/O X X Ada Tornado S-Fcn RSim X Real-Time Windows X X X X 12-9
12 Configuring Real-Time Workshop for Your Application Real-Time Code Format The real-time code format (corresponding to the generic real-time target) is useful for rapid prototyping applications. If you want to generate real-time code while iterating model parameters rapidly, you should begin the design process with a generic real-time target.
Real-Time Code Format Template Makefiles • drt.tmf • grt - grt_bc.tmf — Borland C - grt_vc.tmf — Visual C - grt_watc.tmf — Watcom C - grt_unix.tmf — UNIX host • osek_leo.tmf • rsim - rsim_bc.tmf — Borland C - rsim_vc.tmf — Visual C - rsim_watc.tmf — Watcom C - rsim_unix.tmf — UNIX host • tornado.tmf • win_watc.
12 Configuring Real-Time Workshop for Your Application Real-Time malloc Code Format The real-time malloc code format (corresponding to the generic real-time malloc target) is very similar to the real-time code format. The differences are: • Real-time malloc declares memory dynamically. • Real-time malloc allows you to multiply instance the same model with each instance maintaining its own unique data. • Real-time malloc allows you to combine multiple models together in one executable.
Real-Time malloc Code Format Template Makefiles • grt_malloc - grt_malloc_bc.tmf — Borland C - grt_malloc_vc.tmf — Visual C - grt_malloc_watc.tmf — Watcom C - grt_malloc_unix.tmf — UNIX host • tornado.
12 Configuring Real-Time Workshop for Your Application Embedded-C Code Format The embedded-C code format (corresponding to the embedded real-time target) produces code that is optimized for speed, memory usage, and simplicity. It is intended for use in deeply embedded systems, as opposed to in the rapid prototyping process.
Embedded-C Code Format • Select the Single output/update function check box. Combining the output and update functions allows the Real-Time Workshop to use more local variables in the step function of the model. • Select None or File Splitting in the Function Management pull-down menu. Selecting function splitting disables the Local block outputs optimization.
12 Configuring Real-Time Workshop for Your Application Unsupported Blocks The embedded-C format does not support the following built-in blocks: • Continuous - No blocks in this library are supported • Discrete - First-Order Hold • Functions & Tables - MATLAB Fcn - S-Functions — M-file and Fortran S-functions, C MEX S-functions that call into MATLAB.
Embedded-C Code Format Template Makefiles • ert_bc.tmf — Borland C • ert_vc.tmf — Visual C • ert_watc.tmf — Watcom C • ert_unix.
12 Configuring Real-Time Workshop for Your Application S-Function Code Format The S-function code format (corresponding to the RTW S-function target) generates code so that you can use the model as a (C MEX) S-function block in another model. This format has these applications: • Componentize a model — You can generate an object file for a model, m1, in the S-function format. Then, you can place the generated S-function block in another model, m2.
S-Function Code Format functionality of the sfun model. The picture below shows the sfun_sf block embedded in a new model. After you have placed the RTW S-Function block inside a model, you can try out several different inputs and measure the response of the original model. The speed at which the S-Function block executes is faster than the original model.
12 Configuring Real-Time Workshop for Your Application Restrictions • Hand-written S-functions without corresponding TLC files must contain exception-free code. For more information on exception-free code, refer to “Exception-Free Code” in Chapter 3 of Writing S-Functions. • The parameter values of the blocks in the source model are hard-coded into the generated S-function. There is no mechanism to modify parameters in a Real-Time Workshop generated S-function.
Optimizations Common to All Code Formats Optimizations Common to All Code Formats General Modeling Techniques The following are techniques that you can use with any code format: • Run slupdate on old models to automatically convert them to use the newest features. • Directly inline C MEX S-functions into the generated code by including a TLC file for the S-function. See Chapter 3 of the Target Language Compiler Reference Guide for more information on writing a TLC file for inlining an S-function.
12 Configuring Real-Time Workshop for Your Application Stateflow Optimizations If your model contains Stateflow blocks, select the Use Strong Data Typing with Simulink I/O check box (on the Chart Properties dialog box) on a chart-by-chart basis. See the Stateflow User’s Guide for more information about the Chart Properties dialog box. Simulation Parameters Options on each page of the Simulation Parameters Dialog Box affect the generated code.
Optimizations Common to All Code Formats Diagnostic Page • Deselect the Disable optimized block I/O storage check box. Disabling optimized block I/O storage makes all block outputs global and unique, which in many cases significantly increases RAM and ROM usage. • Deselect the Relax boolean type checking (2.x compatible) check box. A boolean signal typically requires one byte of storage while a double signal requires eight bytes of storage.
12 Configuring Real-Time Workshop for Your Application vector. Note that you can override the inlining of individual parameter by using the Tunable Parameters dialog box. Code Generation Options You can access the Code Generation Options by pressing the Options button on the Real-Time Workshop page. • Set an appropriate Loop rolling threshold.
Optimizations Common to All Code Formats • Select the Inline invariant signals check box. The Real-Time Workshop will not generate code for blocks with a constant (invariant) sample time. • Select the Local block outputs check box. Blocks signals will be declared locally in functions instead of being declared globally (when possible). This check box is ignored when the Disable optimized block I/O storage check box is selected.
12 Configuring Real-Time Workshop for Your Application 12-26
13 Real-Time Workshop Rapid Simulation Target Introduction . . . . . . . . . . . . . . . . . . . . 13-2 Building for the Rapid Simulation Target Running a Rapid Simulation . . . . . . . . Simulation Performance . . . . . . . . . . Batch and Monte Carlo Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4 .
13 Real-Time Workshop Rapid Simulation Target Introduction The Real-Time Workshop rapid simulation target (rsim) consists of a set of target files for nonreal-time execution on your host computer. You can use the Real-Time Workshop to generate fast, stand-alone simulations that allow batch parameter tuning and loading of new simulation data (signals) from a standard MATLAB MAT-file without needing to recompile your model.
Introduction you can easily write simple scripts that will run a set of simulations in sequence while using new data sets. These scripts can be written to provide unique filenames for both input parameters and input signals, as well as output filenames for the entire model or for To File blocks.
13 Real-Time Workshop Rapid Simulation Target Building for the Rapid Simulation Target By specifying the system target file (rsim.tlc) and the template makefile (rsim_default_tmf) on the Real-Time Workshop page of the Simulation Parameters dialog box, you can use the Real-Time Workshop to generate and build an rsim executable. This picture shows the dialog box settings for the rapid simulation target Press the Browse button and select the rapid simulation target from the System Target File Browser.
Building for the Rapid Simulation Target real-time target, on the other hand, is a starting point for targeting a new processor. A single build of your model can be used to study effects from varying parameters or input signals. Command line arguments provide the necessary mechanism to specify new data for your simulation. This table lists all available command line options. Table 13-1: rsim Command Line Options Command Line Option Description model -f old.mat=new.
13 Real-Time Workshop Rapid Simulation Target at the MATLAB prompt. Type w = 100; zeta = 0.5; to set parameters. Copy a test data file by typing !matlabroot\toolbox\rtw\rtwdemos\rsim_tfdata.mat at the MATLAB prompt. Be sure to specify rsim.tlc as the system target file and rsim_default_tmf as the template makefile. Then press the Build button on the Real-Time Workshop page to create the rsim executable.
Building for the Rapid Simulation Target Replacing Input Signal Data. New data for a From File block can be placed in a standard MATLAB MAT-file. As in Simulink, the From File block data must be stored in a matrix with the first row containing the time vector while subsequent rows contain u vectors as input signals. After generating and compiling your code, you can type the model name rsimtfdemo at a DOS prompt to run the simulation. In this case, the file rsm_tfdata.
13 Real-Time Workshop Rapid Simulation Target This picture shows the resulting plot. As a result the new data file is read and the simulation progresses to the stop time as specified in the Solver page of the Simulation Parameters dialog box. It is possible to have multiple instances of From File blocks in your Simulink model. Since rsim does not place signal data into generated code, it reduces code size and compile time for systems with large numbers of data points that originate in From File blocks.
Building for the Rapid Simulation Target <-o> Specifying a New Output Filename for the Simulation If you have specified Save to Workspace options (that is, checked Time, States, Outputs, or Final States checkboxes on the Workspace I/O page of the Simulation Parameters dialog box under the Simulation menu in Simulink), the default is to save simulation logging results to the file modelname.mat. You can now specify a replacement filename for subsequent simulations.
13 Real-Time Workshop Rapid Simulation Target incorrect simulation results. In this case, where model structure has changed, you must regenerate the code for the model. The rsim target allows you to alter any model parameter (of type double) including parameters that include side-effects functions.
Building for the Rapid Simulation Target <-s> Specifying a New Stop Time for an rsim Simulation If a new stop time is not provided, the simulation will run until reaching the value specified in the Solver page at the time of code generation. You can specify a new stop time value as follows: !rsimtfdemo -s 6.0 In this case, the simulation will run until it reaches 6.0 seconds. At this point it will stop and log the data according to the MAT-file data logging rules as described above.
13 Real-Time Workshop Rapid Simulation Target From Workspace data must be contained in a structure variable with the following fields: var.time var.signals.values The field var.time must be of type double. The field var.signals.values can be of any data type that Simulink supports. The length of var.time must equal the length of var.signals.values.
Building for the Rapid Simulation Target Simulation Performance It is not possible to predict accurately the simulation speed-up of an rsim simulation compared to a standard Simulink simulation. Performance will vary. Larger simulations have achieved speed improvements of up to 10 times faster than standard Simulink simulations. Some models may not show any noticeable improvement in simulation speed.
13 Real-Time Workshop Rapid Simulation Target demonstrate how rsim can be called repeatedly within an M-file for Monte Carlo simulations.
14 Real-Time Workshop Ada Coder Introduction . . . . . . . . . . . . . Real-Time Workshop Ada Coder Applications Supported Compilers . . . . . . . . . . Supported Targets . . . . . . . . . . . The Generated Code . . . . . . . . . . Types of Output . . . . . . . . . . . . Supported Blocks . . . . . . . . . . . Restrictions . . . . . . . . . . . . . . S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14 Real-Time Workshop Ada Coder Introduction This chapter presents an introduction to the Real-Time Workshop Ada Coder. It compares and contrasts the Real-Time Workshop Ada Coder with the Real-Time Workshop, shows you how to use the product by presenting an example, and concludes with a discussion of code validation. Note: The Real-Time Workshop Ada Coder is a separate product from the Real-Time Workshop.
Introduction Real-Time Workshop Ada Coder Applications Like the Real-Time Workshop, the Real-Time Workshop Ada Coder supports a variety of real-time applications: • Real-Time Control − You can design your control system using MATLAB and Simulink and generate Ada code from your block diagram model. You can then compile and download the Ada code directly to your target hardware. • Hardware-in-the-Loop Simulation − You can use Simulink to model real-life measurement and actuation signals.
14 Real-Time Workshop Ada Coder All Simulink blocks are automatically converted to code, with the exception of: • MATLAB function blocks • Any continuous sample time blocks • S-functions that are not inlined using the Target Language Compiler See “Supported Blocks” on page 14–21 for a list of supported blocks.
Introduction generation. You can, however, perform explicit upcasting using the Data Type Conversion block in Simulink. S-Functions S-functions provide a mechanism for extending the capabilities of Simulink. They allow you to write your own Ada code and incorporate it into the Simulink model as an S-function block in the generated code. Ada MEX-files are not supported.
14 Real-Time Workshop Ada Coder Getting Started This section illustrates, through a simple example, how to transform a Simulink model into a stand-alone executable program. This program runs independently of Simulink, allowing accelerated execution on the development host or a different target computer. Generating Ada code from a Simulink model is very similar to generating C code. Begin by typing countersdemo at the MATLAB prompt. This block diagram appears.
Getting Started Setting Options for Ada Code Generation You must specify the correct options before you generate Ada code from this model. These are the steps: 1 Select Parameters under the Simulation menu. This opens the Simulation Parameters dialog box. 2 On the Solver page, set the Solver options to Fixed-step discrete (no continuous states) 3 Click the Browse button on the Real-Time Workshop page. This opens the System Target File Browser. 4 Select Ada Simulation Target for GNAT and click OK.
14 Real-Time Workshop Ada Coder Alternatively, you can specify the settings on the Real-Time Workshop page manually by following these steps: 1 Select RTW Options under the Tools menu. This opens the Real-Time Workshop page of the Simulation Parameters dialog box. 2 Specify rt_ada_sim.tlc as the System target file. 3 Specify gnat_sim.tmf as the Template makefile. 4 Specify make_rtw -ada as the Make command. This picture shows the Real-Time Workshop page with the correct settings.
Getting Started Generated Files This table lists the Ada files generated by the Real-Time Workshop Ada Coder from the counter demonstration (countersdemo). Table 14-1: Ada Files Generated by the Real-Time Workshop Ada Coder Filename Description countersdemo.adb Package body with the implementation details of the model. countersdemo.ads Package specification that defines the callable procedures of the model and any external inputs and outputs to the model. countersdemo_types.
14 Real-Time Workshop Ada Coder Create model times2 using these blocks: • Sine Wave (sample time = 0.1) • timestwo S-function (provided in the matlabroot/toolbox/simulink/ blocks) with no parameters set (i.e., leave the Parameters field blank) • Two Outport blocks Your model should look like this picture.
Getting Started The times2 model contains a simple S-function, called timestwo, that takes the input sine wave signal and doubles its amplitude. The TLC file corresponding to the S-function is shown below: %% Copyright (c) 1994-98 by The MathWorks, Inc. %% %% Abstract: %% TLC file for timestwo.c used in Real-Time Workshop %% S-Function test.
14 Real-Time Workshop Ada Coder Configuring the Template Makefile Template makefiles specify the compiler, link, and make directives native to the target computer’s operating system and compiler you are using. Two examples of template makefiles are provided in the directory matlab/rtw/ada/gnat. File gnat_sim.tmf is the template makefile that builds that real-time Ada simulation program. The automatic build process expands the macros defined at the top of the .tmf file to create the call to gnatmake.
Getting Started Application Modules Required for the Real-Time Program Building the real-time program requires a number of support files in addition to the generated code. These support files contain: • A main program • Code to drive execution of the model code • Code to carry out data logging The makefile automatically compiles and links these source modules. This diagram shows the modules used to build the countersdemo example. Generated Code Main Program mr_ada_sim.adb sr_ada_sim.adb rt_ada_tasking.
14 Real-Time Workshop Ada Coder Tunable Parameters If you select Inline parameters on the Real-Time Workshop page, the Tunable parameters button activates. Clicking this button opens the RTW Tunable Parameters dialog box. This picture shows this dialog box for the f14 model. The RTW Tunable Parameters dialog box supports the following features: • Parameter tuning — de-inline any model parameter by placing its name in the Variable field and clicking Add.
Getting Started - ImportedExtern — the variable is assumed to be declared in the package specification entered in the Storage Type Qualifier field. The generated code accesses this variable as Your_Package.Your_variable. - ImportedExternPointer — this is not permitted in Ada. • Storage Type Qualifier — this is only used when specifying the package specification to qualify fully the variable name for the ImportedExtern option. This field is ignored in all other cases.
14 Real-Time Workshop Ada Coder To change the storage class of a signal, select it in your Simulink model; then select Signal Properties under the Edit menu of your model. This opens the Signal Properties dialog box. Refer to Using Simulink for information about these options. The options relevant to the Real-Time Workshop Ada Coder are located in the Signal monitoring and code generation options panel in the bottom half of the dialog box.
Getting Started specification. The generated code accesses this signal as RT_U.Signal_Name. - ExportedGlobal — declares the signal as a global variable that can be accessed from outside the generated code. The signal is declared in the model package specification but not in the External_Inputs structure. The generated code accesses this signal as Signal_Name. The signal will be globally visible as Model.Signal_Name.
14 Real-Time Workshop Ada Coder Code Validation After completing the build process, the stand-alone version of the countersdemo model is ready for comparison with the Simulink model. The data logging options selected with the Real-time Options dialog box cause the program to save the control signal, enabled counter, triggered counter, and simulation time. You can now use MATLAB to produce plots of the same data that you see on the three Simulink scopes.
Code Validation The “!” character passes the command that follows it to the operating system. This command, therefore, runs the stand-alone version of countersdemo (not the M-file). To obtain the data from the stand-alone program, load the file countersdemo.
14 Real-Time Workshop Ada Coder Analyzing Data with MATLAB Points to consider when data logging: • The Ada Coder only supports data logging to a matrix. • To Workspace blocks log data at the frequency of the driving block and do not log time. • Scope blocks log data at the frequency of the driving block and log time in the first column of the matrix. • Root Outport blocks are updated at the frequency of the driving block but are logged at the base rate of the model.
Supported Blocks Supported Blocks The Real-Time Workshop Ada Coder supports the following Simulink blocks.
14 Real-Time Workshop Ada Coder Nonlinear Blocks Backlash Quantizer Coulomb & Viscous Friction Relay DeadZone Saturation Manual Switch (must Break Library Link and use discrete sample time) Switch Multiport Switch Signals & Systems Blocks Bus Selector Hit Crossing Configurable Subsystem Initial Condition (IC) DataStore Memory Inport DataStore Read Merge DataStore Write ModelInfo Data Type Conversion Outport Demux Probe Enable Selector From Subsystem Goto Tag Visibility Termin
Supported Blocks Sinks Display — no code is generated for this block To File Scope — matrix data logging only (double arrays) To Workspace — matrix data logging only (double arrays) Stop Simulation Sources Band-Limited White Noise Ramp — (you must break the library link and replace the clock with a discrete clock and manually set the sample time step to match the discrete clock).
14 Real-Time Workshop Ada Coder 14-24
A Real-Time Workshop Directory Tree
A Real-Time Workshop Directory Tree Real-Time Workshop Directory Tree The files provided to implement real-time and generic real-time applications reside in the matlabroot tree, where matlabroot is the directory in which you installed MATLAB. The following diagram illustrates the basic directory structure.
Real-Time Workshop Directory Tree The matlabroot/rtw/c Directory matlabroot/rtw/c src tlc grt dos tornado libsrc tools tools rtwsfcn ert grt_malloc windows osek_leo rsim A-3
A Real-Time Workshop Directory Tree A-4 Directory Purpose matlabroot/rtw/c/dos Files for targeting DOS matlabroot/rtw/c/ert Files for targeting embedded C code matlabroot/rtw/c/grt Files for targeting generic real-time matlabroot/rtw/c/libsrc Files used to implement functionality in certain blocks and for matrix support matlabroot/rtw/c/grt_malloc Files targeting generic real-time using dynamic memory allocation matlabroot/rtw/c/osek_leo Files for targeting the OSEK operating system matlabr
Real-Time Workshop Directory Tree The matlabroot/simulink Directory matlabroot/simulink include Directory Purpose matlabroot/simulink/ include Include files used to build the target The matlabroot/toolbox Directory matlabroot/toolbox rtw windows Directory Purpose matlabroot/toolbox/rtw M-files that implement the RTW build procedure and device driver libraries matlabroot/toolbox/rtw windows Real-Time Windows Target I/O device drivers, device driver GUI’s, and utility files A-5
A Real-Time Workshop Directory Tree The matlabroot/extern Directory matlabroot/extern include A-6 Directory Purpose matlabroot/extern/include Include files used to build the target
B Glossary
B Glossary Application Modules − With respect to Real-Time Workshop program architecture, these are collections of programs that implement functions carried out by the system dependent, system independent, and application components. Block Target File − A file that describes how a specific Simulink block is to be transformed, to a language such as C, based on the block’s description in the Real-Time Workshop file (model.rtw). Typically, there is one block target file for each Simulink block.
Extension Created by Description .tmf Supplied with Real-Time Workshop A template makefile .mk Real-Time Workshop A makefile specific to your model that is derived from the template makefile Generic Real-Time − An environment where model code is generated for a real-time system, and the resulting code is simulated on your workstation. (Note that execution is not tied to a real-time clock.) You can use generic real-time as a starting point for targeting custom hardware.
B Glossary Makefiles − Files that contain a collection of commands that allow groups of programs, object files, libraries, etc. to interact. Makefiles are executed by the make utility. Multitasking − A process by which your microprocessor schedules the handling of multiple tasks. The number of tasks is equal to the number of sample times in your model. Noninlined S-Function − In the context of the Real-Time Workshop, this is any C MEX S-function that is not implemented using a customized .tlc file.
Target File − A file that is compiled and executed by the Target Language Compiler. A combination of these files describes how to transform the Real-Time Workshop file (model.rtw) into target-specific code. Target System − The computer system on which you execute your real-time application. Targeting − The process of creating an executable for your target system. Template Makefile − A line-for-line makefile used by a make utility.
B Glossary B-6
Index A application modules application specific layer 6-35 common layer 6-31 definition of 6-25 Asynchronous Buffer block 11-20 Asynchronous Interrupt block 11-9 automatic code generation 1-6 automatic program building 3-2 B block target file 1-14 blocks nonvirtual 1-18 virtual 1-18 conditional compilations 10-12 continuous states, integration of 6-30 Custom Code library 11-4 custom hardware creating system target files and template makefiles 10-5 implementing device drivers 10-7 run-time interface 10-4
Index device driver blocks 9-9 adding to model 9-15 device drivers 9-6 digital input block parameters 9-13 digital output block parameters 9-14 hardware requirements 9-6 implementation overview 9-4 interrupt service routine 7-3 Keithley Metrabyte 9-9 make utility 9-6 modifying program timing 9-8 program timing 9-7 sample rate limits 9-7 software requirements 9-6 system configuration 9-5 DOS device drivers library 9-3 F F-14, Simulink model 2-12 faster to slower transitions in real-time 7-13 file splitting
Index under DOS 7-3 under VxWorks 7-3 interrupt service routine (ISR) 9-5 locking and unlocking 11-16 interrupt templates library 11-9 model.reg 1-16 model.rtw 1-16 multitasking and pseudomultitasking 7-5 N L library Custom Code 11-4 DOS device drivers 9-3 interrupt templates 11-9 VxWorks support 8-3 locking and unlocking ISRs 11-16 noninlined S-functions 1-15, 6-33 nonvirtual blocks 1-18 O operating systems VxWorks for real-time 8-5 options grt_msvc.tmf 3-34 grt_unix.tmf 3-32 grt_vc.
Index program building DOS real-time 9-16 VxWorks build command options 8-17 real-time options 8-14 setting step size 8-15 program execution data logging functions 6-32 enabling singletasking 7-8 executing the model 6-29 single vs. multitasking 7-3 program parameters download mechanism 4-18 for VxWorks 8-14 program timing of DOS applications 9-7 public registration function 10-19 R rapid prototyping 1-6 process 1-2 for digital signal processing 1-9 Rapid Simulation Target.
Index sample tiime overlaps 7-15 S-functions API 6-34 device driver 10-9 format of 10-8 inlining 1-4, 10-7 locating source code for 6-34 models containing 6-33 noninlined 1-15, 6-33 of real-time continuous system 6-30 StethoScope 8-17 data analysis tool 8-8 Subsystem Code sublibrary 11-7 system records 1-18 system target file 1-14, 2-8 system target file browser 3-12 simstruc.h 10-11 simstruc.
Index U UNIX 2-18 template makefiles 2-18 V virtual blocks 1-18 VxWorks application overview 8-5 build command options 8-17 configuring for external mode (sockets) 8-6 GNU tools 8-14 makefile template 8-13 downloading and running the executable interactively 8-19 implementation overview 8-11 program building 8-14 program execution 8-19 program monitoring 8-5 real-time operating system 8-2 runtime structure 8-8 setting external mode options 8-7 target 8-5 connecting to 8-19 downloading to 8-19 tasks creat