Main Content

Reuse Custom Code in Stateflow Charts

You can integrate custom code written in C or C++ with Stateflow® charts in Simulink® models. By sharing data and functions between your custom code and your Stateflow chart, you can augment the capabilities of Stateflow and take advantage of your preexisting code.

Integrate Custom C Code in Stateflow Charts

This example shows how to use custom C code to define constants, variables, and functions that you can access in all charts in your model. For more information about integrating custom C++ code in your charts, see Access Custom C++ Code in Stateflow Charts and C++ Code Generation and Integration in Stateflow.

In this example, a Stateflow chart calls a custom code function named custom_function. This function reads the chart input signal and the local data threshold, compares their values, and returns one of three custom global constants named HIGH, MEDIUM, and LOW. The chart uses the return value to determine whether to transition to a new state after it increments or decrements the value of a custom variable named custom_var.

To see the custom code that this chart accesses, open the Model Configuration Parameters dialog box and select the Simulation Target pane.

  • The Header file parameter contains an #include statement that specifies the header file sf_custom_code_constants_vars_fcns_hdr.h.

  • The Source file parameter specifies the source file sf_custom_code_constants_vars_fcns_src.c.

Both of these files are located in the same folder that contains the model. To access custom code files that reside in a different folder, use relative path names. For more information, see Specify Relative Paths to Your Custom Code.

The header file contains the definitions of three global constants and the declarations for the global variable custom_var and the function custom_function.

#ifndef SF_CUSTOM_CODE_CONSTANTS_VARS_FCNS_HDR_H
#define SF_CUSTOM_CODE_CONSTANTS_VARS_FCNS_HDR_H
/* Include guard makes ensures that the header file is included 
   only once in the generated code. */

/* Constant definitions shared by the Stateflow chart and custom code*/

#define LOW -1
#define MEDIUM 0
#define HIGH 1

/* extern declaration of the global variable defined in the source file 
   sf_custom_code_constants_vars_fcns_src.c */

extern int custom_var;

/* extern declaration of the custom function defined in the source file 
   sf_custom_code_constants_vars_fcns_src.c */

extern int custom_function(double var1, int var2); 

#endif /* SF_CUSTOM_CODE_CONSTANTS_VARS_FCNS_HDR_H */

The source file sets the initial value of custom_var to zero and defines the function custom_function.

#include "sf_custom_code_constants_vars_fcns_hdr.h"

/* Definition of the global variable */

int custom_var = 0;

/* Definition of the custom function */

int custom_function(double var1, int var2)
{
    if(var1 > var2 + custom_var) {
        return(HIGH);
    }else if(var1 < var2 - custom_var) {
        return(LOW);
    }
    return(MEDIUM);
}

When you simulate the model, Stateflow compiles the source file and the chart into a single S-function MEX file. Because the custom definitions appear at the top of the generated machine header file sf_custom_code_constants_vars_fcns_sfun.h, every chart in the model can access the custom code during simulation.

Specify Custom Code for Your Model

Specify Custom Code for Simulation

To configure your model to access custom code during simulation, use the Simulation Target pane of the Model Configuration Parameters dialog box.

  1. Open the Model Configuration Parameters dialog box.

  2. Select the Simulation Target pane.

  3. Specify your custom code in the Insert custom C code in generated and Additional build information subpanes.

    • Source file — Enter the code to include at the top of a generated source code file. This code appears at the top of the generated model.c source file, outside of any function. For example, use this parameter to include extern int declarations for global variables. For more information, see Source file (Simulink).

    • Header file — Enter the code to include at the top of the generated model.h header file, which declares custom functions and data in the generated code. The code appears at the top of all generated source code files and is visible to all generated code. For example, use this parameter to enter #define and #include statements. When you include a custom header file, you must enclose the file name in double quotes. For more information, see Header file (Simulink).

      Note

      Because the code you specify in the Header file parameter appears in multiple source files that link into a single binary, you cannot include a global variable definition such as int x or a function with a signature of void myfun(void). These statements cause linking errors because their symbol definitions appear multiple times in the source files of the generated code. You can, however, include extern declarations of variables or functions, such as extern int x or extern void myfun(void).

    • Initialize function — Enter code that executes once at the start of simulation. Use this code to invoke functions that allocate memory or initialize your custom code. For more information, see Initialize function (Simulink).

    • Terminate function — Enter code that executes at the end of simulation. Use this code to invoke functions that free memory allocated by the custom code or perform other cleanup tasks. For more information, see Terminate function (Simulink).

    • Include directories — Enter a space-separated list of the folder paths that contain custom header files that you include either directly in the Header file parameter or indirectly in the compiled target. For more information, see Include directories (Simulink).

    • Source files — Enter a list of source files to compile and link into the target. You can separate source files with a comma, space, or new line. For more information, see Source files (Simulink).

    • Libraries — Enter a space-separated list of static libraries that contain custom object code to link into the target. For more information, see Libraries (Simulink).

    • Defines — Enter a space-separated list of preprocessor macro definitions to add to the generated code. For more information, see Defines (Simulink).

  4. If your model contains library charts, configure the custom code settings for each library model that contributes a chart to your model. For more information, see Configure Custom Code in Library Models.

