Run C Code In Simulink Model

Call C Code from a Simulink model
You can call external C code from a Simulink® model using a MATLAB Function block and the coder.ceval command.
This example shows how to call the simple C program from a MATLAB Function block.:

1-Create the source file doubleIt.c in your current working folder.

/* doubleIt, a simple program that returns double the input */

#include “doubleIt.h”

double doubleIt(double u)




2-Create the header file doubleIt.h in your current working folder.

double doubleIt(double u);

3-Create a new Simulink model.

4-Add a MATLAB Function block to the model and double-click the block to open the editor.

5-Enter code that calls the doubleIt program:

function y = callingDoubleIt(u)

y = 0.0;

y = coder.ceval(‘doubleIt’,u);

6-Connect a Constant block having a value of 3.5 to the input port of the MATLAB Function block.

7-Connect a Display block to the output port.


8-In the Configuration Parameters dialog box, open the Simulation Target pane.

9-In the Insert custom C code in generated section, select Header file from the list, and enter #include "doubleIt.h" in the Header file text box.

10-In the Include list of additional section, select Source files from the list, enter doubleIt.c in the Source files text box, and click OK.

11-Simulate the model.

The value 7 appears in the Display block.

you can generate code for targets using this method.

To use the same source and header files for code generation, click Use the same custom code settings as Simulation Target in the Code Generation > Custom Code pane.

Reference: https://www.mathworks.com/




Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>