Documentation about MATLAB Coder and using converted code in CCS

0 downloads 0 Views 899KB Size Report
Nov 16, 2013 - For a list of supported compilers, see ... C:\Users\toshiba\AppData\Roaming\MathWorks\MATLAB\R2012b\mexopts.bat ... occurs while converting the code,MATLAB coder will return an error (Ex: single ~= double). If the coder ...
Documentation about MATLAB Coder and using converted code in CCS

Dated: 16 Nov 2013 Nabeel P M IIT Madras research Scholar

MATLAB (matrix laboratory) is a numerical computing environment and fourth-generation programming language from MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages, including C, C++, Java, and Fortran. Math Works has now released MATLABCoder. MATLAB version 2012a onwardsMATLAB coder enables design engineers to automatically generate readable, portable C and C++ code directly from their MATLAB algorithms. This option eliminates the need to manually translate MATLAB algorithm code into C and C++ code for prototyping, implementation and integrationinto the final product.Manually converting from MATLAB to C can take from days to weeks; also it may introduce design errors. Design engineers can use MATLAB to speed up development tasks, such as fixed-point design and prototyping, and then automatically generate C code with MATLAB Coder. This automation results in a faster, more efficient system-development workflow. Also the latest versions of MATLAB Coder provide additional options such as „Code replacement library‟, „Test Hardware‟, „Production Hardware‟ etc. These types of options will help us convert the MATLAB algorithms to C and C++ code which is optimised for our hardware. These configuration options and advanced optimizationoptions for fine-grain control of the generated code‟s functions, files, and data will improve code efficiency and facilitate integration with legacy code, data types, and calibration parameters used in production. The „Project management‟ tool of MATLAB Coder will help to specify entry points, input data properties, and other code-generation configuration options and also static ordynamic memory allocation for variable-size data.The generated C code can be used forstandalone execution,integration with other software,accelerating MATLAB algorithms, embedded implementation etc. This Documentation is about detailed explanations and step by step procedures that should be followed to convert an existing MATLAB code to C/C++ code that are optimised forparticular test hardware. (Devicevendor: Texas Instruments; Device Type: C600; and Code replacement library:TIC674x)

Using MATLAB coder Choosing a Compiler: Once the MATLAB Compiler andsupported C or C++ compilers areproperly installed, the user can create C/C++/ MEX-files. If there is only one C or C++ compiler available thenMATLAB Coder automaticallyconfigures itself for the appropriate compiler. The user can directly proceed to MATLAB Coder if he does not wish to change the compiler or does not need to modify the compiler option files. In case theMATLAB Coder returns any error regarding compiler while convertingMATLAB code, changethe default C or C++ compiler.It can be done any timeby using the „mex –setup‟ option. The following example shows the process of changing default compiler to the Lcc-win32 C 2.4.1

>> mex -setup Welcome to mex -setup. This utility will help you set up a default compiler. For a list of supported compilers, see http://www.mathworks.com/support/compilers/R2012b/win32.html Please choose your compiler for building MEX-files: Would you like mex to locate installed compilers [y]/n? n Select a compiler: [1] Intel C++ 12.0 (with Microsoft Software Development Kit (SDK) linker) [2] Intel C++ 12.0 (with Microsoft Visual C++ 2008 SP1 linker) [3] Intel C++ 12.0 (with Microsoft Visual C++ 2010 linker) [4] Intel C++ 11.1 (with Microsoft Visual C++ 2008 SP1 linker) [5] Lcc-win32 C 2.4.1 [0] None Compiler: 5 Your machine has an Lcc-win32 C compiler located at E:\MATLAB\sys\lcc. Do you want to use this compiler [y]/n? y Please verify your choices: Compiler: Lcc-win32 C 2.4.1 Location: E:\MATLAB\sys\lcc Are these correct [y]/n? y Trying to update options file: C:\Users\toshiba\AppData\Roaming\MathWorks\MATLAB\R2012b\mexopts.bat From template: Done . . .

E:\MATLAB\bin\win32\mexopts\lccopts.bat

Now the C/C++ compiler is ready. Keep the MATLAB code (s) which is to be converted in to C/C++. (In this documentation, the conversion procedure for MATLAB version R2012b and MATLAB Coder 2.3 is explained) Open Coder window using the following command >>Coder Or select „MATLAB Coder‟ from APPS MATLAB Coder.

The following „MATLAB coder project‟ window will open. In „New‟ tab give suitable Name for code conversion project and Location where to create the „coder‟ folder-„codegen‟. If an already existing coder project is to be used, choose the same from „Open‟ tab. Then click OK.

Now add the file (.m file) which is to be convertedto C/C++. Browse for the requiredMATLAB file by clicking „Add files‟ in „Overview‟ tab. The added file should be available in „MATLAB Work folder‟

