Generate Component Source Code for Export to External Code Base - MATLAB & Simulink (original) (raw)

If you have Embedded Coder® software, you can generate function source code from modeling components to use in an external code base. The generated code does not include supporting scheduling code (for example, a step function). Controlling logic outside of the Simulink® environment invokes the generated function code.

Modeling Options

You can generate function code to export for these modeling components:

To export code that the code generator produces for these modeling components, the modeling components must meet specific requirements.

Requirements

In addition, for export-function models, you cannot generate code for a rate-based model that includes multiple instances of an export-function model. For example, you cannot generate code for a test harness model that you use for scheduling reusable export-function models during simulation.

For export-function subsystems, the following additional requirements apply:

Export Functions That Use Absolute or Elapsed Time

If you want to export function code for a modeling component with blocks that use absolute or elapsed time, those blocks must be inside a function-call subsystem that:

To configure a function-call subsystem for periodic execution:

  1. In the function-call subsystem, right-click the Trigger block and choose Block Parameters from the context menu.
  2. Set parameter Sample time type toperiodic.
  3. Set Sample time to the same granularity specified (directly or by inheritance) in the function-call initiator.
  4. Click OK or Apply.

For more information, see Timer Representation and Computation.

Limitations for Export-Function Subsystems

Workflow

To generate code for an exported function, iterate through the tasks listed in this table.

Choose an Integration Approach

Multiple approaches are available for generating function code for export to an external development environment. The following table compares approaches. Choose the approach that aligns best with your integration requirements. For more information on how to create export-function models, see Export-Function Models Overview. For more information on generating code for function call subsystems, see Generate Component Source Code for Export to External Code Base.

Condition or Requirement Use More Information
Traceability between modeling elements and generated codeLocal inputs (Inport block) and outputs (Outport block) Function-call subsystem Generate C Function Code for Export-Function Model Generate C++ Function and Class Code for Export-Function Model Using Function-Call Subsystems Function-Call Subsystem
Control over generated function prototypeFormal input arguments (Argument Inport blocks) and output arguments (Argument Outport blocks)Local inputs (Inport block) and outputs (Outport block) Simulink Function block Configure Entry-Point Function Interfaces for Simulink Function and Function Caller Blocks Simulink Function Blocks and Code Generation Generate Code for Simulink Function and Function Caller Simulink Functions Simulink Function
Code responds to an initialization event Initialize Function block Generate C Function Code for Export-Function Model Generate C++ Function and Class Code for Export-Function Model Startup, Reset, and Shutdown Function Interfaces Using Initialize, Reinitialize, Reset, and Terminate Functions
Code responds to a reset event Reset Function block Generate C Function Code for Export-Function Model Generate C++ Function and Class Code for Export-Function Model Startup, Reset, and Shutdown Function Interfaces Using Initialize, Reinitialize, Reset, and Terminate Functions
Code includes entry-point functions beyond what the code generator produces by default (model_initialize,model_step, and_model__terminate) S-function S-Functions and Code Generation
Single-model execution framework to use as test harness and to export code generated for portions of a model Export-function subsystem Simulink Modeling Components Using Function-Call Subsystems Function-Call Subsystem

Generate C Function Code for Export-Function Model

This example shows how to generate function code for individual function-call subsystems in a model without generating scheduling code.

To generate function code for export:

  1. Create a model that contains the functions for export.
  2. Configure the code interface.
  3. Create a test harness model that schedules execution of the functions during simulation.
  4. Simulate the model that contains the functions by using the test harness model.
  5. Generate code for the model that contains the functions.

Create Model That Contains Functions for Export

The model with functions for export must satisfy architectural constraints at the model root level. At the root level, valid blocks are:

For this example, the code generator produces function code for Initialize Function, Terminate Function, and Function-Call Subsystem blocks. An Initialize Function block is executed on a model initialize event and a Terminate Function block is executed on a terminate event. For a Function-call Subsystem block, you connect the block input ports to root Inport blocks that assert function-call signals. The subsystem is executed based on the function-call signal that it receives.

For exporting functions, model ComponentDeploymentFcn contains two function-call subsystems (Integrator and Accumulator). Function-call subsystem Integrator represents an aperiodic integrator function. The function applies a forward integration method and a gain value of 1.25 to the value of state variable x each time the function executes. Function-call subsystem Accumulator represents a periodic function that increments the value of state variable x by 1 and applies a tunable gain value k. The function executes every second.

open_system('ComponentDeploymentFcn')

Configure Model Code Interface

Model ComponentDeploymentFcn is configured to use the service code interface that is defined in ComponentDeploymentCoderDictionary.sldd. The code generator uses the linked dictionary to establish default code mappings that you can view and change by using the Code Mappings Editor or code mappings programming interface.

For elements for which the default interface aligns with the requirements, you do not need to make changes. For this example, to meet code interface requirements, these adjustments were made:

