Main Content

Generate Structured Text Code for Reusable Subsystems

This example shows how to simulate and generate structured text code for an atomic reusable subsystem. Reusable subsystems enable you to model commonly used blocks as a subsystem and reuse the subsystems multiple times within a model. Use reusable subsystems in your model to :

  • Facilitate team-based development.

  • Optimize the time, to make model changes by making changes to one subsystem and copying the subsystem to all other locations in the model where the subsystem is used.

  • Reduce complexity of the generated code by generating a single shared function block.

To generate code for the reusable subsystems, mark the child subsystems as atomic by right-clicking the subsystem blocks, selecting Block Parameters (Subsystem), and then selecting Treat as atomic unit under the Main tab.

Model Description

The model consists of a top-level atomic subsystem called ReusableSubsystem. Under the top-level subsystem there are two identical atomic subsystems S1 and S2.

reusable_subsystems.png

Open the model:

load_system('plcdemo_reusable_subsystem');
open_system('plcdemo_reusable_subsystem/ReusableSubsystem');

Generate Code

To generate structured text code, do one of the following:

  • Open the PLC Coder app. Select the ReusableSubsystem block and click Generate PLC Code.

  • Use the plcgeneratecode function:

plcgeneratecode('plcdemo_reusable_subsystem/ReusableSubsystem');
### Generating PLC code for 'plcdemo_reusable_subsystem/ReusableSubsystem'.
### Using model settings from 'plcdemo_reusable_subsystem' for PLC code generation parameters.
### Begin code generation for IDE codesys23.
### Emit PLC code to file.
### Creating PLC code generation report plcdemo_reusable_subsystem_codegen_rpt.html.
### PLC code generation successful for 'plcdemo_reusable_subsystem/ReusableSubsystem'.
### Generated files:
plcsrc/plcdemo_reusable_subsystem.exp

Structure of Generated Code

The generated structured text code consists of a single shared function block S1 as a result of code reuse optimizations. The generated structured text code for the reusable subsystem consists of these components:

  • Subsystem instance variables: The subsystems S1 and S2 are declared as instances of S1. The code invokes these two instances separately by passing in different inputs to the function block.

  • Function calls: This part of the code contains calls to the subsystem instance variable declarations with the different inputs required for each instance of S1.

  • Reusable function block definition: This part of the code contains code for the components inside the S1 subsystem. This function block definition is called by the code in the function calls section.

This image shows the different components of the generated structured text code.

generated_code_structure.png

Close the Model

To close the model:

close_system('plcdemo_reusable_subsystem');