Once the file(s) are added,define the type of each argument that is going to pass in to the function(s) used inMATLAB file. Here, the working conversion of a bandpass filter function named as bandpassfilter.m, which has one argument„in_Frame‟ - a double 2000 x 1 array is shown. If your array size is variable, then give „:Inf‟ instead of giving a fixed value (2000 here). So the size definition will be :Inf x 1 array. One can also have :Inf x :Inf as per the nature of the variables in the individual function. Add global variables in “Add global” menu. This will be used when more than one function is getting converted in the same project.

In case of more than one file in the conversion project, continue adding the files to the project. Specify global variables in “Add global” menu if any

NB:By default,MATLAB will consider a variable as ‘double’. So if youwant to specify thetype of any of the arguments ofthe converting function to other than double, make sure that no mismatch of the type will occur between different variables inside function. If type mismatch occurs while converting the code,MATLAB coder will return an error (Ex: single ~= double). If the coder returns any error regarding type mismatch while building the project, either declare that particular variable as the required type inside the actual MATLAB function. Or if the type of the variable is not important declare variables as double itself in your ‘Overview’ tab. After that, go to „Build‟ tab and specify the type of output file. In the example shown below,the MATLAB file is to be converted to C/C++ Static Library. The „Generate code only‟ option should be selected if it is not necessary to execute the file after generating the code. Now click on „More settings‟ to specify your project settings

Onselecting „More settings‟ option, the following „Project settings‟ tab will appear. Here, specify all the project requirements like Path, Speed, Memory, Code Appearance, Debugging, Custom Code, Hardware etc.

Paths:This is used to specify the details of working folder and Build folder. By default, working folder will be the sameas Project folder and Build folder will be a subfolder inside the project folder with name „codegen‟ Speed: This is used to specify some important options regarding the nature of the variables present in the converted code.

Saturate on integer overflow: - This parameter applies only to the built in integer type variables present in the MATLAB algorithm. Most C compilers wrap on overflow. So when this option is selected,saturation will happen on overflow to either minimum or maximum that the data type can represent. It is advisable to select this option Support only purely-integer numbers: -This option is to make sure that only integer type data is present in the generated code and that only integer operations will be performed. On selecting this option floating point numbers and floating point operations will not appear in the generated code. If the variables have floating point operations in algorithm don‟t select this option Support non-finite numbers: - With this option, generated code will support non finite numbers (like inf. NaN. -inf). If algorithm does not support non finite number then keep this option unchecked, so that the generated code will support only bounded finite numbers

Memory: If there are any specific conditions about the dynamic memory allocation inthe generated code,such as dynamic memory allocation threshold or the maximum usage of stack etc.,it can be set here. Else, it is advisable to keep these settings as default

Code Appearance: This is used to give options about appearance of the generated code, such as the type of H and C file(s), comments in the generated code, code style etc.

Generated file partitioning method: - If theMATLAB code or function to be converted consists of more than one function (nested functions), there are two options here. Either all the functions can be built in to a single file or a separate file can be generatedfor each MATLAB file. If „all functions in to a single file‟ is chosen, then the final generated code will have only one “.c” file and one“.h” file with main function name (other files like „rtwtypes.h‟ and „_types.h‟ will be there with all conversions). Since all the function will be there in a main “.c” file, linking between different functions will be very easy. The “.h” file will also have to be included, corresponding to the generated code in the main() function of C compiler If proceeding with „one file for each MATLAB file‟ option, the final generated code will have separate “.c” and “.h” files for each nested functions of actual MATLAB file/code. Now, the user will have to make sure that linking between different functions is done properly in C compiler before executing the generated code. Also include the “.h” files corresponding to each function in the generated code in the main() function of C compiler. NB: - For simplicity better go with ‘Generate all functions in to a single file’. If a step by step analysis of the generated code is required, then proceed with the other option. Include comments: - This option helps to include comments in the generated code. „MATLAB source code as comments‟ will give actual MATLAB source code corresponding

to each operation as comments in generated code. „MATLAB function help text‟ will give MATLAB help comments corresponding to basic MATLAB operations, which are being converted in generated code Code Style:  If the if-else statements are to be converted to Switch-case statement, use the option provided for that  In MATLAB algorithm, if the declarations of generated external functions include the “extern” keyword, then „Preserve extern keyword in function declarations‟ option should be selected  Level of parenthesization in the code can be specified in „Parentheses‟ drop down menu. By default “Normal (Optimize for readability)” will be selected. It is advisable to use this default option  Maximum identifier length for variable, typedef, and function names can be set in “Maximum identifier length”  It is advisable to keep identifier format as default settings only Debugging: This helps to give options about the code generation report