To review the code mappings, open the Embedded Coder app. Then, select Code Interface > Component Interface. The Code Mappings editor appears at the bottom of the app display.

In the Code Mappings editor, you can change the interfaces for the sender, receiver, data transfer, and timer services. To change the sender, receiver, and data transfer service, click the corresponding tab and, in the service column, select an alternative service. To change the timer service, click the Functions tab, select the row for the integrator function, click the pencil icon, and in the dialog that appears, select an alternative interface. The default interfaces use the outside-execution data communication method. The alternative interfaces use during-execution and direct-access data communication. Consider changing the interfaces to view differences in the generated code. If you choose to change the interfaces, for each service called along the data path of a signal, set the interfaces such that they apply the same data communication method.

For more information about model code mappings for service interfaces, see C Service Interfaces and Code Mappings Editor — C.

Create Test Harness Model for Simulation

When you export functions, the generated code does not include a scheduler. Create a test harness model to handle scheduling during simulation. Do not use the test harness model to generate code that you deploy.

Model ComponentDeploymentFcnHarness is a test harness. The model provides function-call signals to other models in this example to schedule the model contents, including the model initialize and terminate events.

open_system('ComponentDeploymentFcnHarness')

For this model, in the Embedded Coder app, Output is set to Simulation Only. This setting allows you to switch focus between the test harness model and models from which you intend to generate code without opening a separate Simulink Editor window.

Simulate the Test Harness Model

Verify that the model containing the functions that you want to export is executed as you expect by simulating the test harness model. For example, simulate ComponentDeploymentFcnHarness.

sim('ComponentDeploymentFcnHarness')

Searching for referenced models in model 'ComponentDeploymentFcnHarness'.

Total of 1 models to build.

Searching for referenced models in model 'ComponentDeploymentFcn'.

Total of 1 models to build.

Starting build procedure for: ComponentDeploymentFcn

Successful completion of build procedure for: ComponentDeploymentFcn

Build Summary

Top model targets:

Model Build Reason Status Build Duration

ComponentDeploymentFcn Information cache folder or artifacts were missing. Code generated and compiled. 0h 0m 11.357s

1 of 1 models built (0 models already up to date) Build duration: 0h 0m 11.979s

Preparing to start SIL simulation ...

Building with 'gcc'. MEX completed successfully. ### Writing source file rte_timer.c ### Writing header file rte_private_timer.h ### Writing source file rte_data_transfer.c

Updating code generation report with SIL files ...

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Starting SIL simulation for component: ComponentDeploymentFcn

Application stopped

Stopping SIL simulation for component: ComponentDeploymentFcn

Generate Function Code

In the Embedded Coder app, switch focus to component model by double clicking ComponentDeploymentFcn. Then, generate code for the functions that you want to export.

slbuild('ComponentDeploymentFcn')

Searching for referenced models in model 'ComponentDeploymentFcn'.

Total of 1 models to build.

Starting build procedure for: ComponentDeploymentFcn

Generated code for 'ComponentDeploymentFcn' is up to date because no structural, parameter or code replacement library changes were found.

Successful completion of code generation for: ComponentDeploymentFcn

Build Summary

0 of 1 models built (1 models already up to date) Build duration: 0h 0m 3.7638s

Review Generated Code

Review the generated code. The code generator creates the folder ComponentDeploymentFcn_ert_rtw in the current working folder and places source code files in that folder. The generated code is in two primary files: header file ComponentDeploymentFcn.h and source code file ComponentDeploymentFcn.c. ComponentDeploymentFcn.c calls the initialize function, exported functions Integrator and Accumulator, and terminate function. Model data and entry-point functions are accessible to a caller by including the header file.

The code generator also produces rtwtypes.h and a services header file, which by default the coder generator names services.h. Header file rtwtypes.h defines data types, structures, and macros that the generated code requires. Header file services.h is an interface header file that resides in subfolder services.

To inspect the generated code, use the generated Code Interface Report or, in the Embedded Coder app, use the Code view. The report is helpful for verifying that the generated interface code aligns with the target platform requirements. For more information, see Analyze Generated Service Code Interface Report.

Write Interface Code

Open and review the Code Interface Report. To write the interface code for your execution framework, use the information in that report.

  1. Include the generated header files by adding directives #include ComponentDeploymentFcn.h, #include rtwtypes.h, and #include services.h.
  2. Write input data to the generated code for model Inport blocks.
  3. Call the generated entry-point functions.
  4. Read data from the generated code for model Outport blocks.

Entry-point functions:

More About

Generate C++ Function and Class Code for Export-Function Model

This example shows how to generate function code for an export-function model that includes a function-call subsystem. The code generator produces function and class code that does not include scheduling code.

To generate function code for export:

  1. Create a model that contains the functions for export.
  2. Create a test harness model that schedules execution of the functions during simulation.
  3. Simulate the model that contains the functions by using the test harness model.
  4. Generate code for the model that contains the functions.

