Main Content

Use C API to Access Model Signals and States

This example helps you get started writing application code to interact with model signals and states. To get started writing application code to interact with model parameters, see Use C API to Access Model Parameters.

The C API provides you with the flexibility of writing your own application code to interact with model signals, states, root-level inputs/outputs, and parameters. Your target-based application code is compiled with the Simulink® Coder™ generated code into an executable. The target-based application code accesses the C API structure arrays in model_capi.c (or .cpp). You might have host-based code that interacts with your target-based application code. Or, you might have other target-based code that interacts with your target-based application code. The files rtw_modelmap.h and rtw_capi.h, located in matlabroot/rtw/c/src (open), provide macros for accessing the structures in these arrays and their members.

Here is an example application that logs global signals and states in a model to a text file. This code is intended as a starting point for accessing signal and state addresses. You can extend the code to perform signal logging and monitoring, state logging and monitoring, or both.

This example uses the following macro and function interfaces:

  • rtmGetDataMapInfo macro

    Accesses the model mapping information (MMI) substructure of the real-time model structure. In the following macro call, rtM is the pointer to the real-time model structure in model.c (or .cpp):

    rtwCAPI_ModelMappingInfo* mmi = &(rtmGetDataMapInfo(rtM).mmi);
  • rtmGetTPtr macro

    Accesses the absolute time information for the base rate from the timing substructure of the real-time model structure. In the following macro call, rtM is the pointer to the real-time model structure in model.c (or .cpp):

    rtmGetTPtr(rtM)
  • Custom functions capi_StartLogging, capi_UpdateLogging, and capi_TerminateLogging, provided via the files CAPIModel_datalog.h and CAPIModel_datalog.c. These files are located in matlabroot/toolbox/rtw/rtwdemos (open).

    • capi_StartLogging initializes signal and state logging.

    • capi_UpdateLogging logs a signal and state value at each time step.

    • capi_TerminateLogging terminates signal and state logging and writes the logged values to a text file.

    You can integrate these custom functions into generated code for a model by using these methods:

    • Custom Code of the Model Configuration Parameters dialog box.

    • Custom Code library blocks

    • TLC custom code functions

    This tutorial uses the Custom Code pane of the Model Configuration Parameters dialog box and the System Outputs block from the Custom Code library to insert calls to the custom functions into model.c (or .cpp), as follows:

    • capi_StartLogging is called in the model_initialize function.

    • capi_UpdateLogging is called in the model_step function.

    • capi_TerminateLogging is called in the model_terminate function.

The following excerpts of generated code from model.c (rearranged to reflect their order of execution) show how the function interfaces are used.

void CAPIModel_initialize(void)
{
...
  /* user code (Initialize function Body) */

  /* C API Custom Logging Function: Start Signal and State logging via C API.
   * capi_StartLogging: Function prototype in CAPIModel_datalog.h
   */
  {
    rtwCAPI_ModelMappingInfo *MMI = &(rtmGetDataMapInfo(CAPIModel_M).mmi);
    printf("** Started state/signal logging via C API **\n");
    capi_StartLogging(MMI, MAX_DATA_POINTS);
  }
...
}
...
/* Model step function */
void CAPIModel_step(void)
{
...
  /* user code (Output function Trailer) */

  /* System '<Root>' */

  /* C API Custom Logging Function: Update Signal and State logging buffers.
   * capi_UpdateLogging: Function prototype in CAPIModel_datalog.h
   */
  {
    rtwCAPI_ModelMappingInfo *MMI = &(rtmGetDataMapInfo(CAPIModel_M).mmi);
    capi_UpdateLogging(MMI, rtmGetTPtr(CAPIModel_M));
  }
...
}
...
/* Model terminate function */
void CAPIModel_terminate(void)
{
  /* user code (Terminate function Body) */

  /* C API Custom Logging Function: Dump Signal and State buffers into a text file.
   * capi_TerminateLogging: Function prototype in CAPIModel_datalog.h
   */
  {
    capi_TerminateLogging("CAPIModel_ModelLog.txt");
    printf("** Finished state/signal logging. Created CAPIModel_ModelLog.txt **\n");
  }
}

