Embedded Coder - Getting Started Guide
Embedded Coder - Getting Started Guide
Embedded Coder - Getting Started Guide
R2011b
Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information
508-647-7000 (Phone) 508-647-7001 (Fax) The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site. Embedded Coder Getting Started Guide COPYRIGHT 2011 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc. FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the governments needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for more information.
Revision History
New for Version 6.0 (Release 2011a) New for Version 6.1 (Release 2011b)
Contents
Product Overview
1
Product Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Code Generation Technology . . . . . . . . . . . . . . . . . . . . . . . Code Generation Extensions . . . . . . . . . . . . . . . . . . . . . . . . Target Environments and Applications . . . . . . . . . . . . . . About Target Environments . . . . . . . . . . . . . . . . . . . . . . . . . Types of Target Environments Supported By Embedded Coder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Applications of Supported Target Environments . . . . . . . . Prerequisite Knowledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Simulink Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Algorithm Development Workflows 1-2 1-3 1-4 1-5 1-5 1-5 1-8 1-10 1-10 1-10 1-12
.................
MATLAB Tutorials
2
About the Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About MATLAB Coder . . . . . . . . . . . . . . . . . . . . . . . . . . . . How Embedded Coder Works With MATLAB Coder . . . . Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting Up Tutorial Files . . . . . . . . . . . . . . . . . . . . . . . . . . . Controlling C Code Style . . . . . . . . . . . . . . . . . . . . . . . . . . . About This Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 2-2 2-2 2-3 2-3 2-4 2-4
iii
Copying Files Locally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting Up the MATLAB Coder Project . . . . . . . . . . . . . . . Configuring Build Parameters . . . . . . . . . . . . . . . . . . . . . . . Generating the C Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Viewing the Generated C Code . . . . . . . . . . . . . . . . . . . . . . Key Points to Remember . . . . . . . . . . . . . . . . . . . . . . . . . . . Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generating Reentrant C Code from MATLAB Code . . . About This Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Copying Files Locally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About the Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Providing a main Function . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring Build Parameters . . . . . . . . . . . . . . . . . . . . . . . Generating the C Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Viewing the Generated C Code . . . . . . . . . . . . . . . . . . . . . . Running the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Key Points to Remember . . . . . . . . . . . . . . . . . . . . . . . . . . . Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tracing Between Generated C Code and MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About This Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Copying Files Locally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring Build Parameters . . . . . . . . . . . . . . . . . . . . . . . Generating the C Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Viewing the Generated C Code . . . . . . . . . . . . . . . . . . . . . . Tracing Back to the Source MATLAB Code . . . . . . . . . . . . Key Points to Remember . . . . . . . . . . . . . . . . . . . . . . . . . . . Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-5 2-5 2-6 2-7 2-7 2-8 2-8 2-9 2-9 2-10 2-11 2-12 2-15 2-15 2-15 2-16 2-17 2-17
Simulink Tutorials
3
About the Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Third-Party Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Required Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2 3-2 3-3 3-3 3-3
iv
Contents
Configuring Model and Generating Code . . . . . . . . . . . . About this Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring Model for Code Generation . . . . . . . . . . . . . . . Checking Model for Adverse Conditions and Settings . . . . Generating Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Reviewing Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controlling Appearance of Generated Code . . . . . . . . . . About this Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Customizing Code Comments . . . . . . . . . . . . . . . . . . . . . . . . Customizing Appearance of Identifiers . . . . . . . . . . . . . . . . Customizing Code Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring Data Interface . . . . . . . . . . . . . . . . . . . . . . . . . About this Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating Data Objects for Named Data in Base Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring Data Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . Controlling Placement of Parameter and Constant Data in Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Including Signal Data Objects in Generated Code . . . . . . . Effects of Simulation on Data Typing . . . . . . . . . . . . . . . . . Viewing Data Objects in Generated Code . . . . . . . . . . . . . . Saving Base Workspace Data . . . . . . . . . . . . . . . . . . . . . . . . Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Partitioning and Exporting Functions . . . . . . . . . . . . . . . About this Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing Model Architecture to Control Execution Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controlling Function Location and File Placement in Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Mask to Pass Parameters into Library Subsystem . . Generating Code for Full Model and Exported Functions . . Changing Execution Order and Simulation Results . . . . . . Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-5 3-5 3-6 3-11 3-12 3-13 3-14 3-15 3-16 3-16 3-17 3-19 3-20 3-21 3-21 3-22 3-22 3-23 3-23 3-24 3-26 3-27 3-28 3-29 3-29 3-29 3-30 3-30 3-31 3-33 3-36 3-38 3-40 3-42 3-43
Integrating Generated Code into External Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About this Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Relocating Code to Another Development Environment . . Integrating Generated Code into Existing System . . . . . . . Setting Up Main Function . . . . . . . . . . . . . . . . . . . . . . . . . . Matching System Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . Building Project in Eclipse Environment . . . . . . . . . . . . . . Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Verifying Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . About this Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Methods for Verifying Generated Code . . . . . . . . . . . . . . . . Reusing Test Data By Importing and Exporting Test Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Verifying Behavior of Model with Software-in-the-Loop Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Verifying System Behavior By Importing and Exporting Test Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Testing with Processor-in-the-Loop Testing . . . . . . . . . . . . Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Evaluating Generated Code . . . . . . . . . . . . . . . . . . . . . . . . About this Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Evaluating Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Viewing Code Metrics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . About the Build Configurations . . . . . . . . . . . . . . . . . . . . . . Configuration 1: Reusable Functions, Data Type Double . . Configuration 2: Reusable Functions, Data Type Single . . Configuration 3: Nonreusable Functions, Data Type Single . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-44 3-44 3-45 3-46 3-46 3-48 3-51 3-52 3-52 3-53 3-53 3-54 3-55 3-56 3-59 3-62 3-62 3-62 3-63 3-63 3-63 3-64 3-64 3-64 3-65 3-66 3-67
vi
Contents
Installing and Using an IDE for the Integration and Testing Tutorials
A
Installing the Eclipse IDE and Cygwin Debugger . . . . . Installing the Eclipse IDE . . . . . . . . . . . . . . . . . . . . . . . . . . Installing the Cygwin Debugger . . . . . . . . . . . . . . . . . . . . . Integrating and Testing Code with the Eclipse IDE . . . Introducing Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Defining a New C Project . . . . . . . . . . . . . . . . . . . . . . . . . . . Configuring the Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . Starting the Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting the Cygwin Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . Actions and Commands in the Eclipse Debugger . . . . . . . . A-2 A-2 A-3 A-5 A-5 A-6 A-7 A-7 A-8 A-8
vii
viii
Contents
1
Product Overview
Product Description on page 1-2 Code Generation Technology on page 1-3 Code Generation Extensions on page 1-4 Target Environments and Applications on page 1-5 Prerequisite Knowledge on page 1-10 Algorithm Development Workflows on page 1-12
Product Overview
Product Description
Embedded Coder generates readable, compact, and fast C and C++ code for use on embedded processors, on-target rapid prototyping boards, and microprocessors used in mass production. Embedded Coder enables additional MATLAB Coder and Simulink Coder configuration options and advanced optimizations for fine-grain control of the generated codes functions, files, and data. These optimizations improve code efficiency and facilitate integration with legacy code, data types, and calibration parameters used in production. You can incorporate a third-party development environment into the build process to produce an executable for turnkey deployment on your embedded system. Embedded Coder offers built-in support for AUTOSAR and ASAP2 software standards. It also provides traceability reports, code interface documentation, and automated software verification to support DO-178, IEC 61508 and ISO 26262 software development. Learn more about MathWorks support for certification in automotive (http://www.mathworks.com/automotive/standards/iso-26262.html), aerospace (http://www.mathworks.com/aerospace-defense/), and industrial automation (http://www.mathworks.com/industrial-automation-machinery/) applications.
1-2
1-3
Product Overview
1-4
1-5
Product Overview
Description The same computer that runs MATLAB and Simulink. Typically, a host computer is a PC or UNIX1 environment that uses a non-real-time operating system, such as Microsoft Windows or Linux2. Non-real-time (general purpose) operating systems are nondeterministic. For example, those operating systems might suspend code execution to run an operating system service and then, after providing the service, continue code execution. Therefore, the executable for your generated code might run faster or slower than the sample rates that you specified in your model. A different computer than the host computer. A real-time simulator can be a PC or UNIX environment that uses a real-time operating system (RTOS), such as: xPC Target system A real-time Linux system A Versa Module Eurocard (VME) chassis with PowerPC processors running a commercial RTOS, such as VxWorks from Wind River Systems The generated code runs in real time. The exact nature of execution varies based on the particular behavior of the system hardware and RTOS. Typically, a real-time simulator connects to a host computer for data logging, interactive parameter tuning, and Monte Carlo batch execution studies.
Real-time simulator
Embedded microprocessor
A computer that you eventually disconnect from a host computer and run as a standalone computer as part of an electronics-based product. Embedded microprocessors range in price and performance, from high-end digital signal processors (DSPs) to process communication signals to inexpensive 8-bit fixed-point microcontrollers in mass production (for example, electronic parts produced in the millions of units). Embedded microprocessors can: Use a full-featured RTOS
1. UNIX is a registered trademark of The Open Group in the United States and other countries. 2. Linux is a registered trademark of Linus Torvalds.
1-6
Target Environment
Description
Be driven by basic interrupts Use rate monotonic scheduling provided with code generation A target environment can: Have single- or multiple-core CPUs Be a standalone computer or communicate as part of a computer network In addition, you can deploy different parts of a Simulink model on different target environments. For example, it is common to separate the component (algorithm or controller) portion of a model from the environment (or plant). Using Simulink to model an entire system (plant and controller) is often referred to as closed-loop simulation and can provide many benefits, such as early verification of a component. The following figure shows example target environments for code generated for a model.
Environment model
Code generation
Embedded microprocessor
Real-time simulator
1-7
Product Overview
Rapid simulation
System simulation
System simulation
1-8
Description You generate code for a detailed design that you can run in real time on an embedded microprocessor while tuning parameters and monitoring real-time data. This design step allows you to assess, interact with, and optimize code, using embedded compilers and hardware. From a model, you generate code that is optimized for speed, memory usage, simplicity, and possibly, compliance with industry standards and guidelines. You execute generated code with your plant model within Simulink to verify successful conversion of the model to code. You might change the code to emulate target word size behavior and verify numerical results expected when the code runs on an embedded microprocessor. Or, you might use actual target word sizes and just test production code behavior. You test an object code component with a plant or environment model in an open- or closed-loop simulation to verify successful model-to-code conversion, cross-compilation, and software integration. You verify an embedded system or embedded computing unit (ECU), using a real-time target environment.
1-9
Product Overview
Prerequisite Knowledge
In this section... MATLAB Users on page 1-10 Simulink Users on page 1-10
MATLAB Users
Be familiar with: MATLAB Coder Code Generation from MATLAB MATLAB Function block If you are familiar with C language constructs and want to learn how to map commonly used C constructs to code generated from MATLAB program design patterns, see Patterns for C Code in the Embedded Coder documentation.
Simulink Users
Be familiar with: Simulink and Stateflow software to create models or state machines as block diagrams, running such simulations in Simulink, and interpreting output in the MATLAB workspace. Generating code and building executable programs from Simulink models. High-level programming language concepts applied to embedded, real-time systems. While you do not need to program in C or other programming languages to create, test, and deploy embedded systems, using Embedded Coder software, successful emulation and deployment of embedded systems requires familiarity with parameters and design constraints. The Embedded Coder documentation assumes you have a basic understanding of real-time and embedded system concepts, terminology, and environments.
1-10
Prerequisite Knowledge
If you have not done so, you should study: The tutorials in the Simulink Coder Getting Started Guide. The tutorials provide hands-on experience in configuring models for code generation and generating code, setting up a data interface, and integrating external code. Model Architecture and Design and Scheduling in the Simulink Coder documentation. These sections give a general overview of the architecture and execution of generated code. If you are familiar with C language constructs and want to learn about how to map commonly used C constructs to code generated from model design patterns that include Simulink blocks, Stateflow charts, and MATLAB function blocks, see Patterns for C Code.
1-11
Product Overview
1-12
MATLAB Coder
Simulink Coder
C or C++ code
The following table summarizes how to generate C or C++ code for each of the approaches and identifies where you can find more information.
1-13
Product Overview
You generate code by... Using MATLAB Coder projects Entering the function codegen in the MATLAB Command Window Configuring and initiating code generation for your model or subsystem with the Simulink Configuration Parameters dialog. Including MATLAB code in Simulink models or subsystems by using the MATLAB Function block. To use this block, you can do one of the following: Copy your code into the block. Call your code from the block by referencing the files on the MATLAB path.
For more information, see... Workflow Overview in the MATLAB Coder documentation.
Code Generation from MATLAB documentation MATLAB Function block in the Simulink documentation
To use MATLAB code and Simulink models for a Model-Based Design project: Start by using MATLAB to develop an algorithm for research and early development. Later want to integrate the algorithm into a graphical model for system deployment and verification. Benefits of this approach include: Richer system simulation environment Ability to verify the MATLAB code
1-14
Simulink Coder and Embedded Coder C/C++ code generation for the model and MATLAB code If you are familiar with C language constructs and want to learn about how to map commonly used C constructs to code generated from model design patterns that include Simulink blocks, Stateflow charts, and MATLAB functions, see Patterns for C Code in the Embedded Coder documentation.
1-15
Product Overview
1-16
2
MATLAB Tutorials
About the Tutorials on page 2-2 Controlling C Code Style on page 2-4 Generating Reentrant C Code from MATLAB Code on page 2-9 Tracing Between Generated C Code and MATLAB Code on page 2-18
MATLAB Tutorials
2-2
Prerequisites
To complete these tutorials, you must install the following products: MATLAB MATLAB Coder Embedded Coder C compiler For a list of supported compilers, see
http://www.mathworks.com/support/compilers/current_release/.
You must set up the C compiler before generating C code. See Setting Up the C/C++ Compiler in the MATLAB Coder documentation. For instructions on installing MathWorks products, see the MATLAB installation documentation for your platform. If you have installed MATLAB and want to check which other MathWorks products are installed, in the MATLAB Command Window, enter ver .
2-3
MATLAB Tutorials
Prerequisites
To complete this tutorial, install the required products and set up your C compiler as described in Prerequisites on page 2-3.
2-4
Required Files
Type Function code Name
test_code_style.m
To run the tutorial, copy this file to a local folder. For instructions, see Copying Files Locally on page 2-5.
Your work folder now contains the file you need to complete this tutorial.
where work is the full path of the work folder containing your files.
2 At the MATLAB command line, enter
By default, the project opens in the MATLAB workspace on the right side.
2-5
MATLAB Tutorials
3 On the project Overview tab, click the Add files link and browse to the
file test_code_style.m and then click OK to add the file to the project.
4 Define the type of input x.
Why Specify an Input Definition? Because C and C++ are statically-typed languages, MATLAB Coder must determine the properties of all variables in the MATLAB files at code generation time. For more information, see Primary Function Input Specification in the MATLAB Coder documentation. On the Overview tab, select the input parameter x and then click the Actions icon to the right of this parameter to open the context menu.
5 From the menu, select Define Type. 6 In the Define Type dialog box, set Class to int16. Click OK.
Note The Convert if-elseif-else patterns to switch-case statements optimization works only for integer and enumerated type inputs.
switch-case statements.
6 On the Report tab, verify that Always create a code generation report
2-6
2-7
MATLAB Tutorials
Learn More
To... Learn how to create and set up a MATLAB Coder project Learn how to generate C/C++ code from MATLAB code at the command line See... Setting Up a MATLAB Coder Project in the MATLAB Coder documentation.
codegen in the MATLAB Coder documentation.
2-8
2-9
MATLAB Tutorials
Prerequisites
To complete this tutorial, install the required products and set up your C compiler as described in Prerequisites on page 2-3
Required Files
Type Function code Name
matrix_exp.m
Description MATLAB Function that computes matrix exponential of the input matrix using Taylor series and returns the computed output. Calls the reentrant code.
C main function
main.c
To run the tutorial, copy these files to a local folder. For instructions, see Copying Files Locally on page 2-10.
Your work folder now contains the files you need to complete this tutorial.
4 Set your MATLAB current folder to the work folder that contains your files
where work is the full path of the work folder containing your files.
2-10
When you generate reusable, reentrant code, codegen supports dynamic allocation of function variables that are too large for the stack, as well as persistent and global variables. codegen generates a header file, primary_function_name_types.h, which you must include when using the generated code. This header file contains the following structures: primary_function_nameStackData Contains the user allocated memory. You must pass a pointer to this structure as the first parameter to all functions that use it either directly, because the function uses a field in the structure, or indirectly, because the function passes the structure to a called function.
2-11
MATLAB Tutorials
If the algorithm uses persistent or global data, the primary_function_nameStackData structure also contains a pointer to the primary_function_namePersistentData structure. Including this pointer means that you have to pass only one parameter to each calling function. primary_function_namePersistentData If your algorithm uses persistent or global variables, codegen provides a separate structure for them and adds a pointer to this structure to the memory allocation structure. Having a separate structure for persistent and global variables allows you to allocate memory for these variables once and share them with all threads if desired. However, if there is no communication between threads, you can choose to allocate memory for these variables per thread or per application.
2-12
Contents of main.c
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include "matrix_exp.h" #include "matrix_exp_initialize.h" #include "matrix_exp_terminate.h" #include "rtwtypes.h" #define NUMELEMENTS (160*160)
/* The thread_function calls the matrix_exp function written in MATLAB */ DWORD WINAPI thread_function(PVOID dummyPtr) { IODATA *myIOData = (IODATA*)dummyPtr; matrix_exp_initialize(); matrix_exp(myIOData->spillData, myIOData->in, myIOData->out); matrix_exp_terminate(); return 0; }
void main() { HANDLE thread1, thread2; IODATA data1; IODATA data2; int32_T i;
/*Initializing data for passing to the 2 threads*/ matrix_expStackData* sd1 = (matrix_expStackData*)calloc(1,sizeof(matrix_expStackData)); matrix_expStackData* sd2 = (matrix_expStackData*)calloc(1,sizeof(matrix_expStackData));
2-13
MATLAB Tutorials
/*Initializing the 2 threads and passing appropriate data to the thread functions*/ printf("Starting thread 1...\n"); thread1 = CreateThread(NULL , 0, thread_function, (PVOID) &data1, 0, NULL); if (thread1 == NULL){ perror( "Thread 1 creation failed."); exit(EXIT_FAILURE); }
printf("Starting thread 2...\n"); thread2 = CreateThread(NULL, 0, thread_function, (PVOID) &data2, 0, NULL); if (thread2 == NULL){ perror( "Thread 2 creation failed."); exit(EXIT_FAILURE); }
/*Wait for both the threads to finish execution*/ if (WaitForSingleObject(thread1, INFINITE) != WAIT_OBJECT_0){ perror( "Thread 1 join failed."); exit(EXIT_FAILURE); }
free(sd1); free(sd2);
2-14
This command creates a coder.EmbeddedCodeConfig object which contains all the configuration parameters that the codegen function needs to generate standalone C/C++ static libraries and executables for an embedded target.
2 Enable reentrant code generation.
e.MultiInstanceCode = true;
codegen generates a C executable, matrix_exp.exe, in the current folder and C code in the /codegen/exe/matrix_exp subfolder. Because you selected report generation, codegen provides a link to the report.
variables that are too large to fit on the stack. To view this header file:
2-15
MATLAB Tutorials
1 Click the View report link to open the code generation report. 2 In the report, click the C code tab. 3 On this tab, click the link to matrix_exp_types.h.
/* * matrix_exp_types.h * * MATLAB Coder code generation for function 'matrix_exp' */ #ifndef __MATRIX_EXP_TYPES_H__ #define __MATRIX_EXP_TYPES_H__ /* Type Definitions */ typedef struct { struct { real_T F[25600]; real_T Y[25600]; } f0; } matrix_expStackData; #endif /* End of code generation (matrix_exp_types.h) */
% This example can only be run on Windows platforms if ~ispc error('This example requires Windows-specific libraries and can only be run on Windows.'); end system('matrix_exp.exe')
2-16
Includes the generated header file, primary_function_name_types.h. This file defines the primary_function_nameStackData global structure. This structure contains local variables that are too large to fit on the stack. For each thread, allocates memory for stack data. Calls primary_function_name_initialize . Calls primary_function_name. Calls primary_function_name_terminate. Frees the memory used for stack data.
Use the -config option to pass the code generation configuration object to the codegen function. Use the -args option to specify input parameters at the command line. Use the -report option to create a code generation report.
Learn More
To... Learn more about the generated code API Call reentrant code with no persistent or global data on UNIX Call reentrant code with persistent data on Windows Call reentrant code with persistent data on UNIX See... Generated Code API Example: Calling Reentrant Code with No Persistent or Global Data (UNIX Only) Example: Calling Reentrant Code Multithreaded with Persistent Data (Windows Only) Example: Calling Reentrant Code Multithreaded with Persistent Data (UNIX Only)
2-17
MATLAB Tutorials
Prerequisites
To complete this tutorial, install the required products and set up your C compiler as described in Prerequisites on page 2-3
2-18
Required File
Type Function code Name
polar2cartesian.m
To run the tutorial, copy this file to a local folder. For instructions, see Copying Files Locally on page 2-19.
Your work folder now contains the file you need to complete this tutorial.
4 Set your MATLAB current folder to the work folder that contains the file
where work is the full path of the work folder containing your files.
Contents of polar2cartesian.m
function [x y] = polar2cartesian(r,theta) %#codegen % Convert polar to Cartesian x = r * cos(theta); y = r * sin(theta);
2-19
MATLAB Tutorials
comments in the generated code and the function signature in the function banner.
cfg.MATLABSourceComments = true;
3 Enable the MATLBFcnDesc option to include the function help text in the
function banner.
cfg.MATLABFcnDesc = true;
codegen generates a C library, polar2cartesian.lib, in the current folder and C code in the /codegen/lib/polar2cartesian subfolder. Because you selected report generation, codegen provides a link to the report.
2-20
Examine the generated code. The function help text Convert polar to Cartesian appears in the function header. The source code appears as comments in the generated code.
/* * function [x y] = polar2cartesian(r,theta) * Convert polar to Cartesian */ void straightline(real_T r, real_T theta, ... real_T *x, real_T *y) { /* 'polar2cartesian:4' x = r * cos(theta); */ *x = r * cos(theta); /* 'polar2cartesian:5' y = r * sin(theta); */ *y = r * sin(theta); }
MATLABSourceCode option to include MATLAB source code as comments in the generated code and the function signature in the function banner MATLBFcnDesc option to include the function help text in the function
banner
Use the -config option to pass the code generation configuration object to the codegen function. Use the -report option to create a code generation report.
2-21
MATLAB Tutorials
Learn More
To... Learn more about code traceability Learn about the location of comments in the generated code See traceability limitations See... About Code Traceability in the MATLAB Coder documentation. Location of Comments in Generated Code in the MATLAB Coder documentation. Traceability Limitations in the MATLAB Coder documentation.
2-22
3
Simulink Tutorials
About the Tutorials on page 3-2 Configuring Model and Generating Code on page 3-5 Controlling Appearance of Generated Code on page 3-16 Configuring Data Interface on page 3-22 Partitioning and Exporting Functions on page 3-30 Integrating Generated Code into External Environment on page 3-44 Verifying Generated Code on page 3-53 Evaluating Generated Code on page 3-63
Simulink Tutorials
Introduction
The following tutorials are based on the throttle controller example model described in Getting Familiar with the Example Model and Testing Environment in the Simulink Coder documentation. The tutorials will help you get started with using Embedded Coder to generate code from Simulink models and subsystems for embedded system applications. Configuring Model and Generating Code on page 3-5 Configuring Data Interface on page 3-22 Controlling Appearance of Generated Code on page 3-16 Partitioning and Exporting Functions on page 3-30 Integrating Generated Code into External Environment on page 3-44 Verifying Generated Code on page 3-53 Evaluating Generated Code on page 3-63 Each tutorial focuses on a specific aspect of code generation or integration for embedded systems and is self-contained. Use only the tutorials that apply to your needs. Each tutorial uses a unique Simulink demo model and data set. As you proceed through the tutorials, you save each model after you have worked on it, preserving your modifications to the model and model data for future examination. To prevent any errors from carrying over to the next tutorial, begin the next tutorial by opening a new model and loading new data.
3-2
Prerequisites
You must know how to: MathWorks products
Read, write, and apply MATLAB scripts Create Simulink models Include Stateflow charts in Simulink models Run Simulink simulations and evaluate the results Use C data types and storage classes Use function prototypes and call functions Compile a C function Evaluate code readability Evaluate RAM/ROM usage Evaluate system execution performance
C programming
Third-Party Software
To compile and build generated code for the integration and testing tutorials, you can use an Integrated Development Environment (IDE) or equivalent tools such as command-line compilers and makefiles. Appendix A, Appendix A, Installing and Using an IDE for the Integration and Testing Tutorials describes how to install and use the Eclipse IDE for C/C++ Developers and the Cygwin debugger for integrating and testing your generated code.
Required Files
Each tutorial uses a unique example model file and data set. Before you use each example file, place a copy in a in a writable location on your MATLAB path. Proceed through the tutorials from this location. As you proceed through a tutorial, save your changes for future examination.
3-3
Simulink Tutorials
To avoid potentially introducing errors into the next tutorial, begin each tutorial by opening a new model and loading new data.
3-4
Prerequisites
Completed Getting Familiar with the Example Model and Testing Environment and Configuring the Model and Generating Code in the Simulink Coder documentation
Required File
rtwdemo_throttlecntrl_configert.mdl
3-5
Simulink Tutorials
path.
2 In the Configuration Parameters dialog box, configure the solver. To
generate code, configure the model to use a fixed-step solver. For this example, make sure that the Type, Solver, and Fixed-step size parameters are set as described in the following table. Parameter Type Setting
Fixed-step
Effect on Generated Code Maintains a constant (fixed) step size, which is required for code generation Applies a fixed-step integration technique for computing the state derivative of the model Sets the base rate; must be the lowest common multiple of all rates in the system
Solver
Fixed-step size
3-6
parameters. When this parameter is set, the code generator optimizes the code by replacing model parameters with constant values. Unless a model is still under development, consider using this setting when generating code for an embedded system.
pane to specify the device type, word size, and byte ordering of the target hardware. Assume that the throttle controller model targets a generic 32-bit embedded processor. Set Device type to 32-bit Embedded Processor.
5 Open the Code Generation > General pane. Set the System target
file parameter to the embedded real-time target file, ert.tlc. The code generator uses this target file to generate code that is optimized for embedded system deployment. The list of Code Generation subpanes expands to include: SIL and PIL Verification
3-7
Simulink Tutorials
Code Style Templates Code Placement Data Type Replacement Memory Sections
6 Set code generation parameters based on your application objectives.
Configuring a model to meet specific objectives (requirements) for code generation can be an extremely complex, time consuming task. The Code Generation Advisor simplifies this task by allowing you to select and prioritize one or more of the following objectives: Execution efficiency ROM efficiency RAM efficiency MISRA-C:2004 guidelines Safety precaution Traceability Debugging Each objective includes a set of Code Generation Advisor checks that you can use to: Review the model configuration parameters against the recommended values of the objectives. Verify that the model configuration parameters are set to create code that meets your model objectives. Some objectives recommend different parameter settings and include different checks in the Code Generation Advisor. When objectives conflict, the priorities of the selected objectives determine which recommendations and checks the advisor presents. For this tutorial, configure the model for execution and memory efficiency:
a On the Code Generation pane, click Set objectives. The Set
3-8
7 Review the model against the selected objectives by using the Code
Generation Advisor.
a On the Code Generation pane, click Check model. A System Selector
and click OK. The Code Generation Advisor dynamically creates and runs a list of checks based on the selection and prioritization of the objectives. This task might take a few minutes.
3-9
Simulink Tutorials
c Evaluate the warning condition flagged for the first check in the report,
which reviews configuration parameter settings and recommends values based on the objectives. Select the first check and click Modify Parameters to set parameters to recommended values. Then, click Run This Check to rerun the check. The warning symbol should disappear.
d Select hardware implementation check, which is the second check
flagged with a warning. This check identifies inconsistencies and incomplete specification of hardware attributes, which can lead to inefficient or incorrect code for the target hardware. Under Recommended Action, the report suggests that you specify byte ordering and signed integer division rounding for your target hardware. For this tutorial, assume you are using a target that supports both big-endian and little-endian byte ordering. Therefore, Byte ordering can remain Unspecified. However, you should click the Signed integer division rounding link and set the Signed integer division
3-10
rounds to parameter to Zero (the most common behavior), and rerun the check. Note that only the warning for byte ordering remains.
e Select the third check that is flagged as a warning. The warning
concerns arithmetic exceptions for integer division in generated code. Assume that you verified that your model cannot cause exceptions in division operations, and as the Code Generation Advisor suggests, select Optimization > Remove code that protects against division arithmetic exceptions. Update the model diagram and rerun the check. The warning should disappear.
f
Close the Code Generation Advisor window. For more information, see Determining Whether the Model is Configured for Specified Objectives.
function.
a In the Model Explorer window, select throttlcngrl_configert in the
left pane.
b Right-click and select Export Active Configuration Set. The Export
For more information, see Save a Configuration Set and Load a Saved Configuration Set in the Simulink documentation.
9 Close the Model Explorer. Save and close the model.
throttlecntrl_configert.mdl.
2 Start the Model Advisor.
3-11
Simulink Tutorials
then click OK. It might take a few minutes for the Model Advisor window to open.
4 Expand By Product and Embedded Coder, enable all checks under
Embedded Coder, click Embedded Coder, and in the right pane, click Run Selected Checks. The report summary indicates two warnings remain.
The remaining warnings concern byte ordering and MISRA-C:2004 compliance. Ignore the byte-ordering warning for the reason cited earlier.
5 Evaluate the MISRA conditions using the links in the analysis results,
Generating Code
1 Open throttlecntrl_configert.mdl. 2 In the Configuration Parameters dialog box, select Code
Generation > Report > Static code metrics report. This setting includes the static code metrics report in the HTML code generation report. The static code metrics report provides metrics on source files, global variables, and functions.
3 In the Configuration Parameters dialog box, select Code
in the MATLAB Command Window. The code generator produces standard C and header files and an HTML code generation report. The code generator places the files in a build folder, a subfolder named throttlecntrl_configert_ert_rtw under your current working folder.
3-12
The subfolder name is the model name ending with the string _ert_rtw. The resulting code, while computationally efficient, is not yet organized for integration into a production environment.
open the generated throttlecntrl_configert.c file in the build folder and review the code. Note the following: Identification, version, timestamp, and configuration comments. Data definitions. Controller code is in one function, throttlecntrl_configert_step. Operations of multiple blocks are in one equation. Generated data structures (for example, throttlecntrl_configert_U.pos_rqst) define all data. throttlecntrl_configert_initialize and throttlecntrl_configert_terminate functions contain no code.
2 From the generated HTML code generation report, select the Static Code
Metrics Report in the Contents section. Note the file statistics, size of the largest global variables, and function call paths that require the largest stack size.
3 Close the throttle controller model.
Consider examining the following files by clicking the links in the HTML report, or by exploring other generated files in the build folder. File
throttlecntrl_configert.c throttlecntrl_configert_data.c ert_main.c
Description C file that contains step and initialization functions C file that assigns values to generated data structures Example main module that includes a simple scheduler
3-13
Simulink Tutorials
File
throttlecntrl_configert.h throttlecntrl_configert_private.h throttlecntrl_configert_types.h
Description Header file that defines data structures Header file that defines data used only by the generated code Header file that defines the model data structure
For more information about these and other generated files, see Code Modules.
Key Points
To generate code for an embedded system, you must at least change the model configuration to specify:
A fixed-step solver Hardware settings that match the target hardware specifications ERT system target format Configuration objectives that align with application requirements
Consider configuring the model with parameter inlining enabled if C code debugging is not required. You can check and modify the configuration of a model to best align with application objectives by using the Code Generation Advisor. You can save a model configuration for future use or for applying it to another model. Use the Export Active Configuration Set dialog box, available by right clicking on the model in the Model Explorer. Before generating code, consider checking a model with the Model Advisor. The code generator places generated files in a subfolder (throttlecntrl_configert_ert_rtw) of your working folder. Review the static code metrics report to check that possible memory usage is within your requirements.
3-14
Learn More
Determining Whether the Model is Configured for Specified Objectives Application Considerations Save a Configuration Set and Load a Saved Configuration Set in the Simulink documentation. Consulting the Model Advisor in the Simulink documentation. Generate a Static Code Metrics Report for Code Reviews Program Building, Interaction, and Debugging
3-15
Simulink Tutorials
Prerequisites
You are able to: Open and modify Simulink models and subsystems Set block properties Set model configuration parameters Read C code
3-16
Required File
rtwdemo_throttlecntrl_codeappearance.mdl
MATLAB path.
2 Generate code and examine the comments in the generated file
throttlecntrl_codeappearance.c.
3 Add descriptions to the properties for the three model Inport blocks. For
each block, right-click, select Block properties, and enter the descriptions listed in the following table. For Inport Block...
pos_rqst fbk_1 fbk_2
Add Description... Throttle position request input for PI controller subsystems Feedback input for PI controller subsystem
PI_ctrl_1
Specifically, compare the following before and after code fragments: Before
/* Sum: '<S2>/Sum2' incorporates: * * */ Inport: '<Root>/fbk_1' Inport: '<Root>/pos_rqst'
3-17
Simulink Tutorials
rtb_Sum3 = (*pos_rqst) - my_throttlecntrl_codeappearan_U.fbk_1; . . . /* Sum: '<S3>/Sum2' incorporates: * * */ rtb_Sum3 = (*pos_rqst) - fbk_2; Inport: '<Root>/fbk_2' Inport: '<Root>/pos_rqst'
After
/* Sum: '<S2>/Sum2' incorporates: * * * * Block description for '<Root>/fbk_1': * * * Block description for '<Root>/pos_rqst': * */ rtb_Sum3 = (*pos_rqst) - my_throttlecntrl_codeappearan_U.fbk_1; . . . /* Sum: '<S3>/Sum2' incorporates: * * * * Block description for '/fbk_2': * * * Block description for '<Root>/pos_rqst': * */ rtb_Sum3 = (*pos_rqst) - fbk_2; Throttle position request input for PI controller subsystems Feedback input for PI controller subsystem PI_ctrl_2 Inport: '<Root>/fbk_2' Inport: '<Root>/pos_rqst' Throttle position request input for PI controller subsystems Feedback input for PI controller subsystem PI_ctrl_1 Inport: '<Root>/fbk_1' Inport: '<Root>/pos_rqst'
3-18
For more information, see Configuring Code Comments in Embedded System Code
throttlecntrl_codeappearance.c.
3 Open the Code Generation > Symbols pane of the Configuration
Parameters dialog box and explore the available options. For token and macro details, see the Help for a specific parameter.
4 Change the setting of the Local block output variables parameter to
OutVar_$N$M.
5 Generate code and examine the file throttlecntrl_codeappearance.c.
Specifically, compare the following before and after code fragments: Before
rtb_Sum3 = throttlecntrl_configert_U.pos_rqst throttlecntrl_configert_U.fbk_1; . . . rtb_Sum3 = throttlecntrl_configert_U.pos_rqst throttlecntrl_configert_U.fbk_2;
After
OutVar_Sum3 = throttlecntrl_codeappearance_U.pos_rqst throttlecntrl_codeappearance_U.fbk_1; . . .
3-19
Simulink Tutorials
For more information, see Configuring Generated Identifiers in Embedded System Code
throttlecntrl_codeappearance.c.
3 Open the Code Generation > Code Style pane of the Configuration
Specifically, compare the following before and after code fragments: Before
throttlecntrl_configert_DWork.Discrete_Time_Integrator1_DSTAT = (((-0.03 * rt_Lookup((const real_T *)throttlecntrl_configert_ConstP.pooled4, 9, rtb_Sum3, (const real_T *)throttlecntrl_configert_ConstP.pooled5)) * rtb_Sum3) * 0.001) + throttlecntrl_configert_DWork.Discrete_Time_Integrator1_DSTAT;
After
throttlecntrl_codeappeara_DWork.Discrete_Time_Integrator1_DSTAT = -0.03 * rt_Lookup((const real_T *)throttlecntrl_codeappear_ConstP.pooled4, 9, OutVar_Sum3, (const real_T *) throttlecntrl_codeappear_ConstP.pooled5) * OutVar_Sum3 * 0.001 + throttlecntrl_codeappeara_DWork.Discrete_Time_Integrator1_DSTAT;
3-20
Key Points
Control and customize the following aspects of generated code appearance to optimize the code, simplify maintenance, improve code readability, or comply with company code conventions and style: Customize aspects of generated code appearance to meet application requirements. You can document generated code specifying a level of code comments depending on the application objectives. You can customize identifiers in generated code, for example, to enhance readability or comply with company code guidelines or standards. Available code style customizations pertain to the parentheses level, operand order in expressions, condition expressions and patterns, and use of the extern keyword.
Learn More
Configuring Code Comments in Embedded System Code and Code Generation Pane: Comments Configuring Generated Identifiers in Embedded System Code and Code Generation Pane: Symbols Controlling Code Style and Code Generation Pane: Code Style
3-21
Simulink Tutorials
Prerequisites
Understanding of ways to represent and use data and signals in models. Familiarity with representing data constructs as data objects. Completed Configuring the Data Interface in the Simulink Coder documentation.
3-22
Required Files
rtwdemo_throttlecntrl_dataplacement.mdl rtwdemo_throttlecntrl_testharnessert.mdl
MATLAB path.
2 In the model window, select Tools > Data Object Wizard. The Data
constructs. After a few minutes, constructs fbk_1 and pos_cmd_two appear in the dialog box.
4 Click Check All to select both constructs. 5 Click Apply Package to apply the default Simulink package for the data
objects.
6 Click Create to create the data objects. Constructs fbk_1 and pos_cmd_two
3-23
Simulink Tutorials
2 Configure the fbk_1 and pos_cmd_two signals with the following settings.
Signal
fbk_1 pos_cmd_two
Data Type
double double
Storage Class
ImportedExtern ExportedGlobal
throttlecntrl_dataplacement.mdl.
2 In the Configuration Parameters dialog box, open Code
eval_data.c
3-24
#include "rtwtypes.h" #include "throttlecntrl_dataplacement_types.h" /* Const memory section */ /* Definition for custom storage class: Const */ const real_T I_Gain = -0.03; const real_T I_InErrMap[9] = { -1.0, -0.5, -0.25, -0.05, 0.0, 0.05, 0.25, 0.5, 1.0 } ; const real_T I_OutMap[9] = { 1.0, 0.75, 0.6, 0.0, 0.0, 0.0, 0.6, 0.75, 1.0 } ; const real_T P_Gain = 0.74; const real_T P_InErrMap[7] = { -1.0, -0.25, -0.01, 0.0, 0.01, 0.25, 1.0 } ; const real_T P_OutMap[7] = { 1.0, 0.25, 0.0, 0.0, 0.0, 0.25, 1.0 } ;
eval_data.h
#ifndef RTW_HEADER_eval_data_h_ #define RTW_HEADER_eval_data_h_ #include "rtwtypes.h" #include "throttlecntrl_dataplacement_types.h" /* Const memory section */ /* Declaration for custom storage class: Const */ extern const real_T I_Gain; extern const real_T I_InErrMap[9]; extern const real_T I_OutMap[9]; extern const real_T P_Gain; extern const real_T P_InErrMap[7]; extern const real_T P_OutMap[7]; #endif /* RTW_HEADER_eval_data_h_ */
For more information, see Managing Placement of Data Definitions and Declarations.
3-25
Simulink Tutorials
throttlecntrl_dataplacement.mdl.
2 In the Configuration Parameters dialog box, make sure that you select
4 Enable signal object resolution for all signals in the model simultaneously.
Messaging in the MATLAB Command Window indicates that the following signal objects are resolved. Signal...
pos_cmd_two error_reset max_diff fail_safe_pos fbk_1
5 Save and close the model.
Used By...
PI_ctrl_2/1 Define_Throt_Param/Constant4/1 Define_Throt_Param/Constant3/1 Define_Throt_Param/Constant/1 fbk_1/1
3-26
throttlecntrl_testharnessert.mdl.
3 In the test harness model, right-click the Unit_Under_Test Model block
The resulting plot shows that the difference between the golden and simulated versions of the model remains zero.
3-27
Simulink Tutorials
throttlecntrl_dataplacement.
2 Generate code for the model. 3 Examine the code in the generated file, throttlecntrl_dataplacement.c.
The following statement shows a sampling of generated variables for the model before you converted the data to data objects.
rtb_Sum3 = my_throttlecntrl_dataplacement_U.pos_rqst... - my_throttlecntrl_dataplacement_U.fbk_1;
3-28
After creating data objects for signals pos_rqst and fbk_1, the same line of generated code appears is:
rtb_Sum3 = *pos_rqst - fbk_1;
Key Points
You can declare data in Simulink models and Stateflow charts by using data objects. You can manage (create, view, configure, and so on) base workspace data from the Model Explorer or in the MATLAB Command Window. The Data Object Wizard provides a quick way to create data objects for constructs such as signals, buses, and parameters. You must explicitly configure data objects to appear by name in generated code. Because Simulink software uses the double data type for simulation, if all data types are set to double for a model, you can expect simulation and generated code behavior to match. Separation of the data from the model provides several benefits.
Learn More
Working with Data in the Simulink documentation Data, Function, and File Definition Custom Storage Classes in the Embedded Coder documentation Managing Placement of Data Definitions and Declarations in the Embedded Coder documentation
3-29
Simulink Tutorials
Prerequisites
Understand basic model architecture. Understand the difference between types of subsystems see Systems and Subsystems in the Simulink documentation. Understand the purpose of function-call subsystems. Understand what reentrant code is.
3-30
Familiarity with the Subsystem Parameters dialog box. Familiarity with the Mask Parameters dialog box. Familiarity with different ways to generate code for subsystems. Able to read C code.
Required File
rtwdemo_throttlecntrl_funcpartition.mdl rtwdemo_throttlecntrl_testharnessert.mdl
MATLAB path. This version of the throttle controller model includes three function-call subsystems and a subsystem consisting of a Stateflow chart, which controls execution order of the other subsystems.
3-31
Simulink Tutorials
Pos_Command_Arbitration.
3 Examine the Stateflow chart subsystem Execution_Order_Control. This
subsystem controls the execution order of the function-call subsystems. Later in the tutorial, you see how changing execution order can change simulation results.
4 Examine the new Signal Conversion blocks for output ports pos_cmd_one
and pos_cmd_two of the PI controllers. The Contiguous copy setting for the Output block parameter makes it possible for the PI controller functions in the generated code to be reentrant.
5 Close the model.
3-32
throttlecntrl_funcpartition.mdl.
2 Open the Subsystem Parameters dialog box for subsystems PI_ctrl_1 and
3-33
Simulink Tutorials
automatically selected and unavailable for atomic subsystems. When set, this parameter causes Simulink software to treat block methods associated with a subsystem as a unit when determining execution order. The parameter provides a way to group functional aspects of a model at the execution level. This parameter enables parameters on the Code Generation tab.
c Click the Code Generation tab.
3-34
Enables you to name the function that the code generator produces for a subsystem. In this case, the code generator names the reusable function PI_Cntrl_Reusable.
Use function name causes the code generator to place the generated function in a separate file and name it with the same name as the generated function. In this case, the code generator places the function in the model build folder in the file the PI_Cntrl_Reusable.c.
as atomic unit on the Main tab is already selected. The following table provides the rationale for the parameter settings on the Code Generation tab.
3-35
Simulink Tutorials
Auto causes the code generator to place the function code in the throttlecntrl_funcpartition.c
file.
4 Open the Subsystem Parameters dialog box for subsystem
subsystem, the Treat as atomic unit parameter is not set, restricting Function packaging to Function only.
5 Close the model.
3-36
throttlecntrl_funcpartition.mdl.
2 Open the Mask Parameters dialog box for subsystem PI_ctrl_1 by
double-clicking the subsystem. The dialog box opens, showing data objects for gain parameters P_gain and I_gain.
3 Open the Mask Parameters dialog box for subsystem PI_ctrl_2. For this
subsystem, Simulink creates two new data objects, P_Gain_2 and I_Gain_2.
3-37
Simulink Tutorials
throttlecntrl_funcpartition.mdl.
2 Generate code for the model. 3 Export a function for the PI_ctrl_1 subsystem. a In the model window, right-click PI_ctrl_1 and select Code
Generation > Export Functions. The Build code for Subsystem dialog box opens.
b In the Build code for Subsystem dialog box, click Build. The code
generator produces a complete set of code files for the subsystem and places them in the build folder PI_ctrl_1_ert_rtw.
4 If you have a Stateflow license, export a function for the
Pos_Command_Arbitration subsystem. The code generator produces a complete set of code files for the subsystem and places them in the build folder Pos_Command_Arbitration_ert_rtw.
5 Examine the generated code listed in the following table by locating and
opening the files in the respective build folders. File Full Build
PI_ctrl_1 Pos_Command_Arbitration
No No
3-38
File
Full Build
PI_ctrl_1
Pos_Command_Arbitration
No
No
Yes Called by
PI_ctrl_1
ert_main.c eval_data.c
Yes Yes*
* The content of eval_data.c differs between the full model and export function builds. The full model build includes all parameters that the model uses while the export function contains only variables that the subsystem uses.
6 Close all dialog boxes and the model.
generator passes data objects (P_Gain and I_Gain) from the subsystem masks into the reentrant code.
PI_Cntrl_Reusable(pos_rqst, fbk_1, &throttlecntrl_funcpartiti_DWork_DWork->PI_ctrl_1, I_Gain, P_Gain);
3 Search for PI_Cntrl_Reusable again. The second function call passes data
3-39
Simulink Tutorials
I_Gain_2, P_Gain_2);
You can use the test harness to see the effect of the execution order on the simulation results. The Execution_Order_Control subsystem is set up so that you can switch between two configurations, which change the execution order of the other subsystems in the model. Note The following procedure requires a Stateflow license. Change the execution order.
1 Open your copy of the throttle controller model,
throttlecntrl_funcpartition.mdl.
2 Right-click the Execution_Order_Control subsystem. Select Block
Choice > PI_1_then_PI_2_then_Pos_Cmd_Arb to set the subsystem execution order to PI_ctrl_1, PI_ctrl_2, then Pos_cmd_Arbitration.
3 Save the model. 4 Open the test harness model, throttlecntrl_testharnessert.mdl. 5 Set up the test harness to use model throttlecntrl_funcpartition as
Reference Parameters.
3-40
b Set Model name to throttlecntrl_funcpartition and click OK. c Update the model diagram. 6 Run the test harness.
The resulting plot shows that the difference between the golden and simulated versions of the model remains zero.
3-41
Simulink Tutorials
A slight variation exists in the output results depending on the order of execution. The difference is most noticeable when the desired input changes.
Key Points
One way of controlling execution order of subsystems during simulation is to use function-call subsystems and a Stateflow chart that models the calling functionality of a scheduler.
3-42
For atomic subsystems, you can instruct the code generator to partition algorithm code across multiple functions. When partitioning code across multiple functions, you can specify the name of the function for each subsystem and the name of the separate file for the code with parameters in the Subsystem Parameters dialog box. When a subsystem is reusable and has a mask, the generated code passes the masked parameters into the reentrant code as arguments. The code generator can build code at the system (full model) and subsystem levels. At the subsystem level, the code generator produces a full set of generated files in a separate build folder. You can change the execution of a model by using a subsystem containing a Stateflow chart that models the calling functionality of a scheduler and changing the setting of the Block Choice option on the subsystems context menu.
Learn More
in the Simulink Coder documentation S-Function Code Insertion in the Simulink Coder documentation Exporting Function-Call Subsystems in the Embedded Coder documentation Function Prototype Control in the Embedded Coder documentation Working with Block Masks in the Simulink documentation
3-43
Simulink Tutorials
Prerequisites
Access to installed versions of the Eclipse Integrated Development Environment (IDE) and the Cygwin Debugger. However, required integration tasks demonstrated in the tutorial are common to all integration environments. For information on how to install the Eclipse IDE and Cygwin Debugger, see Appendix A, Installing and Using an IDE for the Integration and Testing Tutorials Able to read C code. Familiarity with debugging tools and capabilities.
3-44
Required Files
rtwdemo_throttlecntrl_externenv.mdl Files in
matlabroot/toolbox/rtw/rtwdemos/EmbeddedCoderOverview/externenv_files, where matlabroot is your MATLAB installation folder
file throttlecntrl_externenv.zip. The number of files in the zip file depends on the version of Embedded Coder software that you are running and the configuration of the model. The compiler does not require all files in the zip file. The compiled executable size (RAM/ROM) is dependent on the link process. You must configure the linker to include only required object files. To generate the zip file manually, in the MATLAB Command Window:
1 Load the buildInfo.mat file, located in the build folder for the model. 2 Enter the command packNGo(buildInfo).
3-45
Simulink Tutorials
For more information about using the packNGo utility, see Relocating Code to Another Development Environment in the Simulink documentation.
Note For the example_main.c file, name your copy of the model file rtdemo_throttlecntrl_externenv.mdl asthrottlecntrl_externenv.mdl.
#include <stdio.h>
3-46
/* Model's header file */ /* MathWorks types */ /* Local data for PCG Eval */
/* Observable signals */ static BlockIO_throttlecntrl_externenv throttlecntrl_externenv_B; /* Observable states */ static D_Work_throttlecntrl_externenv throttlecntrl_externenv_DWork;
int simulationLoop = 0;
int_T main(void) { /* Initialize model */ rt_Pos_Command_Arbitration_Init(); /* Set up the data structures for chart*/ throttle_cnt_Define_Throt_Param(); /* SubSystem: '<Root>/Define_Throt_Param' */ defineImportData(); /* Defines the memory and values of inputs */
do /* This is the "Schedule" loop. Functions would be called based on a scheduling algorithm */ { /* HARDWARE I/O */
/* Call control algorithms */ PI_Cntrl_Reusable((*pos_rqst),fbk_1,&throttlecntrl_externenv_B.PI_ctrl_1, &throttlecntrl_externenv_DWork.PI_ctrl_1); PI_Cntrl_Reusable((*pos_rqst),fbk_2,&throttlecntrl_externenv_B.PI_ctrl_2, &throttlecntrl_externenv_DWork.PI_ctrl_2); pos_cmd_one = throttlecntrl_externenv_B.PI_ctrl_1.Saturation1; pos_cmd_two = throttlecntrl_externenv_B.PI_ctrl_2.Saturation1;
3-47
Simulink Tutorials
&throttlecntrl_externenv_B.sf_Pos_Command_Arbitration);
Identify areas of the code that perform each of the following functions: Defines function interfaces (function prototypes) Includes required files for data definition Defines extern data Initializes data Calls simulated hardware Calls algorithmic functions
3 Close example_main.c.
The order of execution of functions in example_main.c matches the order in which the test harness model and throttlecntrl_externenv.h call the subsystems. If you change the order of execution in example_main.c, results from the executable image differ from simulation results.
The system has three input signals: pos_rqst, fbk_1, and fbk_2. The two feedback signals are imported externs (ImportedExtern) and the position signal is an imported extern pointer (ImportedExternPointer). Because of how the signals are defined, the code generator does not create variables
3-48
for them. Instead, the signal variables are defined in a file that is external to the MATLAB environment.
a Open your copy of the file defineImportedData.c.
/* Define imported data */ #include "rtwtypes.h" real_T fbk_1; real_T fbk_2; real_T dummy_pos_value = 10.0; real_T *pos_rqst; void defineImportData(void) { pos_rqst = &dummy_pos_value; }
This file contains code for a simple C stub that defines the signal variables. The generated code has access to the data from the extern definitions in your generated throttlecntrl_externenv_Private.h file. In a real system, the data comes from other software components or from hardware devices.
b Close defineImportedData.c. c In your build folder, open throttlecntrl_externenv_Private.h. d Find and examine the following extern definitions.
/* Imported (extern) block signals */ extern real_T fbk_1; extern real_T fbk_2; /* '<Root>/fbk_1' */ /* '<Root>/fbk_2' */
You do not have to do anything with the output data. However, you can access the data in your generated throttlecntrl_externenv.h file.
a In your build folder, open throttlecntrl_externenv.h
3-49
Simulink Tutorials
Verifying Generated Code on page 3-53 shows how to save the output data to a log file.
3 Identify additional data.
The code generator creates several data elements that you do not need to access to complete this tutorial. Such data elements include: Block state values (integrator, transfer functions) Local parameters Time For this tutorial, the throttlecntrl_externenv.h file declares this data.
a In your build folder, open throttlecntrl_externenv.h b Search the file for the data listed in the following table. The table lists
the most common data structures. Depending on the configuration of the model, some or all of these structures are in the generated code. Data Type Constants Constants Output Output Internal data Internal data Internal data Internal data Parameters Data Name
throttlecntrl_externenv_cP throttlecntrl_externenv_cB throttlecntrl_externenv_U throttlecntrl_externenv_Y throttlecntrl_externenv_B throttlecntrl_externenv_D throttlecntrl_externenv_M throttlecntrl_externenv_Zero throttlecntrl_externenv_P
Data Purpose Constant parameters Constant block I/O Root and atomic subsystem input Root and atomic subsystem output Value of block output State information vectors Time and other system level data Zero-crossings Parameters
3-50
By default, the code generator creates functions that have a void Func(void) interface. If you configure the model or an atomic subsystem as reentrant code, the code generator creates a more complex function prototype.
a Open your copy of example_main.c. b The example_main function is configured to call the functions.
throttlecntrl_externenv_B.sf_Pos_Command_Arbitration); ((*pos_rqst),fbk_1,&throttlecntrl_externenv_B.PI_ctrl_1, &throttlecntrl_externenv_DWork.PI_ctrl_1); PI_Cntrl_Reusable((*pos_rqst),fbk_2,&throttlecntrl_externenv_B.PI_ctrl_2, &throttlecntrl_externenv_DWork.PI_ctrl_2); pos_cmd_one = throttlecntrl_externenv_B.PI_ctrl_1.Saturation1; pos_cmd_two = throttlecntrl_externenv_B.PI_ctrl_2.Saturation1; throttlePos_Command_Arbitration(pos_cmd_one, &Throt_Param, pos_cmd_two, &throttlecntrl_externenv_B.sf_Pos_Command_Arbitration);
Calls to the PI_Cntrl_Reusable function use a mixture of user-defined variables and default data structures. The build process defines data structures in throttlecntrl_externenv.h. The preceding code fragment also shows how the data structures map to user-defined variables.
such that the path contains no spaces (for example, EclipseProjects/throttlecntrl/externenv). For this tutorial and Verifying Generated Code on page 3-53, you use the Cygwin Debugger, which requires that your build folder be on your C drive and the folder path not include spaces. Note If you have not generated code for the model, or the zip file does not exist, complete the steps in Relocating Code to Another Development Environment on page 3-45 before continuing to the next step.
3-51
Simulink Tutorials
just created.
3 Delete the files ert_main.c and throttlecntrl_externenv.c. Then, add
page 3-46.
4 Use the Eclipse Integrated Development Environment (IDE) and Cygwin
Debugger to step through and evaluate the execution behavior of the generated C code. For instructions on installing the IDE, creating a new project, and configuring the debugger, see Appendix A, Installing and Using an IDE for the Integration and Testing Tutorials.
5 Close throttlecntrl_externenv.mdl.
Key Points
You can find and package all files you need to build an executable image in an alternative build environment by using the Simulink Coder pack-and-go utility. A main function performs actions to exercise the code for a system. Integration of system components requires matching data and function interfaces of generated code and existing system code. Depending on the system, you might need to consider input data, output data, and other data generated in the generated model.h file.
Learn More
Relocating Code to Another Development Environment in the Simulink Coder documentation Deployment Embedded IDEs and Embedded TargetsDesktop IDEs and Desktop Targets
3-52
Prerequisites
Access to installed versions of the Eclipse Integrated Development Environment (IDE) and the Cygwin Debugger. However, required integration tasks demonstrated in the tutorial are common to all integration environments. For information on how to install the Eclipse IDE and Cygwin Debugger, see Appendix A, Installing and Using an IDE for the Integration and Testing Tutorials Able to read C code. Familiarity with debugging tools and capabilities.
3-53
Simulink Tutorials
Required Files
rtwdemo_throttlecntrl_testcode.mdl rtwdemo_throttlecntrl_testharnessSIL.mdl Files in
matlabroot/toolbox/rtw/rtwdemos/EmbeddedCoderOverview/testcode_files, where matlabroot is your MATLAB installation folder
Software-in-the-loop Uses an S-function (SIL) testing wrapper to include the generated code in a Simulink model
3-54
Test Method
What the Method Does How SIL and PIL Simulations Work
Advantages
Disadvantages
Can use C debugger with the simulation Uses actual processor Can determine actual hardware constraints Allows testing of component within the full system Processor runs in real time Requires hardware Requires additional steps to set up test environment
Runs generated code on the target processor as part of the full system
You can also reuse data from an external environment, such as an interactive development environment (IDE) for a specific target, in the Simulink test environment. To do so, you must save the data in a format that MATLAB software can read.
3-55
Simulink Tutorials
Implementation > Device vendor to Generic and Hardware Implementation > Device type to 32-bit x86 compatible.
c Click OK to apply the changes. Close the dialog box. 2 Make sure that you can build an executable for throttlecntrl_testcode. 3 Configure the test harness model.
3-56
path. The test harness uses a Model block to access the model to verify with software-in-the-loop (SIL) testing.
b Right-click the throttlecntrl_testcode Model block and select Model
Reference Parameters.
c Set Model name to throttlecntrl_testcode. d Set Simulation mode to Software-in-the-loop (SIL) and click OK.
After you configure the Model block for SIL verification, the block includes a (SIL) tag, as the following figure shows:
3-57
Simulink Tutorials
e Update the test harness model diagram (Edit > Update Diagram). 4 Run the test harness. As the following plot shows, the results from running
3-58
3-59
Simulink Tutorials
Read simulated hardware input PI_cnrl_1 PI_ctrl_2 Pos_Command_Arbitration Write simulated hardware output
end while
The example_main.c uses two functions, plant and hardwareInputs. File Name
Plant.c
Function Signature
void Plant(void)
Comments Code generated from the plant section of the test harness. Simulates the throttle body response to throttle commands. Provides the pos_req signal and adds noise from the
Input_Signal_Scaling
HardwareInputs.c
void hardwareInputs(void)
subsystems into the plant feedback signal. A handwritten function, WriteDataForEval.c, logs data. When the test is complete, the function executes and writes test data to the file, ThrottleCntrl_ExternSimData.m. You can load this file into the MATLAB environment and compare the data to simulation data.
3-60
throttlecntrl_testcode.mdl.
2 Add the additional files required to build an executable. In the
Configuration Parameter dialog box, add the following paths for Code Generation > Custom Code > Include list of additional > Include directories:
"$matlabroot$\toolbox\rtw\rtwdemos\EmbeddedCoderOverview\" "$matlabroot$\toolbox\rtw\rtwdemos\EmbeddedCoderOverview\verification_files\"
3 Make sure the model configuration parameter Code Generation > SIL
such that the path contains no spaces (for example, EclipseProjects/throttlecntrl/testcode). For this tutorial, you use the Cygwin Debugger, which requires that your build folder be on your C drive and that the folder path not include spaces.
6 Unzip the throttlecntrl_testcode.zip file, in your working folder, into
page 3-46.
8 Run the control code in Eclipse to generate the eclipseData.m file. This
is the file that writeDataForEval.c generates. Consult Integrating and Testing Code with the Eclipse IDE on page A-5 or Eclipse IDE help.
9 Plot the results that you get from the Eclipse environment. Compare the
data from the Eclipse run with the data results from the test harness.
10 Close throttlecntrl_testcode.
3-61
Simulink Tutorials
Key Points
Methods for verifying code generated for an embedded system include running a MicrosoftWindows run-time executable, SIL testing, PIL testing, and on-target rapid prototyping. You can reuse test data by importing and exporting test vectors.
Learn More
SIL and PIL Simulation
3-62
Evaluating Code
Efficiency of generated code is based on two primary metrics: execution speed and memory usage. Often, faster execution requires more memory. Memory usage in ROM (read-only memory) and RAM (random access memory) presents compromises: Accessing data from RAM is faster than accessing data from ROM.
3-63
Simulink Tutorials
Systems store executables and data using ROM because RAM does not maintain data between power cycles. This section describes memory requirements divided into function and data components. Execution speed is not evaluated.
3-64
Data Type: All doubles Included Data: All data required for the build is in the project (including data defined as extern: pos_rqst, fbk_1, and fbk_2) Main Function: A modified version of example_main from Integrating Generated Code into External Environment on page 3-44 Function-Call Method: Reusable functions for the PI controllers
3-65
Simulink Tutorials
Memory Usage Usage Type Full Algorithms Utilities Function (bytes) 1764 1172 592 Data (bytes) 589 549 40
3-66
Included Data: All data required for the build is in the project (including data defined as extern: pos_rqst, fbk_1, and fbk_2) Main Function: A modified version of example_main from Integrating Generated Code into External Environment on page 3-44 Function-Call Method: Reusable functions for the PI controllers Memory Usage Usage Type Full Algorithms Utilities Function (bytes) 1392 800 592 Data (bytes) 348 308 40
Comparing the memory used by the algorithms in the first configuration to the current configuration, there is a large drop in the data memory, from 549 bytes to 308 bytes, or 56 percent. The function size also decreased from 1172 to 800 bytes, or 68 percent. Running the simulation with data type set to single does not reduce the accuracy of the control algorithm. Therefore, this configuration is an acceptable design decision.
Data Type: All singles Included Data: All data required for the build is in the project (including data defined as extern: pos_rqst, fbk_1, and fbk_2) Main Function: A modified version of example_main from Integrating Generated Code into External Environment on page 3-44 Function-Call Method: The function interface is void void. Global parameters pass the data.
3-67
Simulink Tutorials
The memory requirements for the third configuration are higher than the memory requirements for the second configuration. If the data type is doubled, the memory requirements are higher than the first configuration, as well. Memory Usage Usage Type Full Algorithms Utilities Function (bytes) 1540 948 592 Data (bytes) 388 348 40
3-68
A
Installing and Using an IDE for the Integration and Testing Tutorials
Installing the Eclipse IDE and Cygwin Debugger on page A-2 Integrating and Testing Code with the Eclipse IDE on page A-5
Installing and Using an IDE for the Integration and Testing Tutorials
download the Eclipse IDE for C/C++ Developers to your C: drive. You also need the Eclipse C/C++ Development Tools (CDT) that are compatible with the Eclipse IDE. You can install the CDT as part of the Eclipse C/C++ IDE packaged zip file or you can install it into an existing version of the Eclipse IDE. If You Install the CDT... As part of the Eclipse C/C++ IDE packaged zip file Into an existing version of the Eclipse IDE Then... Go to step 4 Go to step 2
A-2
Development Tools (CDT) that is compatible with your installed version of the Eclipse IDE.
3 Unzip the downloaded Eclipse CDT zip file. Copy the contents of the
c:\eclipse\eclipse.exe.
box opens.
3 Follow the installation procedure:
Select the option for installing over the Internet. Accept the default root folder c:\cygwin. Specify a local package folder. For example, specify c:\cygwin\packages. Specify how you want to connect to the Internet. Choose a download site.
4 In the dialog box for selecting packages, set the Devel category to Install
5 Add the folder c:\cygwin\bin to your system Path variable. For example, a Click Start > Settings > Control
A-3
Installing and Using an IDE for the Integration and Testing Tutorials
Note To use Cygwin, your build folder must be on your C drive. The folder path cannot include any spaces.
A-4
Introducing Eclipse
Eclipse (www.eclipse.org) is an integrated development environment for developing and debugging embedded software. Cygwin (www.cygwin.com) is an environment that is similar to the Linux environment, but runs on Windows and includes the GCC compiler and debugger. This section contains instructions for using the Eclipse IDE with Cygwin tools to build, run, test, and debug projects that include generated code, as described in Integrating Generated Code into External Environment on page 3-44 and Verifying Generated Code on page 3-53. There are many other software packages and tools that can work with code generation software to perform similar tasks. Installing the Eclipse IDE and Cygwin Debugger on page A-2 contains instructions for installing Eclipse and Cygwin. Before proceeding, be sure you have installed Eclipse and Cygwin, as described in that section. Note To use Eclipse IDE with embedded IDEs and target processors, see Working with Eclipse IDE under Embedded IDEs and Embedded TargetsDesktop IDEs and Desktop Targets. To use Cygwin, your build folder must be on your C drive. The folder path cannot include any spaces.
A-5
Installing and Using an IDE for the Integration and Testing Tutorials
example, C:\EclipseProjects\throttlecntrl\externenv).
c In the Project type selection box, select and expand Makefile project. d Click the Empty Project node. e Under Other Toolchains, select Cygwin GCC . f
A-6
entry appears under C/C++ Application. The Main tab of the configuration pane appears on the right side of the dialog box with the following parameter settings: Parameter Name C/C++ Application Project Build configuration Enable auto build Disable auto build Use workspace settings
3 Click Close.
Setting
throttlecntrl_externenv Default Default\throttlecntrl_externenv.exe throttlecntrl_externenv Default
A-7
Installing and Using an IDE for the Integration and Testing Tutorials
process. To run the debugger, Eclipse remaps the drive or locates your project files. Once Eclipse locates the first file, it automatically finds the remaining files. In the Eclipse window, click Locate File. The Open dialog box opens. For information on using the Edit Source Lookup Path button, see Setting the Cygwin Path on page A-8.
4 Navigate to the example_main.c file and click Open. Your program opens
A-8
Action Step into Step over Step out Resume Toggle break point
A-9