Create Model That Contains Functions and C++ Class Interface for Export

The model with functions for export with a C++ model class interface must satisfy architectural constraints at the model root level. For C++ class generation, blocks that are valid at the root level are:

Note: Export Function-Call Subsystem with C++ class interface does not support Simulink Function blocks.

The code generator produces function code for the Function-Call Subsystem block. For a Function-call Subsystem block, you connect the block input ports to root Inport blocks that assert function-call signals. The subsystem is executed based on the function-call signal that it receives.

Model CppClassFunctions contains function-call subsystems f1, f2, and f3 for exporting functions.

open_system('CppClassFunctions')

Create Test Harness Model for Simulation

When you export functions, the generated code does not include a scheduler. Create a test harness model to handle scheduling during simulation. Do not use the test harness model to generate code that you deploy.

Model CppClassFunctionsHarness is a test harness. The model provides function-call signals to other models in this example to schedule the model contents.

open_system('CppClassFunctionsHarness')

Simulate the Test Harness Model

Verify that the model containing the functions that you want to export is executed as you expect by simulating the test harness model. For example, simulate CppClassFunctionsHarness.

sim('CppClassFunctionsHarness')

Generate Function Code and Report

Generate code and a code generation report for the functions that you want to export. For example, generate code for CppClassFunctions.

slbuild('CppClassFunctions')

Searching for referenced models in model 'CppClassFunctions'.

Total of 1 models to build.

Starting build procedure for: CppClassFunctions

Successful completion of build procedure for: CppClassFunctions

Build Summary

Top model targets:

Model Build Reason Status Build Duration

CppClassFunctions Information cache folder or artifacts were missing. Code generated and compiled. 0h 0m 16.894s

1 of 1 models built (0 models already up to date) Build duration: 0h 0m 18.193s

Review Generated Code

From the code generation report, review the generated code.

Write Interface Code

Open and review the Code Interface Report. To write the interface code for your execution framework, use the information in that report.

  1. Include the generated header files by adding directives #include CppClassFunctions.h and #include rtwtypes.h.
  2. Write input data to the generated code for model Inport blocks.
  3. Call the generated entry-point functions.
  4. Read data from the generated code for model Outport blocks.

Input ports:

Entry-point functions:

Output ports:

Close Example Models

bdclose('CppClassFunctionsHarness') bdclose('CppClassFunctions')

More About

Generate Code for Export-Function Subsystems

To generate code for an export-function subsystem:

  1. Verify that the subsystem for which you are generating code satisfies exporting requirements.
  2. In the Configuration Parameters dialog box:
    1. Set the parameter System target file to an ERT-based system target file, such asert.tlc.
    2. If you want a SIL block with the generated code, for verification purposes, set model configuration parameter Create block to SIL.
    3. Click OK orApply.
  3. Right-click the subsystem block and select from the context menu.
    The operation creates and builds a new model,_`subsystem`_.slx, that contains the content of the original subsystem and creates aScratchModel that contains a Model block. This block references the newly created_`subsystem`_.slx model.
    The code generator produces code and places it in the working folder.
    If you set Create block toSIL in step 2b, Simulink opens a new window that contains an S-function block that represents the generated code. This block has the same size, shape, and connectors as the original subsystem.

Code generation and optional block creation are now complete. You can test and use the code and optional block as you do for generated ERT code and S-function block. For optional workflow tasks, see Specify a Custom Initialize Function Name and Specify a Custom Description.

Specify a Custom Initialize Function Name

You can specify a custom name for the initialize function of your exported function as an argument to the slbuild command. The command takes the following form:

blockHandle = slbuild('subsystem', 'Mode', 'ExportFunctionCalls',.. 'ExportFunctionInitializeFunctionName', 'fcnname')

_`fcnname`_ specifies the function name. For example, if you specify the name 'myinitfcn', the build process emits code similar to:

/* Model initialize function */ void myinitfcn(void){ ... }

Specify a Custom Description

You can enter a custom description for an exported function by using the Block Properties dialog box of an Inport block.

  1. Right-click the Inport block that drives the control port of the subsystem for which you are exporting code.
  2. Select Properties.
  3. In the General tab, in theDescription field, enter your descriptive text.

During function export, the text you enter is emitted to the generated code in the header for the Inport block. For example, if you open a model and enter a description in the Block Properties dialog box for a port f1, the code generator produces code that is similar to:

/*

Optimize Code Generated for Export-Function Subsystems

To optimize the code generated for an export-function subsystem, specify a separate storage class for each input signal and output signal that crosses the boundary of the subsystem.

For each function-call subsystem that you are exporting:

  1. Right-click the subsystem.
  2. From the context menu, choose Block Parameters (Subsystem).
  3. Select the Code Generation tab.
  4. Set Function packaging toAuto.
  5. Click OK or Apply.

See Also

Topics