Custom Code: Custom Code is about customizing the generated code. If want to include additional Directories, Source files or Libraries in the generated code, browse for the same and mention its location so thatthose will also get included in the generated code. “Post-codegeneration command” can also be given here

If any additional code is to be included to appear at the top of the generated C/C++ files (Source file, Header file, Initialize function, and Terminate function), do the coding in the provided space. Source file, Header file, Initialize function and Terminate function can be selected from the drop down menu

Hardware:This is used to select the hardware to which the converted code is to be ported, and so the converted code will be optimized by MATLABfor the specified hardware. A set of standard commonly using Code replacement library, Test hardware and Production hardware are available in this window and these can be set the same as per hardware specifications. For example,

Device vendor: Texas Instruments Device Type: C600 Code replacement library: TIC674x

All Settings:This window will show review the settings and preferences opted for the particular code conversion project

After confirming the settings, close the „Project Settings‟ widow and build the project

Once the project is successfully built, it will give a report about the same and the converted code will be savedin the „codegen‟ folder of MATLAB work folder or the specified location

Sometimes project building may get failed. In most of the case it happens when the output argument is not assigned to any initial value. C/C++ compilers strictly require the declarationof variables that are to be used in the project. If the MATLAB code converter is not able to identify the type and assign its nature by its own, it will show an error. At that time, it is essential to initialize the variables with suitable value. Similarly,when two arrays are equated,MATLAB will auto adjust the size but not C/C++ compiler. Hence error due to size mismatch between two arrays will occurs. So make sure that size of left side array and right side are the same

„View Report‟ option is very useful in casethe project building fails. It will show which function and/or which variable has causedthe error. In that case the error messages can be read and necessary modifications can be done in the MATLAB code accordingly. In most of the case the error happens due to size mismatch between two arrays and/or ifthe return value from a function is not initialised with suitable value.

USING CONVERTED CODE IN CCS Here are some important points to consider while using the converted code in a C/C++ compiler. CCS v5 is the considered version for this example. So the syntax and setting that should follow in CCS to use MATLAB converted code is explained below  Copy all the „.c‟ and „.h‟ file in to your CCS work folder.  Rename all the „.c‟ files in to „.cpp‟ o If code conversion is done with “All functions in to a single file” option then there will be only one „.c‟ file and „three „.h‟ files  Include „(function_name).h‟ file in to main cpp file. „(function_name_types).h‟ and „rtwtypes.h‟ need not be included separately  If MATLAB function is using array of variable size (:Inf X n) or (:Inf X :Inf), then create an EMXARRAY in CCS. Otherwise, the converted function will not be able to read or write value in arrays declared in CCS  To link between the MATLAB array format and CCS array format,emx create wrapper “emxCreateWrapper” will be available in „(function_name).h‟ file. Create emx array before calling the function which use any CCS array or output of which is supposed to store in a CCS array

 After the use of emx Array destroy the same (not necessary), so that memory can be reused. Use “emxDestroyArray” from „(function_name).h‟ to destroy the array o Example code: //declare input and output functions. double INPUT[2000]; double OUTPUT[500][2];

//creating emx for them. emxArray_real_T *input=emxCreateWrapper_real_T(INPUT,2000,1); emxArray_real_T *output=emxCreateWrapper_real_T(INPUT,500,2);

//call function. function_name(input,other arguments,output);

//destroy unwanted emx array. emxDestroyArray_real_T(input);

Usually MATLAB to C/C++ converted code will take more time than the same code written in C/C+ platform. Especially when using standard MATLAB functions directly. It will cause time balancing problem in CCS project. To save more time the following tips can be used while programming and using code conversion in MATLAB itself. So hardware specific programming should be done in MATLAB if time is a critical factor for the real time project.  Use only necessary MATLAB functions  If sizes of the arrays are known, declare them with zeros initially. Also declare variables with some suitable initial value  Avoid unnecessary function callings o For example, while using a filter, get the filter coefficients separately and store them in to suitable variables in main MATLAB function. Use those variables while calling filter function. Thus filter coefficient calculation time can besaved  It is also noted that calling many function in a main MATLAB function, as well as using the converted main function directly in CCS, will take much more time than using the sub functions separately o Therefore, the program could be reworked in such a way that user can use each sub functions separately and combine them to get required main function in CCS

o After properly splitting the main MATLAB function, convert the MATLAB code in to C/C++ by adding all sub functions in a single project. Give the project name as main function name (not necessary).Use “All function in a single file” option while building, so that we will get „.c‟ and „.h‟ files with main function name. (here Walls_n_Dia.c) o After converting, use each of the functions and make a single function in CCS as done in MATLAB. Ex: Walls_n_Dia ( );

 If the size of Emx array is already known, then create them as global variable instead of doing inside the function, so that declaration happens only once and thus saving both time and memory  Destroy Emx array with dynamic size each time after its use to save memory

***