For information on setting simulation options by using the command-line API, see Set Simulation Parameters Programmatically.

Specify Custom Code for Code Generation

To configure your model to access custom code for code generation, use the Code Generation > Custom Code pane of the Model Configuration Parameters dialog box. When generating code, your model can use the same custom code settings that it uses for simulation or use unique custom code settings.

  • To use the same custom code settings used for simulation, select Use the same custom code settings as Simulation Target. Specify the custom code settings in the Simulation Custom Code pane as described in Specify Custom Code for Simulation.

  • To use unique custom code settings, clear Use the same custom code settings as Simulation Target. Specify custom code settings for code generation in the Insert custom C code in generated and Additional build information subpanes. For descriptions of the parameters in these subpanes, see Specify Custom Code for Simulation.

For more information, see Use the same custom code settings as Simulation Target (Simulink Coder) and Integrate External Code by Using Model Configuration Parameters (Simulink Coder).

The Code Generation Custom Code pane of the Model Configuration Parameters dialog box, showing the same custom code settings specified in the Simulation Target pane.

Call Custom Code Functions in States and Transitions

You can call custom code functions from the actions of any state or transition or from other functions.

To call a custom code function, use the signature specified by the function declaration in your header file. Include an actual argument value for each formal argument in the function signature:

return_val = function_name(arg1,arg2,...)

Note

Do not share fixed-point data between your custom code and your Stateflow chart.

Specify Relative Paths to Your Custom Code

When you update your model or start the simulation, the model searches for the custom code files in these folders:

  • The current folder

  • The model folder (if this folder is different from the current folder)

  • The custom list of folders that you specify

  • All the folders on the MATLAB® search path, excluding the toolbox folders

You can specify the location of your custom code by using paths relative to one of these folders. For instance, suppose that, in the previous example, you store the source and header files for your custom code in the subfolders CustomCode/SourceFiles and CustomCode/HeaderFiles of the model folder. To access these files, enter the relative paths of the subfolders in the Include directories subpane.

The Simulation Target pane of the Model Configuration Parameters dialog box, showing the relative paths to two subfolders.

Alternatively, you can use relative path names to specify the header and source files individually:

  • In the Header file subpane, enter:

    #include "./CustomCode/HeaderFiles/sf_custom_code_constants_vars_fcns_hdr.h"
  • In the Source file subpane, enter:

    ./CustomCode/HeaderFiles/sf_custom_code_constants_vars_fcns_src.c

Guidelines for Relative Path Syntax

When you construct relative paths for custom code, follow these syntax guidelines:

  • Use a single period (.) to indicate the starting point for the relative path.

  • Use forward slashes (/) or backward slashes (\) as file separators, regardless of the current platform you are using.

  • Enclose paths in double quotes ("...") if they contain nonstandard path characters such as spaces or hyphens (-).

  • Enclose expressions with dollar signs ($...$) to evaluate them in the MATLAB workspace. For example, suppose that CustomCodeFolder is a variable that you define in the MATLAB workspace as "module1". If you specify your custom code files using the path name .\work\source\$CustomCodeFolder$, then the model searches for the custom code files in the folder .\work\source\module1.

Related Topics