Generate Structured Text Code for Hierarchical Simulink Subsystems
This example shows how to generate structured text code for a hierarchical Simulink® subsystem. Use hierarchical subsystems when:
Your model is large and complex and requires multiple subsystems.
You need code modularity and reusability across different models or projects.
You need to share the model with other users or integrate the model with other systems.
Different users need to work on different subsystems within the model.
You want to keep the subsystem files separate from the main model file for better file management and version control.
Example Model
Open the example model
mdl = 'plcdemo_hierarchical_subsystem.slx';
open_system(mdl)
The model consists of a subsystem at the top level HierarchicalSubsystem
that accepts inputs from various input sources. The subsystem contains two other subsystems S1
and S2
that perform operations on the inputs at every time step.
Generate Code
To generate structured text code,
In the Apps tab, click PLC Coder.
In the PLC Coder tab, click Settings > PLC Code Generation Settings. Change the Target IDE to
3S CodeSys 2.3
. Click OK.Select the HierarchicalSubsystem block. In the PLC Tab, click Generate PLC Code.
Alternatively, to generate structured text code from the MATLAB command line, use the plcgeneratecode
function.
generatedFiles = plcgeneratecode('plcdemo_hierarchical_subsystem/HierarchicalSubsystem');
Inspect Code
The hierarchical subsystems S1 and S2 are generated as separate function blocks.
type("plcsrc\plcdemo_hierarchical_subsystem.exp")
FUNCTION_BLOCK S1 VAR_INPUT ssMethodType: SINT; U: LREAL; END_VAR VAR_OUTPUT Y: LREAL; END_VAR VAR UnitDelay_DSTATE: LREAL; END_VAR CASE ssMethodType OF SS_INITIALIZE: (* InitializeConditions for UnitDelay: '<S2>/Unit Delay' *) UnitDelay_DSTATE := 0.0; SS_OUTPUT: (* Gain: '<S2>/Gain' incorporates: * Sum: '<S2>/Sum' * UnitDelay: '<S2>/Unit Delay' *) Y := (U - UnitDelay_DSTATE) * 0.5; (* Update for UnitDelay: '<S2>/Unit Delay' *) UnitDelay_DSTATE := Y; END_CASE; END_FUNCTION_BLOCK FUNCTION_BLOCK S2 VAR_INPUT ssMethodType: SINT; U: LREAL; END_VAR VAR_OUTPUT Y: LREAL; END_VAR VAR UnitDelay_DSTATE: LREAL; END_VAR CASE ssMethodType OF SS_INITIALIZE: (* InitializeConditions for UnitDelay: '<S3>/Unit Delay' *) UnitDelay_DSTATE := 0.0; SS_OUTPUT: (* Gain: '<S3>/Gain' incorporates: * Sum: '<S3>/Sum' * UnitDelay: '<S3>/Unit Delay' *) Y := (U - UnitDelay_DSTATE) * 0.75; (* Update for UnitDelay: '<S3>/Unit Delay' *) UnitDelay_DSTATE := Y; END_CASE; END_FUNCTION_BLOCK