The following procedure illustrates how you can use the C API macro and function interfaces to log global signals and states in a model to a text file.

  1. Open the model CAPIModel.

    openExample("CAPIModel")

  2. Save the top model CAPIModel and the referenced model CAPIModelRef to the same writable work folder.

  3. Open the Configuration Parameters dialog box.

  4. If you are licensed for Embedded Coder® software and you want to use the ert.tlc system target file instead of the default grt.tlc, change the setting of model configuration parameter System target file. Make sure that you also select ert.tlc for the referenced model CAPIModelRef.

  5. For the top model, confirm these model configuration parameter settings:

    1. Select parameters Generate C API for signals, Generate C API for states, and Generate C API for parameters.

    2. If you are using the ert.tlc system target file, select Support complex numbers

    3. Select MAT-file logging.

    4. Click Apply.

    5. Update configuration parameter settings in the referenced model, CAPIModelRef, to match changes you made in the top model.

  6. Use the Custom Code pane to embed your custom application code in the generated code. Select the Custom Code pane. On the Code information tab, click Include directories. The Include directories input field is displayed.

  7. In the Include directories field, type matlabroot/toolbox/rtw/rtwdemos, where matlabroot represents the root of your MATLAB® installation folder. (If you are specifying a Windows® path that contains a space, place the text inside double quotes.)

  8. On the same tab, click Source files, and type CAPIModel_datalog.c.

  9. On the Additional source code tab, click Additional code, and type or copy and paste the following include statement:

    #include "CAPIModel_datalog.h"
  10. On the same tab, in the Initialize code field, type or copy and paste the following application code:

      /* C API Custom Logging Function: Start Signal and State logging via C API.
       * capi_StartLogging: Function prototype in CAPIModel_datalog.h
       */
      {
        rtwCAPI_ModelMappingInfo *MMI = &(rtmGetDataMapInfo(CAPIModel_M).mmi);
        printf("** Started state/signal logging via C API **\n");
        capi_StartLogging(MMI, MAX_DATA_POINTS);
      }

    Note

    If you renamed the top model CAPIModel, update the name CAPIModel_M in the application code to reflect the new model name.

  11. On the same tab, in the Terminate code field, type or copy and paste the following application code:

      /* C API Custom Logging Function: Dump Signal and State buffers into a text file.
       * capi_TerminateLogging: Function prototype in CAPIModel_datalog.h
       */
      {
        capi_TerminateLogging("CAPIModel_ModelLog.txt");
        printf("** Finished state/signal logging. Created CAPIModel_ModelLog.txt **\n");
      }

    Click Apply.

  12. In the MATLAB Command Window, enter custcode to open the Simulink Coder Custom Code library. At the top level of the CAPIModel model, add a System Outputs block.

  13. Double-click the System Outputs block to open the System Outputs Function Custom Code dialog box. In the System Outputs Function Exit Code field, type or copy and paste the following application code:

      /* C API Custom Logging Function: Update Signal and State logging buffers.
       * capi_UpdateLogging: Function prototype in CAPIModel_datalog.h
       */
      {
        rtwCAPI_ModelMappingInfo *MMI = &(rtmGetDataMapInfo(CAPIModel_M).mmi);
        capi_UpdateLogging(MMI, rtmGetTPtr(CAPIModel_M));
      }

    If you renamed the top model CAPIModel, update two instances of the name CAPIModel_M in the application code to reflect the new model name.

    Click OK.

  14. Clear model configuration parameter Generate code only.

    Build the model and generate an executable program. For example, on a Windows system, the build generates the executable file CAPIModel.exe in your current working folder.

  15. In the MATLAB Command Window, enter the command !CAPIModel to run the executable file. During execution, signals and states are logged using the C API and then written to the text file CAPIModel_ModelLog.txt in your current working folder.

    >> !CAPIModel
    
    ** starting the model **
    ** Started state/signal logging via C API **
    ** Logging 2 signal(s) and 1 state(s). In this demo, 
       only scalar named signals/states are logged **
    ** Finished state/signal logging. Created CAPIModel_ModelLog.txt **
  16. Examine the text file in the MATLAB editor or other text editor. Here is an excerpt of the signal and state logging output.

    ******** Signal Log File ********
    
    Number of Signals Logged: 2
    Number of points (time steps) logged: 51
    
    Time           bot_sig1 (Referenced Model)             top_sig1
    0              70                                      4
    0.2            70                                      4
    0.4            70                                      4
    0.6            70                                      4
    0.8            70                                      4
    1              70                                      4
    1.2            70                                      4
    1.4            70                                      4
    1.6            70                                      4
    1.8            70                                      4
    2              70                                      4
    ...
    
    ******** State Log File ********
    
    Number of States Logged: 1
    Number of points (time steps) logged: 51
    
    Time           bot_state (Referenced Model)
    0              0
    0.2            70
    0.4            35
    0.6            52.5
    0.8            43.75
    1              48.13
    1.2            45.94
    1.4            47.03
    1.6            46.48
    1.8            46.76
    2              46.62
    ...

Related Topics