Integrating C or MATLAB code into ACG SDK
Table of Contents
This note provides instructions for integrating C or MATLAB code into a control algorithm developed using the ACG SDK on Simulink or PLECS. This approach can be used to implement advanced algorithms that can be complex to develop with the graphical approach. It covers:
- C code on Simulink (S-Functions)
- MATLAB code on Simulink
- C code on PLECS
C code on Simulink (S-Functions)
The best way to include C code into a Simulink model is by using S-functions. With S-functions, users can basically create a custom Simulink block, whose behavior is defined by code (C, C++, Fortran or MATLAB). The block can then be used in both Simulation and Code Generation modes of ACG SDK.
Creating an S-function
Simulink provides an S-function Builder block that generates the necessary files and helps define the inputs, outputs and parameters of the S-function.
The inputs, outputs and parameters can be defined in the Data Properties tab:
Then, your C code can be written in the Outputs tab.
Finally, the following build options can be configured in the Build Info tab:
When finished, the Build button on the top right corner generates the necessary files. These include:
|name.cpp||Is the S-function files that define the function inputs, outputs and parameters and call the wrapper function.|
|name_wrapper.cpp||Is a function that contains the user-written code of the S-function. This file is the only file compiled by the imperix toolchain in code generation.|
|name.tlc||Is an interface defining how the code should be called by Simulink Coder.|
|name.mexw64||Is the compiled version of the S-function.|
Using the S-function
The S-Function Builder block also serves as a wrapper for the generated S-function, which means that it can be used inside a model as any other Simulink block. Alternatively, an S-function block can be used to integrate the generated files into a Simulink model.
MATLAB code on Simulink
As seen previously, S-functions can integrate MATLAB code, but for simple codes, Simulink provides a MATLAB function block that is even easier to use.
When double-clicking on a MATLAB function block, the editor opens and the output code of the function can be written directly.
C code on PLECS
PLECS provides a handy C-Script block that lets you write and compile custom C code to integrate it into your model. It works in both simulation and code generation modes.