Simulink PLC Coder User's Guide
Simulink PLC Coder User's Guide
User's Guide
R2020a
How to Contact MathWorks
Phone: 508-647-7000
Getting Started
1
Simulink PLC Coder Product Description . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
iii
Generated Code Structure for Triggered Subsystems . . . . . . . . . . . . . . . . 2-6
Prepare Chart for Simulink PLC Coder Ladder Diagram Code Generation
.......................................................... 3-6
Design PLC Application with Stateflow . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6
Create Test Harness for Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
Generate Simulink PLC Coder Ladder Diagram Code from Stateflow Chart
.......................................................... 3-9
Stateflow Chart and Ladder Logic Diagram . . . . . . . . . . . . . . . . . . . . . . . . 3-9
Generate Ladder Diagram from Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12
Generate Ladder Diagram Along with Test Bench . . . . . . . . . . . . . . . . . . 3-12
Import Ladder Diagram Code to CODESYS 3.5 IDE and Validate Diagram
......................................................... 3-14
Import Ladder Diagram XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14
Verify Ladder Diagram with Test Bench . . . . . . . . . . . . . . . . . . . . . . . . . 3-16
iv Contents
Generating Ladder Diagram Code from Simulink . . . . . . . . . . . . . . . . . . 3-34
v
Function Block Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15
IDE-Specific Considerations
9
Integrate Generated Code with Siemens IDE Project . . . . . . . . . . . . . . . . . 9-2
Integrate Generated Code with Siemens SIMATIC STEP 7 Projects . . . . . . 9-2
Integrate Generated Code with Siemens TIA Portal Projects . . . . . . . . . . . 9-2
vi Contents
Rockwell Automation RSLogix Requirements . . . . . . . . . . . . . . . . . . . . . . . 9-4
Add-On Instruction and Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Double-Precision Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Unsigned Integer Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Unsigned Fixed-Point Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Enumerated Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Reserved Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Rockwell Automation IDE selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5
Limitations
11
Simulink PLC Coder Structured Text Code Generation Limitations . . . . 11-2
General Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
Simulink PLC Coder Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
vii
Configuration Parameters for Simulink PLC Coder Models
12
PLC Coder: General . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2
PLC Coder: General Tab Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2
Target IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-3
Show Full Target List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-5
Target IDE Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-6
Code Output Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7
Generate Testbench for Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7
Include Testbench Diagnostic Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-8
Generate Functions Instead of Function Block . . . . . . . . . . . . . . . . . . . . 12-8
Allow Functions with Zero Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-9
Suppress Auto-Generated Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-9
Emit Data type Worksheet Tags for PCWorx . . . . . . . . . . . . . . . . . . . . . 12-10
Aggressively Inline Structured Text Function Calls . . . . . . . . . . . . . . . . 12-11
viii Contents
External Mode
13
External Mode Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2
Use the Simulation Data Inspector to Visualize and Monitor the Logging
Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-7
Set Up and Download Code to the Studio 5000 IDE . . . . . . . . . . . . . . . . 13-7
Configure RSLinx OPC Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-8
Use PLC External Mode Commands to Stream and Display Live Log Data
..................................................... 13-8
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-4
ix
Generating PLC Code for MATLAB Function Block
18
Configuring the rand function for PLC Code generation . . . . . . . . . . . . . 18-2
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-5
x Contents
Simulink PLC Coder Structured Text Code Generation For
Simulink Data Dictionary (SLDD)
21
Structured Text Code Generation Support for Simulink Data Dictionary
......................................................... 21-2
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-2
xi
1
Getting Started
Simulink PLC Coder generates hardware-independent IEC 61131-3 Structured Text and Ladder
Diagrams from Simulink models, Stateflow® charts, and MATLAB® functions. The Structured Text and
Ladder Diagrams are generated in PLCopen XML and other file formats supported by widely used
integrated development environments (IDEs) including 3S-Smart Software Solutions CODESYS,
Rockwell Automation® Studio 5000, Siemens® TIA Portal, and OMRON® Sysmac® Studio. As a result,
you can compile and deploy your application to numerous programmable logic controller (PLC) and
programmable automation controller (PAC) devices.
Simulink PLC Coder generates test benches that help you verify the Structured Text and Ladder
Diagrams using PLC and PAC IDEs and simulation tools. It also provides code generation reports with
static code metrics and bidirectional traceability between model and code. Support for industry
standards is available through IEC Certification Kit (for IEC 61508 and IEC 61511).
1-2
Prepare Model for Structured Text Generation
Tasking Mode
This step is only required if your Simulink model contains multi-rate signals. If your Simulink model
does not contain multi-rate signals, you may proceed to solver selection.
Simulink PLC Coder only generates code for single-tasking subsystems. For multi-rate subsystems,
you must first explicitly set the tasking mode to single-tasking before selecting a solver. In the model
configuration, on the Solver pane, clear the check box for Treat each discrete rate as a separate
task.
Solvers
Choose a solver for your Simulink PLC Coder model.
1-3
1 Getting Started
2 Configure the model to use the fixed-step discrete solver. Click the solver link in the lower-right
corner. The Solver information pane opens. In the pane, click the View solver settings button
to open the Solver pane of the model configuration parameters. Under the Solver selection, set
Type to Fixed-step and Solver to discrete (no continuous states).
If your model uses a continuous solver, has a subsystem, configure a fixed sample time for the
subsystem for which you generate code.
3 Save this model as plcdemo_simple_subsystem1.
4 Create a subsystem containing the components for which you want to generate Structured Text
code.
Optionally, rename In1 and Out1 to U and Y respectively. This operation results in a subsystem
like the following figure:
1-4
Prepare Model for Structured Text Generation
8 Click OK.
9 Simulate your model.
10 Save your model. In later procedures, you can use either this model, or the
plcdemo_simple_subsystem model that comes with your software.
1-5
1 Getting Started
• Set up your subsystem to generate Structured Text code. See “Check System Compatibility for
Structured Text Code Generation” on page 1-6.
• Generate Structured Text code for your IDE. See “Generate and Examine Structured Text Code”
on page 1-9.
1 In your model, navigate to the subsystem for which you want to generate code.
2 Right-click that Subsystem block and select PLC Code > Check Subsystem Compatibility.
The coder checks whether your model satisfies the Simulink PLC Coder criteria. When the
checking is complete, a View diagnostics hyperlink appears at the bottom of the model window.
Click this hyperlink to open the Diagnostic Viewer window.
If the subsystem is not atomic, right-click the Subsystem block and select PLC Code, which
prompts Enable “Treat as atomic unit” to generate code.
1-6
Prepare Model for Structured Text Generation
This command opens the block parameter dialog box. Select Treat as atomic unit.
1-7
1 Getting Started
You are now ready to generate Structured Text code for your IDE. See “Generate and Examine
Structured Text Code” on page 1-9.
1-8
Generate and Examine Structured Text Code
4 On the PLC Code Generation pane, select an option from the Target IDE list, for example, 3S
CoDeSys 2.3.
1-9
1 Getting Started
The default Target IDE list displays the full set of supported IDEs. To see a reduced subset of the
target IDEs supported by Simulink PLC Coder, disable the option Show full target list. To
customize this list, use the plccoderpref function.
5 Click OK.
6 Click Generate PLC Code.
This button:
• Generates Structured Text code (same as the PLC Code > Generate Code for Subsystem
option)
• Stores generated code in model_name.exp (for example,
plcdemo_simple_subsystem.exp)
When code generation is complete, a View diagnostics hyperlink appears at the bottom of the
model window. Click this hyperlink to open the Diagnostic Viewer window.
This window has links that you can click to open the associated files. For more information, see
“Files Generated with Simulink PLC Coder” on page 1-14.
plcdemo_simple_subsystem
2 Open the Configuration Parameters dialog box using the plcopenconfigset function:
plcopenconfigset('plcdemo_simple_subsystem/SimpleSubsystem')
1-10
Generate and Examine Structured Text Code
When using plcgeneratecode for code generation, all diagnostic messages are printed to the
MATLAB command window.
• Matrix data types: The coder converts matrix data types to single-dimensional vectors (column-
major) in the generated Structured Text.
• Generated code header: If your model has author names, creation dates, and model descriptions,
the generated code contains these items in the header comments. The header also lists
fundamental sample times for the model and the subsystem block for which you generate code.
• Code comments: You can choose to propagate block descriptions to comments in generated code.
See “Propagate Block Descriptions to Code Comments” on page 1-13.
The figure illustrates generated code for the CoDeSys Version 2.3 PLC IDE. Generated code for other
platforms, such as Rockwell Automation RSLogix™ 5000, is in XML or other format and looks
different.
1-11
1 Getting Started
If you are confident that the generated Structured Text is good, optionally change your workflow to
automatically generate and import code to the target IDE. For more information, see “Import
Structured Text Code Automatically” on page 1-17.
1-12
Propagate Block Descriptions to Code Comments
For specific IDEs, you can propagate the block descriptions into specific XML tags in the generated
code. The IDEs use the tags to create a readable description of the function blocks in the IDE.
• For Rockwell Automation RSLogix 5000 AOI/routine target IDEs, the coder propagates block
descriptions from the model into the L5X AdditionalHelpText XML tag. The IDE can then
import the tag as part of AOI and routine definition in the generated code.
• For CoDeSys 3.5 IDE, the coder propagates block descriptions from the model into the
documentation XML tag. When you import the generated code into the CoDeSys 3.5 IDE, the
IDE parses the content of this tag and provides readable descriptions of the function blocks in
your code.
a Right-click the block for which you want to write a description and select Properties.
b On the General tab, enter a block description.
2 Before code generation, specify that block descriptions must propagate to code comments.
a Right-click the subsystem for which you are generating code and select PLC Code >
Options.
b Select the option Include block description on page 12-13.
1-13
1 Getting Started
• Package.pkg — (If test bench is generated) Top-level package file for function blocks
library and test bench main program in XML format.
1-14
Files Generated with Simulink PLC Coder
1-15
1 Getting Started
To specify a different name for the generated files, set the Function name options parameter in the
Subsystem block:
1 Right-click the Subsystem block for which you want to generate code and select Subsystem
Parameters.
2 In the Main tab, select the Treat as atomic unit check box.
3 Click the Code Generation tab.
4 From the Function Packaging parameter list, select either Nonreusable function or
Reusable Function.
These options enable the Function name options and File name options parameters.
5 Select the option that you want to use for generating the file name.
1-16
Import Structured Text Code Automatically
For the Rockwell Automation RSLogix routine format, you must generate testbench code for
automatic import and verification.
• Siemens SIMATIC STEP 7 Version 5.4 only for the following versions:
Working with the default CoDeSys Version 2.3 IDE should require additional changes for only the
PHOENIX CONTACT (previously KW) Software MULTIPROG 5.0/5.50 and Phoenix Contact PC WORX
6.0 IDE. For information about automatically importing Structured Text code to these IDEs, see
“Import and Verify Structured Text to PHOENIX CONTACT (previously KW) Software MULTIPROG
5.0 and Phoenix Contact PC WORX 6.0 IDEs” on page 4-4.
Note While the automatic import process is in progress, do not use your mouse or keyboard. Doing
so might disrupt the process. When the process completes, you can resume normal operations.
You must have already installed your target PLC IDE in a default location, and it must use the
CoDeSys V2.3 IDE. If you installed the target PLC IDE in a nondefault location, open the
Configuration Parameters dialog box. In the PLC Coder node, set the Target IDE Path parameter to
the installation folder of your PLC IDE. See “Target IDE Path” on page 12-6.
1-17
1 Getting Started
The software:
If you want to generate, import, and run the Structured Text code, see “Import and Verify Structured
Text Code” on page 4-4.
The Simulink PLC Coder software supports only the following versions of target IDEs for automatic
import and verification:
For the Rockwell Automation RSLogix routine format, you must generate testbench code for
automatic import and verification.
• Siemens SIMATIC STEP 7 Version 5.4 (English and German)
Note Some antivirus softwares falsely identify the executables that implement the automatic import
feature as malware. This can be safely ignored. For more information, see “Issues with Anti-Virus
Software”.
The following target IDEs currently do not support automatic import. For these target IDEs, the
automatic import menu items (Generate and Import Code for Subsystem and Generate, Import,
and Verify Code for Subsystem) are disabled.
1-18
Import Structured Text Code Automatically
• Generic
• PLCopen
• Rockwell Automation Studio 5000 Logix Designer (both routine and AOI constructs)
When the Simulink PLC Coder software fails to finish automatically importing for the target IDE, it
reports an issue in a message dialog box. To remedy the issue, try the following actions:
• Check that the coder supports the target IDE version and language setting combination.
• Check that you have specified the target IDE path in the subsystem Configuration Parameters
dialog box.
• Close currently open projects in the target IDE, close the target IDE completely, and try again.
• Some target IDEs can have issues supporting the large data sets the coder test bench generates.
In these cases, try to shorten the simulation cycles to reduce the data set size, then try the
automatic import again.
• Other applications can interfere with automatic importing to a target IDE. Try to close other
unrelated applications on the system and try the automatic import again.
1-19
1 Getting Started
1-20
Using Simulink Test with Simulink PLC Coder
5 On the PLC Code Generation pane, select a target and enable the Generate testbench for
subsystemoption.
6 Click OK.
7 Right-click and select Generate code for the subsystem from the Test Harness Window. The
generated code contains multiple test-benches from the signal builder. You can run this code in
the PLC emulator to make sure it matches simulation.
Limitations
• If you use anything other than a signal builder block in the test harness, you must create a top-
level atomic subsystem in the test harness that contains both the subsystem under test and the
testing blocks (for example, say test sequence block) and generate code for this subsystem.
• Simulink PLC Coder does not yet support verify keyword in the test sequence block
• Simulink PLC Coder does support duration keyword in the test sequence block but it requires
the generate code to be run with the same sample rate as in the Simulink model
1-21
1 Getting Started
Name Description
MotionControllerExample.slx Simulink model containing an example Stateflow chart for
modeling motion instructions.
DriveLibrary.slx Simulink library with a Stateflow chart that is used for
modeling a real world drive (axis) with trajectories, delays,
and other parameters.
MotionTypesForSim.mat MAT-file containing the bus data types for the
AXIS_SERVO_DRIVE and MOTION_INSTRUCTION. The
MotioncontrollerExample.slx model loads the content
of the MAT-file into the workspace. If you are creating a new
model you must load this MAT-file for simulation and code
generation.
Trajectory.m MATLAB class file for implementing trapezoidal velocity
profile. This is used to simulate the behavior of the Motion
Axis Move (MAM) command.
MotionApiStubs.slx Supporting file for code generation.
MotionInstructionType.m MATLAB enumeration class file that represents the type of
motion API calls. For example, isMAM, isMSF. This file is
used only during simulation.
plc_keyword_hook.m Helper file to avoid name mangling and reserved keyword
limitations.
plcgeneratemotionapicode.p Function that transforms the chart in the model to make it
suitable for code generation.
Before you start, copy the files in the example to the current working folder.
1 Create a Simulink model with a Stateflow chart.
2 Load the bus data types from the MotionTypesForSim.mat file into the workspace by using the
load function.
3 Create data that represents the drive and motion instructions for the chart. For information on
adding data to Stateflow charts, see “Add Stateflow Data” (Stateflow)
4 Copy the drive(axis) model from the DriveLibrary.slx file into the Stateflow chart. The drive
model must be copied as an atomic subchart.
1-22
Simulation and Code Generation of Motion Instructions
The drive logic Stateflow chart models a real world drive with parameters such as trajectory and
delay. Any drive subchart has the following data:
5 Use the Subchart Mappings dialog to map the drive subchart data store memory data with the
local data of the appropriate names in the container chart. For more information, see “Map
Variables for Atomic Subcharts and Boxes” (Stateflow). The “Simulating and Generating
Structured Text Code for Rockwell Motion Instructions” example has the following mapping for
Drive1.
6 Use graphical functions to create motion API instructions. For example, for the Motion Servo
On (MSO) instruction:
1-23
1 Getting Started
The mapping between the inputs to the outputs is through "pass by reference".
7 Create the controller logic in another subchart and use the motion instructions created in the
previous step in the chart. Controller1 in the example has the following Stateflow chart.
1-24
Simulation and Code Generation of Motion Instructions
At the end of simulation, the logged signals are captured in the base workspace as a variable called
logsout. This can be imported into Simulation Data Inspector.
1-25
1 Getting Started
• MAM
• MAS
• MSF
• MSO
To use other Rockwell Automation RSLogix motion instructions in the model (For example, Motion
Axis Jog (MAJ)), you must perform the following steps:
1-26
Simulation and Code Generation of Motion Instructions
1 Because the MAJ instruction is similar to MAM instruction, create a bus for MAJ with elements
similar to that of MAM.
2 Update the MotionTypesForSim.mat file with the new definitions for MAJDATA and
AXIS_SERVO_DRIVE.
3 In the Stateflow chart, create a graphical function representing MAJ (similar to MAM). Assign the
appropriate inputs and outputs.
1-27
1 Getting Started
5 Remove the transition commands and copy the graphical function to the MotionApiStubs.slx.
1-28
Simulation and Code Generation of Motion Instructions
1-29
1 Getting Started
1-30
Simulation and Code Generation of Motion Instructions
• Update the Drive subchart to respond to MAJ by implementing required transitions etc
(similar to MAM as shown).
1-31
1 Getting Started
8 Create or update the controller logic as required. Create a new state and add MAJ instruction to
it (similar to the MAM )
1-32
Simulation and Code Generation of Motion Instructions
9 Perform simulation and generate code using the steps described earlier.
1-33
2
The example in this topic shows generated code for the CoDeSys Version 2.3 IDE. Generated code for
other IDE platforms looks different.
1 If you do not have the plcdemo_simple_subsystem.exp file open, open it in the MATLAB
editor. In the folder that contains the file, type:
edit plcdemo_simple_subsystem.exp
The following figure illustrates the mapping of the generated code to Structured Text
components for a simple Simulink subsystem. The Simulink subsystem corresponds to the
Structured Text function block, Subsystem.
Note The coder maps alias data types to the base data type in the generated code.
2 Inspect this code as you ordinarily do for PLC code. Check the generated code.
Note The Simulink model for plcdemo_simple_subsystem does not contain signal names at the
input or output of the SimpleSubsystem block. So the generated code has the port names U and Y
2-2
Generated Code Structure for Simple Simulink Subsystems
as the input and output variable names of the FUNCTION_BLOCK. However, even if your model does
contain signal names, coder only uses port names in the generated code.
2-3
2 Mapping Simulink Semantics to Structured Text
The example in this topic shows generated code for the CoDeSys Version 2.3 IDE. Generated code for
other IDE platforms looks different.
The Simulink PLC Coder software generates Structured Text code and places it in
current_folder/plcsrc/plcdemo_reusable_subsystem.exp.
4 If you do not have the plcdemo_reusable_subsystem.exp file open, open it in the MATLAB
editor.
The following figure illustrates the mapping of the generated code to Structured Text
components for a reusable Simulink subsystem. This graphic contains a copy of the hierarchical
subsystem, ReusableSubsystem. This subsystem contains two identical subsystems, S1 and S2.
This configuration enables code reuse between the two instances (look for the
ReusableSubsystem string in the code).
2-4
Generated Code Structure for Reusable Subsystems
5 Examine the generated Structured Text code. The code defines FUNCTION_BLOCK S1 once.
Look for two instance variables that correspond to the two instances declared inside the parent
FUNCTION_BLOCK ReusableSubsystem (i0_S1: S1 and i1_S1: S1). The code invokes these
two instances separately by passing in different inputs. The code invokes the outputs per the
Simulink execution semantics.
6 For IEC 61131-3 compatible targets, the non-step and the output ssMethodType do not use the
output variables of the FUNCTION_BLOCK. Therefore, the generated Structured Text code for
SS_INITIALIZE does not contain assignment statements for the outputs Y1 and Y2.
2-5
2 Mapping Simulink Semantics to Structured Text
The example in this topic shows generated code for the CoDeSys Version 2.3 PLC IDE. Generated
code for other IDE platforms looks different.
The Simulink PLC Coder software generates Structured Text code and places it in
current_folder/plcsrc/plcdemo_cruise_control.exp.
4 If you do not have the plcdemo_cruise_control.exp file open, open it in the MATLAB editor.
The following figure illustrates the mapping of the generated code to Structured Text
components for a triggered Simulink subsystem. The first part of the figure shows the Controller
subsystem and the triggered Stateflow chart that it contains. The second part of the figure shows
excerpts of the generated code. Notice the zero-crossing functions that implement the triggered
subsystem semantics.
2-6
Generated Code Structure for Triggered Subsystems
2-7
2 Mapping Simulink Semantics to Structured Text
2-8
Generated Code Structure for Stateflow Charts
You can map the states and transitions in the chart to the generated code. For instance, the transition
from the state Aborting to Aborted appears in the generated code as:
ControlModule_IN_Aborting:
rtb_out := sABORTING;
(* During 'Aborting': '<S1>:11' *)
(* Graphical Function 'is_active': '<S1>:73' *)
(* Transition: '<S1>:75' *)
IF NOT drive_state.Active THEN
(* Transition: '<S1>:31' *)
is_c2_ControlModule := ControlModule_IN_Aborted;
(* Entry 'Aborted': '<S1>:12' *)
rtb_out := sABORTED;
(* Graphical Function 'stop_drive': '<S1>:88' *)
(* Transition: '<S1>:90' *)
driveOut.Start := FALSE;
driveOut.Stop := TRUE;
driveOut.Reset := FALSE;
END_IF;
For more information on the inlining of functions such as start_drive, stop_drive, and
reset_drive in the generated code, see “Control Code Partitions for MATLAB Functions in
Stateflow Charts” on page 7-8.
2-9
2 Mapping Simulink Semantics to Structured Text
You can map states and transitions in the chart to the generated code. For instance, the transition
from state B to C appears as:
Temporal_IN_B:
(* During 'B': '<S1>:2' *)
temporalCounter_i1(timerAction := 2, maxTime := 4000);
IF temporalCounter_i1.done THEN
(* Transition: '<S1>:8' *)
is_c2_Temporal := Temporal_IN_C;
temporalCounter_i1(timerAction := 1, maxTime := 0);
ELSE
(* Outport: '<Root>/pulse' *)
pulse := 2.0;
END_IF;
FUNCTION_BLOCK PLC_CODER_TIMER
VAR_INPUT
timerAction: INT;
maxTime: DINT;
END_VAR
VAR_OUTPUT
done: BOOL;
END_VAR
VAR
plcTimer: TON;
plcTimerExpired: BOOL;
2-10
Generated Code Structure for Stateflow Charts
END_VAR
CASE timerAction OF
1:
(* RESET *)
plcTimer(IN:=FALSE, PT:=T#0ms);
plcTimerExpired := FALSE;
done := FALSE;
2:
(* AFTER *)
IF (NOT(plcTimerExpired)) THEN
plcTimer(IN:=TRUE, PT:=DINT_TO_TIME(maxTime));
END_IF;
plcTimerExpired := plcTimer.Q;
done := plcTimerExpired;
3:
(* BEFORE *)
IF (NOT(plcTimerExpired)) THEN
plcTimer(IN:=TRUE, PT:=DINT_TO_TIME(maxTime));
END_IF;
plcTimerExpired := plcTimer.Q;
done := NOT(plcTimerExpired);
END_CASE;
END_FUNCTION_BLOCK
2-11
2 Mapping Simulink Semantics to Structured Text
The example in this topic shows generated code for the CoDeSys Version 2.3 IDE. Generated code for
other IDE platforms looks different.
The Simulink PLC Coder software generates Structured Text code and places it in
current_folder/plcsrc/plcdemo_eml_tankcontrol.exp.
4 If you do not have the plcdemo_eml_tankcontrol.exp file open, open it in the MATLAB
editor.
The following figure illustrates the mapping of the generated code to Structured Text
components for a Simulink Subsystem block that contains a MATLAB Function block. The coder
tries to perform inline optimization on the generated code for MATLAB local functions. If the
coder determines that it is more efficient to leave the local function as is, it places the generated
code in a Structured Text construct called FUNCTION.
5 Examine the generated Structured Text code.
2-12
Generated Code Structure for MATLAB Function Block
2-13
2 Mapping Simulink Semantics to Structured Text
The example in this topic shows generated code for the CoDeSys Version 2.3 IDE. Generated code for
other IDE platforms looks different.
1 Open the plcdemo_multirate model. This model has two sample rates.
2 Open the PLC Coder app. Click the PLC Code tab.
3 Click Generate PLC Code.
The Simulink PLC Coder software generates Structured Text code and places it in
current_folder/plcsrc/plcdemo_multirate.exp.
4 If you do not have the plcdemo_multirate.exp file open, open it in the MATLAB editor and
examine the Structured Text code.
VAR_GLOBAL
plc_ts_counter1: DINT;
END_VAR
In this example, there are two rates, and the fast rate is twice as fast as the slow rate, so the time
step counter counts to 1, then resets:
The generated code for blocks running at slower rates executes conditionally based on the
corresponding time step counter values. In this example, the generated code for Gain1, Unit
Delay1, and Sum1 executes every other time step, when plc_ts_counter1 = 0, because those
blocks run at the slow rate. The generated code for Gain, Unit Delay, Sum, and Sum2 executes
every time step because those blocks run at the fast rate.
SS_STEP:
(* Outport: '<Root>/Y1' *)
Y1 := rtb_Gain;
IF plc_ts_counter1 = 0 THEN
2-14
Generated Code Structure for Multirate Models
* Sum: '<S1>/Sum1' *)
rtb_Gain1 := (U2 - UnitDelay1) * 0.5;
(* Outport: '<Root>/Y2' *)
Y2 := rtb_Gain1;
END_IF;
IF plc_ts_counter1 = 0 THEN
END_IF;
In general, for a subsystem with n different sample times, the generated code has n-1 time step
counter variables, corresponding to the n-1 slower rates. Code generated from parts of the model
running at the slower rates executes conditionally, based on the corresponding time step counter
values.
2-15
2 Mapping Simulink Semantics to Structured Text
For example, the following subsystem, Subsystem, contains two instances, Filt1 and Filt2, of the
same masked subsystem.
2-16
Generated Code Structure for Subsystem Mask Parameters
The two subsystems, Filt1, and Filt2, have different values assigned to their mask parameters. In
this example, Filt1_Order_Thau is a constant with a value of 5.
2-17
2 Mapping Simulink Semantics to Structured Text
Therefore, for the Filt1 subsystem, the Filt1_Order_Thau parameter has a value of 8, and for the
Filt2 subsystem, the Filt1_Order_Thau parameter has a value of 5.
The following generated code shows the Filt1 function block inputs. The rtp_Filt1_Order_Thau
input was generated for the Filt1_Order_Thau mask parameter.
FUNCTION_BLOCK Filt1
VAR_INPUT
ssMethodType: SINT;
InitV: LREAL;
InitF: BOOL;
Input: LREAL;
rtp_Filt1_Order_Thau: LREAL;
rtp_InitialValue: LREAL;
rtp_Filt1_Order_Enable: BOOL;
END_VAR
The following generated code is from the FUNCTION_BLOCK Subsystem. The function block assigns a
value of 8 to the rtp_Filt1_Order_Thau input for the i0_Filt1 instance, and assigns a value of 5
to the rtp_Filt1_Order_Thau input for the i1_Filt1 instance.
SS_INITIALIZE:
(* InitializeConditions for Atomic SubSystem: '<S1>/Filt1' *)
2-18
Generated Code Structure for Subsystem Mask Parameters
2-19
2 Mapping Simulink Semantics to Structured Text
For example, suppose that your model has a global array variable, ParArrayXLUT:
ParArrayXLUT=[0,2,6,10];
In the generated code, the PLC_INIT_PARAMETERS function contains the following code to initialize
ParArrayXLUT:
2-20
Considerations for Nonintrinsic Math Functions
For example, hyperbolic tan is not an intrinsic function. Simulink PLC Coder uses exp in the
generated code to represent tanh. More specifically, it uses (exp(2*x)-1)/(exp(2*x)+1). For large
values of x, this function overflows. The issue can be addressed by adding validation code or using
blocks before calling the tanh function to check that the range of the input is within acceptable
values. In MATLAB, tanh(x) for x>19 is 1.0000. So if x>19, return a value of 1.0000.
See Also
2-21
3
Note Ladder diagram generation from Stateflow charts will be removed in a future release. To
generate ladder diagrams, use Simulink models instead. To create Simulink models compatible with
ladder logic generation, do one of the following:
• Use the blocks from the PLC Ladder library to create a model that is compatible with ladder
diagram generation. To open the PLC Ladder library, type plcladderlib at the MATLAB
command prompt.
• Import ladder logic from a L5X file with the plcimportladder function.
To generate ladder logic from the Simulink models, use these functions: plcgeneratecode and
plcgeneraterunnertb
Ladder Diagram (LD) is a graphical programming language used to develop software for
programmable logic controllers (PLCs). It is one of the languages that the IEC 61131 Standard
specifies for use with PLCs.
A program in Ladder Diagram notation is a circuit diagram that emulates circuits of relay logic
hardware. The underlying program uses Boolean expressions that translate readily to switches and
relays. When you program complex applications directly in Ladder Diagram notation, it is challenging
because you must write the programs with only Boolean variables and expressions.
Using Simulink PLC Coder, you can generate Ladder Diagram code for your applications from a
Stateflow chart. The benefits are:
• You can design your application by using states and transitions in a Stateflow chart. Once you
complete the design, you can generate Ladder Diagram code in XML or another format. You then
import the generated code to an IDE such as CODESYS 3.5 or RSLogix AOI 5000 and view the
Ladder Diagram.
• When you test your Stateflow chart by using a set of inputs, you can reuse these inputs to create a
test bench for the Ladder Diagram code. You import the test bench to your PLC IDE and compare
the results of simulation with the results of running the Ladder Diagram. If the results agree, the
original Stateflow chart is equivalent to the generated Ladder Diagram code.
The figure shows a simple Stateflow chart with three states and two transitions. Based on the
transition conditions, the chart transitions from one state to another.
3-2
Simulink PLC Coder Ladder Diagram Code Generation
The state State1 is active as long transitionCondition1 and transitionCondition2 are not
true. This means, State1 is active in one of these two cases:
You can import the generated Ladder Diagram code to CODESYS 3.5 and view the diagram. A portion
of the Ladder Diagram is shown.
3-3
3 Generating Ladder Diagram
In the preceding Ladder Diagram, each rung of the ladder ends in a coil. The coil corresponds to a
state of the original chart. The contacts before the coil determine if the coil receives power. You can
compare the Ladder Diagram visually with the Stateflow chart. For instance, the coil State1_new
receives power in one of these two cases:
• The normally open contact State1 is closed and the normally closed contacts
transitionCondition1 and transitionCondition2 are open.
• The normally open contact stateflow_init is closed. This contact corresponds to the default
transition.
Once the coil State1_new receives power, the contact State1_new further down in the ladder is
then closed and the coil State1 receives power.
The Ladder Diagram executes from top to bottom and from left to right.
See “Prepare Chart for Simulink PLC Coder Ladder Diagram Code Generation” on page 3-6.
2 Generate Ladder Diagram code from the Stateflow chart. The code is in a format suitable for
import to an IDE.
Generate a test bench along with the code. The test bench is in the Structured Text language.
You can later import the code along with the test bench to your IDE. The test bench invokes the
Ladder Diagram code and compares the output against the expected outputs from the original
Stateflow chart.
See “Generate Simulink PLC Coder Ladder Diagram Code from Stateflow Chart” on page 3-9.
3-4
Simulink PLC Coder Ladder Diagram Code Generation
3 Import the generated Ladder Diagram code to your CODESYS 3.5 IDE. Validate the diagram in
the IDE by using the generated test bench.
See “Import Ladder Diagram Code to CODESYS 3.5 IDE and Validate Diagram” on page 3-14.
3-5
3 Generating Ladder Diagram
Note Ladder diagram generation from Stateflow charts will be removed in a future release. To
generate ladder diagrams, use Simulink models instead. To create Simulink models compatible with
ladder logic generation, do one of the following:
• Use the blocks from the PLC Ladder library to create a model that is compatible with ladder
diagram generation. To open the PLC Ladder library, type plcladderlib at the MATLAB
command prompt.
• Import ladder logic from a L5X file with the plcimportladder function.
To generate ladder logic from the Simulink models, use these functions: plcgeneratecode and
plcgeneraterunnertb
This example shows how to prepare your Stateflow chart for Ladder Diagram code generation. Once
your chart is ready, you can generate Ladder Diagram code from the chart.
For the complete Ladder Diagram code generation workflow, see “Ladder Diagram Generation
Workflow” on page 3-4.
• The inputs and outputs to the chart must be Boolean. They correspond to the input and output
terminals of your PLC.
• Each state in the chart must correspond to an output. The output is true if the state is active.
To ensure that each state in the chart is mapped to an output, in the Properties dialog box of each
state, select Create output for monitoring. Then, select Self activity.
• The transition conditions must involve only Boolean operations such as ~, &, and | between the
inputs.
3-6
Prepare Chart for Simulink PLC Coder Ladder Diagram Code Generation
Some advanced Stateflow features on page 3-18 are not supported because of inherent restrictions
in Ladder Diagram semantics. You can use the function plccheckforladder to check if the chart
has the required properties. You can also use the function plcprepareforladder to change certain
chart properties so that the chart is ready for Ladder Diagram code generation.
You can start generating Ladder Diagram code from the chart. See the example in “Generate
Simulink PLC Coder Ladder Diagram Code from Stateflow Chart” on page 3-9.
You can manually create a test harness by using the Signal Builder block or autogenerate a test
harness by using Simulink Design Verifier™. To autogenerate the test harness:
1 Right-click the chart or a subsystem containing the chart. Select Design Verifier > Generate
Tests for Subsystem.
2 After test creation, select Create harness model.
The harness model is created. The model consists of the original subsystem coupled with inputs from
a Signal Builder block. The block consists of multiple test cases, so that the states and transitions in
your model are covered at least once.
3-7
3 Generating Ladder Diagram
You can also create tests by using other blocks from the Simulink library. However, you must ensure
that the inputs to the chart are Boolean.
You can now generate Ladder Diagram code from the chart and validate the diagram.
• To generate Ladder Diagram code only, use the original Stateflow chart.
• To generate Ladder Diagram code with test bench, use the Stateflow chart coupled with the
Boolean inputs from the test cases. For instance, if you create a harness model with Simulink
Design Verifier, use the harness model for the Ladder Diagram code and test bench generation
instead of the original chart.
See “Generate Simulink PLC Coder Ladder Diagram Code from Stateflow Chart” on page 3-9.
3-8
Generate Simulink PLC Coder Ladder Diagram Code from Stateflow Chart
Note Ladder diagram generation from Stateflow charts will be removed in a future release. To
generate ladder diagrams, use Simulink models instead. To create Simulink models compatible with
ladder logic generation, do one of the following:
• Use the blocks from the PLC Ladder library to create a model that is compatible with ladder
diagram generation. To open the PLC Ladder library, type plcladderlib at the MATLAB
command prompt.
• Import ladder logic from a L5X file with the plcimportladder function.
To generate ladder logic from the Simulink models, use these functions: plcgeneratecode and
plcgeneraterunnertb
• Generate code from a Stateflow chart that you can view as Ladder Diagram in your IDE.
• Generate test bench for validation of the Ladder Diagram code in your IDE.
For the complete Ladder Diagram code generation workflow, see “Ladder Diagram Generation
Workflow” on page 3-4.
3-9
3 Generating Ladder Diagram
The chart consists of five states: Init, Fault, Red, Yellow, and Green. Based on the input to the
chart, transitions to any of these states can take place. For instance, the state Red becomes active in
the following scenarios:
• Initialization and power up: The previous state is Init and the condition Power_Up is true.
• Fault rectification: The previous state is Fault and the condition VLDHealthy &
FaultRectified is true.
• Transitions from other colors: The previous state is Green or Yellow, the conditions that allow
transition to Red are true, and the conditions that allow transition to another color or to the
Fault state are false.
• Staying red: The previous state is Red and the conditions that allow transition to another state
are false.
3-10
Generate Simulink PLC Coder Ladder Diagram Code from Stateflow Chart
The figure shows a portion of the Ladder Diagram code generated from the chart when viewed in the
CODESYS 3.5 IDE. The Ladder Diagram consists of contacts (normally open and normally closed) and
coils (normal, set, and reset).
3-11
3 Generating Ladder Diagram
You can map elements of the original Stateflow chart to these coils and contacts. For instance, the
coil Red_new corresponds to the update of the state Red in the Stateflow chart. For the coil to receive
power, one of the following must be true:
• Initialization and power up: The normally open contacts Init and Power_Up must be closed.
• Fault rectification: The normally open contacts Fault and T_1_1_trans must be closed. The
contact T_1_1_trans represents the transition condition VLDHealthy & FaultRectified in
the chart.
• Transitions from other colors: The normally open contact Green must be closed and the
following must be true:
• The normally open contact T_2_3_trans must be closed. This contact corresponds to the
chart condition that must be true for transition to the Red state.
• The normally closed contacts T_2_1_trans and T_2_2_trans must stay closed. These
contacts correspond to the chart condition that must be false for transition to the Red state. If
the conditions are true, the contacts open and the coil no longer receives power.
• Staying red: The normally open contact Red must be closed, and the normally closed contacts
T_4_1_trans and T_4_2_trans must stay closed. These contacts correspond to the chart
conditions that must be false for the Red state to continue to be active. If the conditions are true,
the contacts open and the coil no longer receives power.
Click Settings. Specify a supported IDE for the option “Target IDE” on page 12-3. See “IDEs
Supported for Ladder Diagram Code Generation”. Click OK.
4 Right-click the chart and select PLC Code > Generate Ladder Logic for Chart.
If code generation is successful, in the subfolder plcsrc of the current working folder, you see the
file ModelName.xml. You import this file to your IDE and view the Ladder Diagram. For the
CODESYS 3.5 IDE, see “Import Ladder Diagram Code to CODESYS 3.5 IDE and Validate Diagram” on
page 3-14.
You can also use the function plcgenerateladder to generate Ladder Diagram code from a
Stateflow chart.
1 Open the PLC Coder app. Click the PLC Code tab.
2 Click Settings. Select the option “Generate Testbench for Subsystem” on page 12-7.
3-12
Generate Simulink PLC Coder Ladder Diagram Code from Stateflow Chart
3 Right-click the chart and select PLC Code > Generate Ladder Logic for Chart.
The test benches use the inputs to the original Stateflow chart. Therefore, you can create test
harnesses for the original chart and reuse them for validation of the Ladder Diagram code.
You can also use the function plcgenerateladder to generate test benches.
After generating the Ladder Diagram code and the test benches, you can import them to your IDE.
For the CODESYS 3.5 IDE, see “Import Ladder Diagram Code to CODESYS 3.5 IDE and Validate
Diagram” on page 3-14.
3-13
3 Generating Ladder Diagram
Note Ladder diagram generation from Stateflow charts will be removed in a future release. To
generate ladder diagrams, use Simulink models instead. To create Simulink models compatible with
ladder logic generation, do one of the following:
• Use the blocks from the PLC Ladder library to create a model that is compatible with ladder
diagram generation. To open the PLC Ladder library, type plcladderlib at the MATLAB
command prompt.
• Import ladder logic from a L5X file with the plcimportladder function.
To generate ladder logic from the Simulink models, use these functions: plcgeneratecode and
plcgeneraterunnertb.
This example shows how to import generated Ladder Diagram code to an IDE and validate the
generated code against the original Stateflow chart by using the generated test bench.
For this example, the CODESYS 3.5 IDE is used. You can also use one of the other supported IDE. See
“IDEs Supported for Ladder Diagram Code Generation”.
For the complete Ladder Diagram code generation workflow, see “Ladder Diagram Generation
Workflow” on page 3-4.
Select Project > Import PLCOpenXML and navigate to the folder containing the XML file.
A dialog box opens with a full list of the components imported from the XML. If you generate a
test bench for validation, you also see the testbench.
3-14
Import Ladder Diagram Code to CODESYS 3.5 IDE and Validate Diagram
3 On the POUs pane, you see the project. View the Ladder Diagram in the project.
You can compare the Ladder Diagram with the original Stateflow chart.
For instance, if you generate Ladder Diagram code from the model
plcdemo_ladder_three_aspect, in the Ladder Diagram, you can identify the transition from
the Fault state to the Red state.
3-15
3 Generating Ladder Diagram
a The normally open contacts VLDHealthy and FaultRectified are closed. Coil
T_1_1_trans receives power and is energized.
b The normally open contacts Fault and T_1_1_trans are closed. The coil Red_new receives
power and is energized. Other conditions not shown in figure must also be satisfied.
c The normally open contact Red_new is closed. The coil Red receives power and is energized.
Besides coils and normally open contacts , the Ladder Diagram also uses:
•
Normally closed contacts : They appear if the ~ operator is used in a transition
condition.
•
Set coils and reset coils : They are used in the Ladder Diagram for chart
initialization. Reset coils are also used if you enforce additional safeguards against multiple
states from being simultaneously active. See the argument InsertGuardResets in
plcgenerateladder.
For more information about these symbols, refer to the IEC 61131-3 specifications.
4 Select Online > Simulation. Click the (Build) button and verify that there are no build
errors.
If the option is not active, you might have to change the version number in your XML. Search for
the version number in the XML and depending on the patch that you have, replace it with the
following version number:
1
Click the (Login) button and log in to the emulator device.
2
Click the (Start) button and begin simulation.
3 Double-click a test bench in your project. You see the following variables updating to reflect the
results of validation.
3-16
Import Ladder Diagram Code to CODESYS 3.5 IDE and Validate Diagram
3-17
3 Generating Ladder Diagram
Note Ladder diagram generation from Stateflow charts will be removed in a future release. To
generate ladder diagrams, use Simulink models instead. To create Simulink models compatible with
ladder logic generation, do one of the following:
• Use the blocks from the PLC Ladder library to create a model that is compatible with ladder
diagram generation. To open the PLC Ladder library, type plcladderlib at the MATLAB
command prompt.
• Import ladder logic from a L5X file with the plcimportladder function.
To generate ladder logic from the Simulink models, use these functions: plcgeneratecode and
plcgeneraterunnertb
Ladder Diagram semantics must be represented with switches and relays. Therefore, if you intend to
generate a Ladder Diagram from a Stateflow chart, you cannot use some advanced features in your
chart. The Stateflow chart must have the following form:
• The inputs and outputs to the chart must be Boolean. These inputs and outputs correspond to the
input and output terminals of your PLC.
• Each state of the chart must correspond to a chart output.
• The expressions controlling the transition between states must involve only Boolean operations
between the inputs.
In addition, the chart must have the following properties. You can use the function
plccheckforladder to check if the chart has the required properties. You can also use the function
plcprepareforladder to change certain chart properties so that the chart is ready for Ladder
Diagram code generation.
To ensure that each state in the chart is mapped to an output, in the Properties dialog box of each
state, select Create output for monitoring. Then, select Self activity.
3-18
Restrictions on Stateflow Chart for Ladder Diagram Generation
• The chart must not have data with scope other than input or output.
• The chart must not include:
• Atomic subcharts
• Multiple default transition
• Simulink functions
• Parallel states
• State hierarchy
• History junctions
• Dangling transitions
• Super transitions crossing subchart boundaries
• Conditional default paths
• Self transitions
See Also
Related Examples
• “Prepare Chart for Simulink PLC Coder Ladder Diagram Code Generation” on page 3-6
• “Generate Simulink PLC Coder Ladder Diagram Code from Stateflow Chart” on page 3-9
• “Import Ladder Diagram Code to CODESYS 3.5 IDE and Validate Diagram” on page 3-14
More About
• “Simulink PLC Coder Ladder Diagram Code Generation” on page 3-2
3-19
3 Generating Ladder Diagram
• Boolean variables
• Data access to array elements, bus elements, bit, and constant variables.
• Multiple rungs
• Simple Jump, Temporary End, and other supported execution control elements.
• Ladder diagram blocks. See plcladderlib.
• Ladder Diagram Instructions. See “Instructions Supported in Ladder Diagram” on page 14-2
• L5X Datatypes:
• Controller Tags
• Program Tags
• AOI Tags such as Input, Output and InOut
See Also
plccleartypes | plcgeneratecode | plcgeneraterunnertb | plcimportladder |
plcladderlib | plcladderoption | plcloadtypes
More About
• “Import L5X Ladder Files into Simulink” on page 3-22
• “Modeling and Simulation of Ladder Diagrams in Simulink” on page 3-27
3-20
Supported Features in Ladder Diagram
3-21
3 Generating Ladder Diagram
The simple_timer.L5X file was created by using the RSLogix 5000 IDE. A snippet of the .L5X file
is shown.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RSLogix5000Content SchemaRevision="1.0" SoftwareRevision="30.00"
TargetName="simple_timer" TargetType="Controller"
ContainsContext="false" Owner="Arun Mathew Iype, MathWorks"
ExportDate="Mon Nov 12 16:35:28 2018" ExportOptions="NoRawData
L5KData DecoratedData ForceProtectedEncoding AllProjDocTrans">
<Controller Use="Target" Name="simple_timer"
ProcessorType="Emulate 5570" MajorRev="30"
MinorRev="11" TimeSlice="20" ShareUnusedTimeSlice="1"
ProjectCreationDate="Mon Nov 12 16:33:36 2018"
LastModifiedDate="Mon Nov 12 16:33:43 2018"
SFCExecutionControl="CurrentActive"
SFCRestartPosition="MostRecent" SFCLastScan="DontScan"
ProjectSN="16#0000_0000"
MatchProjectToController="false" CanUseRPIFromProducer="false"
InhibitAutomaticFirmwareUpdate="0" PassThroughConfiguration="EnabledWithAppend"
DownloadProjectDocumentationAndExtendedProperties="true"
DownloadProjectCustomProperties="true"
ReportMinorOverflow="false">
<RedundancyInfo Enabled="false" KeepTestEditsOnSwitchOver="false"
IOMemoryPadPercentage="90"
DataTablePadPercentage="50"/>
<Security Code="0" ChangesToDetect="16#ffff_ffff_ffff_ffff"/>
<SafetyInfo/>
<DataTypes/>
<Modules>
<Module Name="Local" CatalogNumber="Emulate 5570" Vendor="1" ProductType="14"
ProductCode="53" Major="30" Minor="11" ParentModule="Local" ParentModPortId="1"
Inhibited="false" MajorFault="true">
<EKey State="ExactMatch"/>
<Ports>
<Port Id="1" Address="0" Type="ICP" Upstream="false">
3-22
Import L5X Ladder Files into Simulink
<Bus Size="10"/>
</Port>
</Ports>
</Module>
</Modules>
<AddOnInstructionDefinitions/>
<Tags/>
<Programs>
<Program Name="MainProgram" TestEdits="false" MainRoutineName="MainRoutine"
Disabled="false" UseAsFolder="false">
...
<Tags>
• Verify the Ladder Diagram file is a valid .L5X file. The file can be verified by compiling it in
Rockwell Automation IDE.
• If the file is valid, copy the .L5X file into a folder with read and write permissions. You can also
create a separate folder to store all the imported files along with the original Ladder
Diagram .L5X file.
Use the plcimportladder function to import the ladder into Simulink. For this example, the
program Name of the ladder is MainProgram and the MainRoutineName is MainRoutine.
>> plcimportladder('simple_timer.L5X')
The Ladder Diagram is imported into the pwd\simple_timer.slx Simulink model. The state
information of the ladder elements is stored in the data store memory and updated by the model
during simulation. The plcout\simple_timer_value.m file gets called during the pre-load stage
of the Simulink model. This file sets the timer initial values in Motor_timer data store memory.
The simple_timer.slx Simulink model consists of a Ladder Diagram Controller as the top unit.
This controller has a Main Task and Controller Tags. The Main Task consists of a Main
Program.
3-23
3 Generating Ladder Diagram
The Main Program contains the Simulink implementation of the simple_timer.L5X Ladder
Diagram. The ladder rung executes from top to bottom and left to right.
3-24
Import L5X Ladder Files into Simulink
You can use the Signal Builder block to create test inputs for Switch_A and verify the operation of
the imported ladder. You can also generate a PLC Ladder Diagram code or a C code for the top-level
subsystem. If you want to edit the imported ladder, the Simulink blocks are in the template Ladder
Diagram Library. To open the library, enter:
plcladderlib
If your Ladder Diagram has comments associated with the rung, these comments are also imported to
Simulink. In the Simulink environment, the comments are connected to the respective rung. For
example, the Ladder Diagram for the simple timer has a comment Switch ON Delay. After
importing the ladder diagram to Simulink, the comment is also imported as seen in Rung 3 of the
imported Simulink model.
3-25
3 Generating Ladder Diagram
Similarly, when you generate Ladder Diagram code from a Simulink model containing a rung
comment, the comment is also generated in the (L5X) ladder file. If your Simulink model has
multiple comments associated with the rung, in the generated Ladder Diagram, these comments are
merged into a single comment with each individual comment appearing in a separate line.
If you have an L5X file containing an AOI with mixed ordered arguments, this order is preserved
during import and export of the files.
See Also
plccleartypes | plcgeneratecode | plcgeneraterunnertb | plcimportladder |
plcladderlib | plcladderoption | plcloadtypes
More About
• “Supported Features in Ladder Diagram” on page 3-20
• “Modeling and Simulation of Ladder Diagrams in Simulink” on page 3-27
• “Generating Ladder Diagram Code from Simulink” on page 3-34
• “Generating C Code from Simulink Ladder” on page 3-36
• “Verify Generated Ladder Diagram Code” on page 3-38
• “Simulink PLC Coder Workflow vs. Rockwell Automation RSLogix IDE Workflow” on page 3-42
3-26
Modeling and Simulation of Ladder Diagrams in Simulink
1 To create a Ladder Diagram, open the Simulink PLC Coder Ladder library. At the MATLAB
command line, enter:
plcladderlib
The Ladder library opens containing all the blocks required for building the Ladder Diagram in
Simulink.
3-27
3 Generating Ladder Diagram
3-28
Modeling and Simulation of Ladder Diagrams in Simulink
2 Create a blank Simulink model. You can drag appropriate blocks from the library to build your
ladder logic model in Simulink. For each block, you can double-click the block to see the block
parameters and use the help menu to view its description. For more information on the Ladder
instructions that are implemented by these blocks, refer to the LOGIX 5000 Controllers General
Instructions Reference Manual.
3 The Simulink PLC Coder Ladder library contains top level ladder logic block such as
PLCControllerSuite, PLC Controller, Task, Ladder Diagram Program, Ladder diagram Subroutine,
Ladder Diagram Function Block (AOI), and AOI Runner. All these blocks are organization blocks
(Ladder Diagram containers) that cannot be on Ladder Diagram rungs. Apart from these
organizational blocks, other blocks from the library cannot be top level ladder logic block for
simulation.
• PLCControllerSuite can hold controller tags that are visible for all ladder logic blocks in this
controller, and also can contain Task block.
• PLCController allows you to build ladder logic directly. All the tags in the controller level
ladder diagram are controller tags (global variables or I/O symbols)
• Task is used to contain Ladder Diagram programs that are using the same sample time and
priority.
Note Code generation for empty Task blocks is not supported. If a Task block is empty, the
software does not issue warnings or errors during code generation, but the generated code
produces errors in Rockwell IDEs.
• Ladder Diagram Program enables you to build ladder logic directly. Program-level Ladder
Diagram can have program scope variables and also can access controller tags if defined.
• Ladder Diagram Subroutine enables you to create and define a named ladder routine. You can
edit the logic implemented by the subroutine by clicking the Routine Logic button under
the block parameters menu of this block.
• Ladder Diagram Function Block (AOI) enables you to create the Ladder Diagram function
block. You can edit the parameters and specifications of this block by using the various
options available under the block parameters menu of this block.
• AOI Runner is special program block that can contain only one Ladder Diagram Function
Block (AOI: add-on instruction) designed for AOI testing (test bench generation and
verification).
4 Drag a PLCControllerSuite block into the blank model you created in the previous step. You can
double-click each organizational unit to traverse to the lower level ladder logic semantics and
build your Ladder Diagram. The empty ladder logic semantics is shown.
3-29
3 Generating Ladder Diagram
5 Use the XIC and Motor blocks from the library to construct a simple ladder diagram. Use Add
Rungs or Add 1 Rung buttons in the ladder logic semantic to add a new rung. All added blocks
must be on the rung. Use the Junction block to merge rung branches.
6 Double-click each new block added to the rung and specify the tags. In Ladder Diagrams, tags
(variables) are used for representing all inputs, outputs, and internal memory. The tag can be a
variable name or an expression like:
3-30
Modeling and Simulation of Ladder Diagrams in Simulink
9 Update the ladder logic model to reflect changes. You have now created a simple ladder model in
Simulink.
3-31
3 Generating Ladder Diagram
Note If Function Block (AOI) is at the top level of a ladder diagram model and not inside a parent
program unit, the Allow Prescan Routine option is not enabled.
1 Use the plcladderoption function to enable Animation. At the MATLAB command line, enter:
plcladderoption('simpleController','Animation','on')
2 Connect input and output ports to the PLCControllerSuite block to provide inputs for simulation
and read the outputs. You must modify the attributes of the switch and motor tags. To change the
attributes of the tag, open the Program Variables table within the Ladder Diagram Program
block and set them to the values shown.
3 Go to controller level block and double-click the Controller Tags table to specify the global
variable and I/O symbol attributes.
4 The software now adds input and output ports to the PLCControllerSuite block. You can use
Simulink blocks to add inputs to the ladder model. For example, you can use the Constant block
to add Boolean inputs to mimic switch behavior.
5 Traverse to the Ladder Diagram Program block of the ladder model and Step Forward through
the simulation. The software uses the inputs provided, runs a behavioral simulation, and
animates the ladder rungs and blocks based on the execution state.
3-32
Modeling and Simulation of Ladder Diagrams in Simulink
6 You can continue stepping forward or run a continuous simulation to the end.
See Also
plccleartypes | plcgeneratecode | plcgeneraterunnertb | plcimportladder |
plcladderlib | plcladderoption | plcloadtypes
More About
• “Supported Features in Ladder Diagram” on page 3-20
• “Import L5X Ladder Files into Simulink” on page 3-22
• “Generating Ladder Diagram Code from Simulink” on page 3-34
• “Generating C Code from Simulink Ladder” on page 3-36
• “Verify Generated Ladder Diagram Code” on page 3-38
• “Simulink PLC Coder Workflow vs. Rockwell Automation RSLogix IDE Workflow” on page 3-42
3-33
3 Generating Ladder Diagram
generatedFiles = plcgeneratecode('simpleController/simpleController');
3-34
Generating Ladder Diagram Code from Simulink
Note You cannot generate Structured Text code from the Ladder Diagram blocks. The Ladder
feature supports only ladder code generation.
See Also
plccleartypes | plcgeneratecode | plcgeneraterunnertb | plcimportladder |
plcladderlib | plcladderoption | plcloadtypes
More About
• “Supported Features in Ladder Diagram” on page 3-20
• “Import L5X Ladder Files into Simulink” on page 3-22
• “Modeling and Simulation of Ladder Diagrams in Simulink” on page 3-27
• “Generating C Code from Simulink Ladder” on page 3-36
• “Verify Generated Ladder Diagram Code” on page 3-38
• “Simulink PLC Coder Workflow vs. Rockwell Automation RSLogix IDE Workflow” on page 3-42
3-35
3 Generating Ladder Diagram
The .L5X file was created using RSLogix 5000 IDE and contains contacts and coils representing
switches and motor. The following is a snapshot of the ladder structure.
The imported model contains a PLC Controller block named simpleController, followed by a Task
block named MainTask and finally a Ladder Diagram Program block named MainProgram. The
model imported into Simulink has blocks that implement the functionality of the contacts and coils.
3-36
Generating C Code from Simulink Ladder
Open the Configuration Parameters dialog box from the model editor by clicking Simulation >
Configuration Parameters.
cs = getActiveConfigSet(model);
openDialog(cs);
In the model window, initiate code generation and the build process for the model by using any of the
following options:
See Also
plccleartypes | plcgeneratecode | plcgeneraterunnertb | plcimportladder |
plcladderlib | plcladderoption | plcloadtypes
More About
• “Supported Features in Ladder Diagram” on page 3-20
• “Import L5X Ladder Files into Simulink” on page 3-22
• “Modeling and Simulation of Ladder Diagrams in Simulink” on page 3-27
• “Generating Ladder Diagram Code from Simulink” on page 3-34
• “Verify Generated Ladder Diagram Code” on page 3-38
3-37
3 Generating Ladder Diagram
3 Add Signal Builder input block, Scope and output ports as shown.
3-38
Verify Generated Ladder Diagram Code
3-39
3 Generating Ladder Diagram
Tbcode =
{'C:\runnerTB\simpleXIC_runner.L5X'}
If you have created the Ladder Diagram model in Simulink and are generating Ladder Diagram (L5X)
code, you can also use the Generate testbench for subsystem option available on the PLC Code
3-40
Verify Generated Ladder Diagram Code
Generation pane in the Configuration Parameters dialog box to generate test bench code along with
ladder code. When the selected subsystem is ladder AOI Runner block and test bench option is on,
the generated code will include test bench, selected AOI, as well as dependent AOI and UDT types.
See Also
plccleartypes | plcgeneratecode | plcgeneraterunnertb | plcimportladder |
plcladderlib | plcladderoption | plcloadtypes
More About
• “Supported Features in Ladder Diagram” on page 3-20
• “Import L5X Ladder Files into Simulink” on page 3-22
• “Modeling and Simulation of Ladder Diagrams in Simulink” on page 3-27
• “Generating Ladder Diagram Code from Simulink” on page 3-34
• “Generating C Code from Simulink Ladder” on page 3-36
• “Simulink PLC Coder Workflow vs. Rockwell Automation RSLogix IDE Workflow” on page 3-42
3-41
3 Generating Ladder Diagram
• You first place either the PLC Controller or PLC Controller Suite block onto the blank
Simulinkmodel page. This block contains all the tasks, programs, program tags, controller tags,
routines, AOI blocks and so on. For more information, see PLC Controller.
• You place the Task block inside the PLC Controller or PLC Controller suite block. The Task blocks
house the programs, program tags, routines, AOI blocks, and so on. For more information see,
Task.
• You place the Ladder Diagram Program block or blocks inside the Task block. The Ladder Diagram
Program block contains program tags, routines , AOI blocks, and so on. For more information see,
Program
• You next place JSR (Jump To Subroutine) blocks within the Ladder Diagram Program block. The
JSR blocks contain the ladder rungs, ladder logic and AOI blocks within them. For more
information see ,Subroutine.
• You can place the AOI block either inside the JSR block or inside the Ladder Diagram Program
block. For more information see, Function Block (AOI).
3-42
Simulink PLC Coder Workflow vs. Rockwell Automation RSLogix IDE Workflow
See Also
Function Block (AOI) | PLC Controller | PLC Controller Suite | Program | Subroutine
| Task
More About
• “Supported Features in Ladder Diagram” on page 3-20
• “Import L5X Ladder Files into Simulink” on page 3-22
• “Modeling and Simulation of Ladder Diagrams in Simulink” on page 3-27
• “Generating Ladder Diagram Code from Simulink” on page 3-34
• “Verify Generated Ladder Diagram Code” on page 3-38
3-43
3 Generating Ladder Diagram
The Ladder Library opens all the blocks required for building the Ladder Diagram in Simulink.
2 To create a new Simulink library, in the Library tab click New > Library. From the Simulink
start page, select Blank Library and click Create Library.
3 Drag a Custom Instruction block from the Ladder Library to the new library that you created.
4 To build your own ladder logic model, double-click your Custom Instruction block to see the block
parameters. Use the Help menu to view their descriptions.
3-44
Create Custom Instruction in PLC Ladder Diagram Models
5 In Instruction Name text field, give a name to your instruction. Specify the inputs and outputs
required for your instruction block. Click Apply, and then click OK.
6 To look inside the mask, click in the Custom Instruction block. The blocks inside the mask
enable the instruction to simulate with other PLC Ladder instructions. The user-defined logic is
included in the Instruction_Enable block.
7 Save the library as plcuserlib.slx. You can add multiple instruction blocks to this library.
1 To open the Simulink Start Page, on the MATLAB Home tab, click Simulink.
2 Select Blank Library and click Create Library.
3 Save the library as plcuserlib.slx to a folder on the MATLAB path.
4 To open the PLC Ladder Library, at the MATLAB command line, enter:
plcladderlib
5 Drag the Custom Instruction block from plcladderlib to your user-defined library
plcuserlib.slx.
6 Double-click the Custom Instruction block to open the Block Parameters.
7 Specify the Instruction Name as SQR. Check that the Number of Inputs is 1 and Input Types
is specified as a cell array of allowed data types. Similarly, check that the Number of Outputs is
1 and Output Types is specified as a cell array of allowed data types. Click OK.
8 Click in the SQR block and double-click the Instruction_Enable subsystem.
3-45
3 Generating Ladder Diagram
9 Inside the Instruction_Enable subsystem, add a Sqrt block from the Simulink / Math Operations
Library. Double-click this block and select signedSqrt from Main>Function, and then click
OK.
10 Connect the input and output ports to the input and output ports of Sqrt block by using Data
Type Conversion blocks.
11 Navigate to the top level of the library. Click Lock Links and Unlock Library in the Library tab,
and then save the library. Simulink PLC Coder can now use the SQR instruction when
plcuserlib.slx is on the MATLAB path. You can drag this instruction to your models from the
library that you have created and saved.
12 To verify if Simulink PLC Coder has identified the newly created instruction, at the MATLAB
command line, enter:
plcladderinstructions
This command lists the instructions that Simulink PLC Coder can use. The supported instructions
displayed in the output includes the SQR instruction.
The example in the image shows the use of the SQR instruction inside an Add-On Instruction
block.
3-46
Create Custom Instruction in PLC Ladder Diagram Models
Limitations
The Custom Instruction block does not support instructions:
See Also
Custom Instruction | plcimportladder | plcladderinstructions | plcladderlib
More About
• “Supported Features in Ladder Diagram” on page 3-20
• “Import L5X Ladder Files into Simulink” on page 3-22
• “Modeling and Simulation of Ladder Diagrams in Simulink” on page 3-27
• “Generating Ladder Diagram Code from Simulink” on page 3-34
3-47
4
The test bench runs the generated code to verify that the output is functionally and numerically
equivalent to the output from the execution of a Simulink model. The following table shows how the
test bench compares the expected and actual data values.
The relative tolerance comparison for single or double data types uses the following logic:
IF ABS(actual_value - expected_value) > (ERROR_TOLERANCE * expected_value) THEN
testVerify := FALSE;
END_IF;
To verify the generated code using the test bench, import the generated Structured Text and the test
bench data into your target IDE. You can import test bench code:
• Manually.
• Automatically, including running the test bench.
For more information, see “Import and Verify Structured Text Code” on page 4-4.
Depending on the target IDE platform, the Simulink PLC Coder software generates code into one or
more files. See “Files Generated with Simulink PLC Coder” on page 1-14 for list of the target IDE
platforms and the possible generated files.
4-2
Integrate Generated Code with Custom Code
To use ssMethodType with a FUNCTION_BLOCK for your model, in the generated code, the top-level
subsystem function block prototype has one of the following formats:
For non top-level subsystems, in the generated code, the subsystem function block prototype has one
of the following formats:
4-3
4 Generating Test Bench Code
If you want to import the generated code, see “Generate and Automatically Import Structured Text
Code” on page 1-17.
1 Specify that test bench code must be generated for the subsystem.
a Open the PLC Coder app. Click the PLC Code tab.
b Click Settings.
c Select “Generate Testbench for Subsystem” on page 12-7.
If you do not specify that test bench code must be generated, when you automatically verify the
generated code, you see the error Testbench not selected.
2 You can generate the code and testbench, and manually import them to your target IDE. For
information on how to import generated code, see the user manual for your target IDE.
Alternatively, after code generation, import and verify the generated code automatically. Right-
click the subsystem and select PLC Code > Generate, Import, and Verify Code for
Subsystem. The software:
• IDEs not supported for automatic import and verification, see “Troubleshoot Automatic Import
Issues” on page 1-18.
• Possible reasons for long testbench code generation time, see “Troubleshooting: Long Test Bench
Code Generation Time” on page 4-5.
4-4
Import and Verify Structured Text Code
1 Start the PHOENIX CONTACT (previously KW) Software MULTIPROG 5.0/5.50 or Phoenix
Contact PC WORX 6.0 IDE.
2 Select File > Delete Template. Delete any template named Empty, and click OK when done.
3 Select File > New Project, select Project Wizard, then click OK.
• Logical POUs
• Physical Hardware
5 Verify that the project tree has only top-level nodes for Libraries, Data Types, Logical
POUs, and Physical Hardware. There must not be any subtree nodes.
6 In the IDE, select File > Save As Template.
7 In Template Name, type Empty.
8 Click OK.
9 Close the IDE interface.
Open your model, right-click the Subsystem block, and select one of the following:
4-5
4 Generating Test Bench Code
• If you want to retain the simulation duration and the step size, divide the simulation into multiple
parts. For a simulation input signal with duration [0, t], divide the input into multiple parts with
durations [0, t1], [t1, t2 ], [t2, t3], etc., where t1 < t2 < t3 < .. < t. Generate test bench
code for each part separately and manually import them together to your IDE.
See Also
Related Examples
• “Verify Generated Code with Multiple Test Benches” on page 4-7
4-6
Verify Generated Code with Multiple Test Benches
1 Provide multiple signal groups as inputs by using a Signal Builder block with multiple signal
groups (Simulink).
Instead of manually entering a Signal Builder block and creating multiple signal groups, you can
use Simulink Design Verifier to create a test harness model from the subsystem. In the test
harness model, a Signal Builder block with one or more signal groups provides input to the
subsystem. You can use this Signal Builder block to provide inputs to your subsystem. However, if
your model is complex, Simulink Design Verifier can create large number of signal groups. See
“Troubleshooting: Test Data Exceeds Target Data Size” on page 4-8.
a Right-click the subsystem and select Design Verifier > Generate Tests for Subsystem.
b In the Simulink Design Verifier Results Summary window, select Create harness model.
c Open the Inputs block in the test harness model. The Inputs block is a Signal Builder block
that can have one or more signal groups.
In the Signal Builder window, make sure that more than one signal group is available in the
Active Group drop-down list.
4-7
4 Generating Test Bench Code
d Copy the Signal Builder block from the test harness model and use this block to provide
inputs to your original subsystem.
2 Specify that test benches must be generated for the subsystem.
a Open the PLC Coder app. Click the PLC Code tab.
b Click Settings.
c Select “Generate Testbench for Subsystem” on page 12-7.
3 Right-click the subsystem and select PLC Code > Generate, Import and Verify Code for
Subsystem.
In your target IDE, you can see multiple test benches. Each test bench corresponds to a signal
group.
4-8
Verify Generated Code with Multiple Test Benches
• Reduce the number of signal groups in the Signal Builder block and regenerate the test benches.
• Increase the simulation step size for the subsystem.
Limitations
Signal groups in a signal builder block should have the same time range for testbench code
generation.
See Also
Related Examples
• “Import and Verify Structured Text Code” on page 4-4
4-9
5
In the Configuration Parameters dialog box, in the Report panel, you see these options.
Note You must have a Simulink Report Generator™ license to generate traceability reports.
The coder provides the traceability report to help you navigate more easily between the generated
code and your source model. When you enable code generation report, the coder creates and displays
an HTML code generation report. You can generate reports from the Configuration Parameters dialog
box or the command line. Traceability report generation is disabled when generating Ladder
Diagrams from Stateflow chart. See “Traceability Report Limitations” on page 12-32 . A typical
traceability report looks something like this figure:
5-2
Information in Code Generation Reports
5-3
5 Code Generation Reports
5-4
Create and Use Code Generation Reports
6 Click Generate PLC Code to initiate code and report generation. The coder generates HTML
report files as part of the code generation process.
5-5
5 Code Generation Reports
1 In the generated code HTML report display, look for <S1>/Gain. Code Generation Report has
syntax highlighting for easy readability. PLC-specific keywords are highlighted in blue, comments
in green, and the rest of the code in black.
2 In the HTML report window, click a link to highlight the corresponding source block. For
example, in the HTML report shown in the previous figure, you click the hyperlink for the Gain
block (highlighted) to view that block in the model. Clicking the hyperlink locates and displays
the corresponding block in the model editor window. You can use the same method to trace other
block from the HTML report.
• Subsystem
5-6
Create and Use Code Generation Reports
• Simulink block
• MATLAB Function block
• Truth Table block
• State Transition Table block
• Stateflow chart, or the following elements of a Stateflow chart:
• State
• Transition
• Graphical function
• MATLAB function
• Truth table function
You must have already generated code with a traceability report to trace a model component to the
generated code. If not, see “Generate a Traceability Report from Configuration Parameters” on page
5-4 or “Generate a Traceability Report from the Command Line” on page 5-12.
In the report, the highlighted tag S1/Gain indicates the beginning of the generated code for the
block. You can use the same method to trace from other Simulink, Stateflow, and MATLAB objects
to the generated traceability report.
For a programmatic way to trace a block in the model to generated code, see rtwtrace.
To review and analyze the generated code, it is helpful to navigate between the code and model. You
can include a web view of the model within the HTML code generation report. You can then share
your model and generated code outside of the MATLAB environment. You need a Simulink Report
Generator license to include a Web view (Simulink Report Generator) of the model in the code
generation report.
5-7
5 Code Generation Reports
Web views require a web browser that supports Scalable Vector Graphics (SVG). Web views use SVG
to render and navigate models.
• Mozilla® Firefox® Version 1.5 or later, which has native support for SVG. To download the Firefox
browser, go to www.mozilla.com/.
• Apple Safari Web browser
• The Microsoft® Internet Explorer® web browser with the Adobe® SVG Viewer plugin. To download
the Adobe SVG Viewer plugin, go to www.adobe.com/svg/.
This example shows how to create an HTML code generation report which includes a web view of the
model diagram.
5-8
Create and Use Code Generation Reports
7 Click Generate PLC Code to initiate code and report generation. The code generation report for
the top model opens in a MATLAB web browser.
5-9
5 Code Generation Reports
8 In the left navigation pane, select a source code file. The corresponding traceable source code is
displayed in the right pane and includes hyperlinks.
9 Click a link in the code. The model web view displays and highlights the corresponding block in
the model.
10 To go back to the code generation report for the top model, at the top of the left navigation pane,
click the Back button until the report for the top model is displayed.
For more information about navigating between the generated code and the model diagram, see:
When you are using the model web view, the HTML code generation report includes the following
limitations:
• Code is not generated for virtual blocks. In the model web view, if you click a virtual block, the
code generation report clears highlighting in the source code files.
5-10
Create and Use Code Generation Reports
• Stateflow truth tables, events, and links to library charts are not supported in the model web view.
• Searching in the code generation report does not find or highlight text in the model web view.
• In a subsystem build, the traceability hyperlinks of the root-level inports and outports blocks are
disabled.
• If you navigate from the actual model diagram (not the model web view in the report), to the
source code in the HTML code generation report, the model web view is disabled and not visible.
To enable the model web view, open the report again, see “Open Code Generation Report”
(Simulink Coder).
1 Open the PLC Coder app. Click the PLC Code tab.
2 Click Settings and navigate to the PLC Code Generation pane.
3 To enable report generation, select Report > Generate traceability report.
4 Click OK.
5 Click Generate PLC Code to initiate code and report generation. The coder generates HTML
report files as part of the code generation process. The Code Metrics Report is shown on the left
navigation pane.
5-11
5 Code Generation Reports
open_system('plcdemo_simple_subsystem');
2 Enable the code generation parameter PLC_GenerateReport. To view the output in the model
web view, also enable PLC_GenerateWebview:
set_param('plcdemo_simple_subsystem', 'PLC_GenerateReport', 'on');
set_param('plcdemo_simple_subsystem', 'PLC_GenerateWebView', 'on');
A traceability report is displayed. In your model, a View diagnostics hyperlink appears at the
bottom of the model window. Click this hyperlink to open the Diagnostic Viewer window.
5-12
View Requirements Links from Generated Code
Note The requirement links must be associated with a model object. If requirements links are
associated with the code in a MATLAB Function block, they do not appear in generated code
comments.
Option Purpose
Include comments on page 12-12 Model information must appear in code
comments.
Generate traceability report on page 12-32 After code is generated, a Code Generation
Report must be produced.
3 Generate code.
The Code Generation Report opens. The links to requirements documents appear in generated
code comments. When you view the code in the Code Generation Report, you can open the links
from the comments.
5-13
5 Code Generation Reports
You can use the information in the Static Code Metrics Report to assess the generated code and make
model changes before code implementation in your target IDE.
Before starting, you must familiarize yourself with potential code limitations of your IDE. For
example, some IDEs have limits on the number of variables or lines of code in a function block.
For detailed instructions on generating the report, see “Generate a Static Code Metrics Report” on
page 5-11.
Report Contents
The Static Code Metrics Report is divided into the following sections:
5-14
Working with the Static Code Metrics Report
• File Information: Reports high-level information about generated files, such as lines and lines of
code.
• Global Variables: Reports information about global variables defined in the generated code.
• Global Constants: Reports information about global constants defined in the generated code.
• Function Block Information: Reports a table of metrics for each function block generated from
your model.
5-15
6
To control how the block parameters appear in the generated code, you can either define the
parameters as Simulink.Parameter objects in the MATLAB workspace or use the Model Parameter
Configuration dialog box. For more information, see “Control Appearance of Block Parameters in
Generated Code” on page 6-4.
Simulink PLC Coder exports tunable parameters as exported symbols and preserves the names of
these parameters in the generated code. It does not mangle these names. As a result, if you use a
reserved IDE keyword as a tunable parameter name, the code generation can cause compilation
errors in the IDE. As a best practice, do not use IDE keywords as tunable parameter names.
The coder maps tunable parameters in the generated code as listed in the following table:
6-2
Block Parameters in Generated Code
6-3
6 Working with Tunable Parameters in the Simulink PLC Coder Environment
For more information, see “Block Parameters in Generated Code” on page 6-2.
• Use a MATLAB script to create a Simulink.Parameter object. Run the script every time
that the model loads.
Simulink stores Simulink.Parameter objects outside the model. You can then share
Simulink.Parameter objects between multiple models.
• Use the Model Configuration Parameters dialog box to make the parameters tunable.
Simulink stores global tunable parameters specified using the Configuration Parameters
dialog box with the model. You cannot share these parameters between multiple models.
Note The MATLAB workspace parameter value must be of the same data type as used in the
model. Otherwise, the value of the variable in the generated code is set to zero. See “Workspace
Parameter Data Type Limitations” on page 18-4.
The following script setup_tunable_params.m creates the constants K1, K2, and K3 as
Simulink.Parameter objects, assigns values, and sets the storage classes for these constants.
For more information on the storage classes, see “Block Parameters in Generated Code” on page
6-2.
% tunable parameter mapped to local variable
K1 = Simulink.Parameter;
K1.Value = 0.1;
K1.CoderInfo.StorageClass = 'Model default';
6-4
Control Appearance of Block Parameters in Generated Code
K2.CoderInfo.StorageClass = 'ExportedGlobal';
a In the model window, go to the Modeling tab and select Model Properties from the Model
Settings drop-down.
b In the Model Properties dialog box, on the Callbacks tab, select PreLoadFcn. Enter
setup_tunable_params for Model pre-load function.
c On the Callbacks tab, select CloseFcn. Enter clear K1 K2 K3; for Model close
function.
Every time that you open the model, the variables K1, K2, and K3 are loaded into the base
workspace. You can view the variables and their storage classes in the Model Explorer.
3 Generate code and inspect it.
6-5
6 Working with Tunable Parameters in the Simulink PLC Coder Environment
FUNCTION_BLOCK SimpleSubsystem
.
.
VAR
K1: LREAL := 0.1;
.
.
END_VAR
.
.
END_FUNCTION_BLOCK
K2 ExportedGlobal K2 is a global variable.
VAR_GLOBAL
K2: LREAL := 0.2;
END_VAR
K3 CoderInfo.CustomStorageClass set K3 is a global constant.
to Const.
VAR_GLOBAL CONSTANT
SS_INITIALIZE: SINT := 0;
K3: LREAL := 0.3;
SS_STEP: SINT := 1;
END_VAR
The model plcdemo_tunable_params illustrates these steps. The model contains a Subsystem
block SimpleSubsystem that has three Gain blocks with tunable parameters, K1, K2, and K3.
1 Specify that the variables K1, K2, and K3 must be initialized before the model loads and that the
MATLAB workspace must be cleared before the model closes.
a In the Modeling tab and select Model Properties from the Model Settings drop-down.
b In the Model Properties dialog box, on the Callbacks tab, select PreLoadFcn. Enter
K1=0.1; K2=0.2; K3=0.3; for Model pre-load function.
c On the Callbacks tab, select CloseFcn. Enter clear K1 K2 K3; for Model close
function.
2 On the Modeling tab and select Model Settings to open the Configuration Parameters dialog
box.
3 Navigate to Optimization pane. Specify that all parameters must be inlined in the generated
code. Select Inlined for Default Parameter Behavior.
4 To override the inlining and make individual parameters tunable, click Configure. In the Model
Parameter Configuration dialog box, from the Source list, select Referenced workspace
variables.
5 Ctrl+select the parameters and click Add to table >>.
6-6
Control Appearance of Block Parameters in Generated Code
By default, this dialog box sets all parameters to the SimulinkGlobal storage class. Set the
Storage class and Storage type qualifier as shown in this figure. For more information on the
storage classes, see “Block Parameters in Generated Code” on page 6-2.
FUNCTION_BLOCK SimpleSubsystem
.
.
VAR
K1: LREAL := 0.1;
.
.
END_VAR
.
.
END_FUNCTION_BLOCK
6-7
6 Working with Tunable Parameters in the Simulink PLC Coder Environment
VAR_GLOBAL
K2: LREAL := 0.2;
END_VAR
K3 CoderInfo.CustomStorageC K3 is a global constant.
lass and Storage type
qualifier set to Const. VAR_GLOBAL CONSTANT
SS_INITIALIZE: SINT := 0;
K3: LREAL := 0.3;
SS_STEP: SINT := 1;
END_VAR
6-8
7
1 Set up a data store in your model by using a Data Store Memory block.
2 Associate a Simulink.Signal object with the data store.
a In the base workspace, define a Simulink.Signal object with the same name as the data
store. Set the storage class of the object to ExportedGlobal or ImportedExtern.
b Use the Model Data Editor to enable the Data store name must resolve to Simulink
signal object parameter of the Data Store Memory block. To use the Model Data Editor in a
model, on the Modeling tab, select Model Data Editor under the Design category. On the
Data Stores tab, set the Change View drop-down to Code. Enable Resolve for the Data
Store Memory block. For more information, see “Configure Data Properties by Using the
Model Data Editor” (Simulink) .
3 In your model, attach the signals that you want to Data Store Read blocks that read from the data
store and Data Store Write blocks that write to the data store.
The Simulink.Signal object that is associated with the global Data Store Memory block appears as
a global variable in generated code.
Note If you follow this workflow for Rockwell Automation RSLogix 5000 AOIs, the generated code
uses INOUT variables for the global data.
7-2
Control Code Partitions for Subsystem Block
• Generates a function block for the top-level atomic subsystem for which you generate code.
• Generates a function block for an atomic subsystem whose Function packaging parameter is set
to Reusable function.
• Inlines generated code from atomic subsystems, whose Function packaging parameter is set to
Inline, into the function block that corresponds to the nearest ancestor subsystem. This nearest
ancestor cannot be inlined.
For code generation from a subsystem with no inputs or outputs, you must set the Function
packaging parameter of the block to Reusable function.
• Function packaging
• Function name options
Use the Function packaging parameter to specify the code format to generate for an atomic
(nonvirtual) subsystem. The Simulink PLC Coder software interprets this parameter depending on the
setting that you choose:
• Inline the S1 subsystem code by setting Function packaging to Inline. This setting creates one
function block for the parent with the S1 subsystem inlined.
• Create a function block for the S2 subsystem by setting Function packaging to Reusable
function or Auto. This setting creates two function blocks, one for the parent, one for S2.
7-3
7 Controlling Generated Code Partitions
You can use the Function name options parameter to change the name of a subsystem from the one
on the block label. When the Simulink PLC Coder generates software, it uses the string you specify
for this parameter as the subsystem name. For example, see
plcdemo_hierarchical_virtual_subsystem:
1 Open the S1 subsystem block parameter dialog box.
2 If the Treat as atomic unit check box is not yet selected, select it.
3 Click the Code Generation tab.
4 Set Function packaging to Reusable function.
5 Set Function name options to User specified.
6 In the Function name field, specify a custom name. For example, type my_own_subsystem.
7-4
Control Code Partitions for Subsystem Block
7-5
7 Controlling Generated Code Partitions
7-6
Control Code Partitions for Subsystem Block
7-7
7 Controlling Generated Code Partitions
However, Simulink PLC Coder does not follow your inlining specifications exactly in the following
cases:
• If a MATLAB function accesses data that is local to the chart, it is inlined in generated code even if
you specify that the function must not be inlined.
Explanation: The chart is converted to a function block in generated code. If the MATLAB function
in the chart is converted to a Structured Text function, it cannot access the data of an instance of
the function block. Therefore, the MATLAB function cannot be converted to a Structured Text
function in generated code and is inlined.
• If a MATLAB function has multiple outputs and you specify that the function must not be inlined, it
is converted to a function block in generated code.
Explanation: A Structured Text function cannot have multiple outputs, therefore the MATLAB
function cannot be converted to a Structured Text function.
The following simple example illustrates the different cases. The model used here has a Stateflow
chart that contains four MATLAB functions fcn1 to fcn4.
7-8
Control Code Partitions for MATLAB Functions in Stateflow Charts
7-9
7 Controlling Generated Code Partitions
7-10
Control Code Partitions for MATLAB Functions in Stateflow Charts
7-11
7 Controlling Generated Code Partitions
7-12
8
• Define the custom element in the subsystem for which you want to generate code.
• Name the custom element.
• In the Configuration Parameters dialog box, add the name of the custom element to PLC Code
Generation > Identifiers > Externally Defined Identifiers in the Configuration Parameters
dialog box.
• Generate code.
For a description of how to integrate a custom function block, see “Integrate Custom Function Block
in Generated Code” on page 8-3. For a description of the Externally Defined Identifiers
parameter, see “Externally Defined Identifiers” on page 12-28.
8-2
Integrate Custom Function Block in Generated Code
function Y = fcn(U,V)
% Stub behavior for simulation. This block
% is replaced during code generation
Y = U + V;
4 Change the MATLAB Function block name to ExternallyDefinedBlock.
5 Create a subsystem from this MATLAB Function block.
6 Complete the model to look like plcdemo_external_symbols.
8-3
8 Integrating Externally Defined Identifiers
10 Save and close your new model. For example, save it as plcdemo_external_symbols_mine.
11 Generate code for the model.
12 In the generated code, look for instances of ExternallyDefinedBlock.
8-4
9
IDE-Specific Considerations
• How to generate code, see “Generate and Examine Structured Text Code” on page 1-9.
• The location of generated code, see “Files Generated with Simulink PLC Coder” on page 1-14.
The custom file name unless assigned differently, is the model_name.scl. After you open the
file, a new entry called model_name.scl appears under the Sources node.
3 Double-click the new entry. The generated code is listed in the SCL editor window.
4 In the SCL editor window, select Options > Customize.
5 In the customize window, select Create block numbers automatically, and click OK.
The new Function Block is now integrated and available for use with the existing Siemens SIMATIC
STEP 7 project.
The custom file name unless assigned differently, is the model_name.scl. After you open the
file, a new entry called model_name.scl appears under the External source files node.
3 Right-click the new entry and select Generate blocks from source.
The Siemens TIA Portal IDE compiles the new file and generates TIA Portal program blocks from
the code. The program blocks appear under the Program blocks node. They are available for
use with the existing Siemens TIA Portal project.
9-2
Use Internal Signals for Debugging in RSLogix 5000 IDE
plcdemo_simple_subsystem
2 In the Configuration Parameters dialog box, set Target IDE to Rockwell RSLogix 5000:
AOI.
3 In the top-level subsystem of the model, right-click the output signal of SimpleSubsystem and
select Properties.
5 Click OK.
6 Generate code for the top-level subsystem.
7 Inspect the generated code for the string Required=false.
For more information on signals with test points, see “What Is a Test Point?” (Simulink).
9-3
9 IDE-Specific Considerations
Design your model to use single-precision data type (single) as much as possible instead of double-
precision data type (double). If you must use doubles in your model, the numeric results produced by
the generated Structured Text can differ from Simulink results. This difference is due to double-single
conversion in the generated code.
Design your model to use signed integer data types (int8, int16, int32) as much as possible instead of
unsigned integer data types (uint8, uint16, uint32). Doing so avoids overflow issues that unsigned-to-
signed integer conversions can cause in the generated code.
Reserved Keywords
The Rockwell AutomationRSLogix target IDE has reserved keywords. Do not use them as tag names
in subsystems from which code will be for be generated for Rockwell AutomationRSLogix IDE.
9-4
Rockwell Automation RSLogix Requirements
ABS ACS AND ASN ATN COS DEG FRD LN LOG MOD
NOT OR RAD SIN SQR TAN TOD TRN XOR acos asin
atan by case do else elsif end_cas end_for end_if end_rep end_wh
e eat ile
exit for if of repeat return then to trunc until while
These keywords are case insensitive. If your code generation target IDE is the Rockwell
AutomationRSLogix 5000 or Studio 5000 IDE do not use these keywords as variable names.
9-5
9 IDE-Specific Considerations
For Siemens PLC devices that support double-precision floating point types, use Siemens TIA
Portal: Double Precision as Target IDE for generating code. The generated code uses the
LREAL type for double-precision floating point types in the model. For more information, see “Target
IDE” on page 12-3.
Design your model to use int16 and int32 data types as much as possible instead of int8 or unsigned
integer data types. The Simulink numerical results using int8 or unsigned integer data types can
differ from the numerical results produced by the generated Structured Text.
Design your model so that effects of integer data type conversion of the generated code do not
change the expected semantics of the model.
INOUT Variables
The Siemens SIMATIC STEP 7 and the TIA Portal single-precision targets do not support INOUT
variables. If your Simulink model contains MATLAB Function blocks with y = f ( y ) style in-place
variables, coder generates code using normal input and output variables. However, if the code
generation option for the MATLAB Function block is set to use Reusable function, this conversion is
not possible. To fix this issue, rewrite the MATLAB Function block without using in-place variables or
change the block code generation option to either Auto or Inline.
9-6
Selectron CAP1131 IDE Requirements
See Also
9-7
10
Supported Blocks
For Simulink semantics not supported by Simulink PLC Coder, see “Simulink PLC Coder Structured
Text Code Generation Limitations” on page 11-2.
This library contains two sublibraries, Simulink and Stateflow. Each sublibrary contains the blocks
that you can include in a Simulink PLC Coder model.
10-2
Supported Blocks
Inport
Bus Creator
Bus Selector
Constant
Demux
Discrete-Time Integrator
Gain
Ground
Logical Operator
Mux
Product
Relational Operator
Saturation
Scope
Subsystem
10-3
10 Supported Simulink and Stateflow Blocks
Inport
Outport
Sum
Switch
Terminator
Unit Delay
Discontinuities
Rate Limiter
Relay
Saturation
Saturation Dynamic
Wrap To Zero
Discrete
Difference
Discrete Derivative
Discrete Filter
Discrete State-Space
Discrete-Time Integrator
FIR Interpolation
Integer Delay
Memory
Tapped Delay
10-4
Supported Blocks
Unit Delay
Zero-Order Hold
Bit Clear
Bit Set
Bitwise Operator
Compare To Constant
Compare To Zero
Detect Change
Detect Decrease
Detect Increase
Extract Bits
Interval Test
Logical Operator
Shift Arithmetic
Lookup Tables
Dynamic-Lookup
PreLookup
10-5
10 Supported Simulink and Stateflow Blocks
Math Operations
Abs
Add
Assignment
Bias
Divide
Dot Product
Gain
Math Function
Matrix Concatenate
MinMax
Permute Dimensions
Polynomial
Product
Product of Elements
Reciprocal Sqrt
Reshape
Rounding Function
Sign
Slider Gain
Sqrt
Squeeze
Subtract
Sum
Sum of Elements
Trigonometric Function
Unary Minus
Vector Concatenate
10-6
Supported Blocks
Model Verification
Assertion
Model-Wide Utilities
DocBlock
Model Info
Atomic Subsystem
CodeReuse Subsystem
Enabled Subsystem
Enable
Function-Call Subsystem
Subsystem
Inport
Outport
Signal Attributes
Signal Conversion
10-7
10 Supported Simulink and Stateflow Blocks
Signal Routing
Bus Assignment
Bus Creator
Bus Selector
Demux
From
Goto
Index Vector
Multiport Switch
Mux
Selector
Sinks
Display
Floating Scope
Scope
Stop Simulation
Terminator
To File
To Workspace
XY Graph
Sources
Constant
Counter Free-Running
Counter Limited
Enumerated Constant
Ground
Pulse Generator
10-8
Supported Blocks
User-Defined Functions
Stateflow
Chart
Truth Table
The Simulink PLC Coder software supports the plclib blocks with the following exceptions. Also,
see “Simulink PLC Coder Structured Text Code Generation Limitations” on page 11-2 for a list of
limitations of the software.
If you get unsupported fixed-point type messages during code generation, update the block
parameter. Open the block parameter dialog box. Navigate to the Signal Attributes and Parameter
Attributes tabs. Check that the Output data type and Parameter data type parameters are not
Inherit: Inherit via internal rule. Set these parameters to either Inherit: Same as
input or a desired non-fixed-point data type, such as double or int8.
If you receive a message about consistency between the original subsystem and the S-function
generated from the subsystem build, and the model contains a Stateflow chart that contains one or
more Simulink functions, use the following procedure to address the issue:
1 Open the model and double-click the Stateflow chart that causes the issue.
10-9
10 Supported Simulink and Stateflow Blocks
To generate PLC code for a model that uses a Data Store Memory block, first define a
Simulink.Signal object in the base workspace. Then, in the Signal Attributes tab of the block
parameters, set the data store name to resolve to that Simulink.Signal object.
For more information, see “Data Stores with Data Store Memory Blocks” (Simulink).
The Simulink PLC Coder software does not support the Simulink Reciprocal Sqrt block signedSqrt
and rSqrt functions.
Simulink PLC Coder has limited support for lookup table blocks. The coder does not support:
Note The Simulink PLC Coder software does not support the Simulink Lookup Table Dynamic block.
For your convenience, the plclib/Simulink/Lookup Tables library contains an implementation of a
dynamic table lookup block using the Prelookup and Interpolation Using Prelookup blocks.
10-10
11
Limitations
• “Simulink PLC Coder Structured Text Code Generation Limitations” on page 11-2
• “Simulink PLC CoderLadder Logic Code Generation Limitations” on page 11-4
11 Limitations
General Limitations
The Simulink PLC Coder software does not support :
• The Simulink PLC Coder software supports code generation only for atomic subsystems.
• The Simulink PLC Coder software supports automatic, inline, or reusable function packaging for
code generation. Nonreusable function packaging is not supported.
• No blocks that require continuous time semantics. This restriction includes continuous
integrators, zero-crossing blocks, physical modeling blocks, and so on.
• No pointer data types.
• No recursion (including recursive events).
• Nonfinite data, for example NaN or Inf, is not supported.
11-2
Simulink PLC Coder Structured Text Code Generation Limitations
11-3
11 Limitations
• Only Rockwell Automation RSLogix 5000 and Studio 5000 IDEs can import ladder logic generated
using the plcladderlib library.
11-4
Simulink PLC CoderLadder Logic Code Generation Limitations
• AOI input argument should be either non-array or 1-D array type. Test bench generation does not
support 2-D or 3-D array types. This limitation includes nested 2-D, 3-D array types in structure
fields.
• AOI input argument in the L5X file should not be single-element array type for runner test bench
generation.
• Test bench generation for Ladder Diagram models containing timer blocks such as TON, TOF and
RTO fails. To generate test-bench code for these models, modify the Ladder Diagram structure
while maintaining the logic.
• If the Simulink model is set as read-only, the model can become corrupted during the test bench
generation process. When the code generation process completes, it reverts all code generation
changes performed on the model. You can ignore or close the model during this process.
“Generating Ladder Diagram Code from Simulink” on page 3-34 | “Import L5X Ladder Files into
Simulink” on page 3-22 | “Modeling and Simulation of Ladder Diagrams in Simulink” on page 3-27 |
“Verify Generated Ladder Diagram Code” on page 3-38
11-5
12
In this section...
“PLC Coder: General Tab Overview” on page 12-2
“Target IDE” on page 12-3
“Show Full Target List” on page 12-5
“Target IDE Path” on page 12-6
“Code Output Directory” on page 12-7
“Generate Testbench for Subsystem” on page 12-7
“Include Testbench Diagnostic Code” on page 12-8
“Generate Functions Instead of Function Block” on page 12-8
“Allow Functions with Zero Inputs” on page 12-9
“Suppress Auto-Generated Data Types” on page 12-9
“Emit Data type Worksheet Tags for PCWorx” on page 12-10
“Aggressively Inline Structured Text Function Calls” on page 12-11
12-2
PLC Coder: General
Configuration
Tip
• In addition to configuring parameters for the Simulink PLC Coder model, you can also use this
dialog box to generate Structured Text code and test bench code for the Subsystem block.
• Certain options are target-specific and are displayed based on the selection for Target IDE.
See Also
Target IDE
Select the target IDE for which you want to generate code. This option is available in the
Configuration Parameters dialog box, PLC Code Generation pane.
The default Target IDE list shows the full set of supported targets. See “Show Full Target List” on
page 12-5.
To see a reduced subset of targets, clear the option Show full target list. To customize this list and
specify IDEs that you use more frequently, use the plccoderpref function.
Settings
3S CoDeSys 2.3
Generates Structured Text (IEC 61131-3) code for 3S-Smart Software Solutions CoDeSys Version
2.3.
3S CoDeSys 3.3
Generates Structured Text code in PLCopen XML for 3S-Smart Software Solutions CoDeSys
Version 3.3.
3S CoDeSys 3.5
Generates Structured Text code in PLCopen XML for 3S-Smart Software Solutions CoDeSys
Version 3.5.
B&R Automation Studio 3.0
Generates Structured Text code for B&R Automation Studio 3.0.
B&R Automation Studio 4.0
Generates Structured Text code for B&R Automation Studio 4.0.
12-3
12 Configuration Parameters for Simulink PLC Coder Models
Tips
• Rockwell Automation RSLogix 5000 routines represent the model hierarchy using hierarchical
user-defined types (UDTs). UDT types preserve model hierarchy in the generated code.
12-4
PLC Coder: General
• The coder generates code for reusable subsystems as separate routine instances. These
subsystems access instance data in program tag fields.
Command-Line Information
Parameter: PLC_TargetIDE
Type: string
Value: 'codesys23' | 'codesys33' | 'codesys35' | 'rslogix5000' |
'rslogix5000_routine' | 'studio5000' | 'studio5000_routine' | 'brautomation30' |
'brautomation40' | 'multiprog50' | 'pcworx60' | 'step7' | 'plcopen' | 'twincat211' |
'twincat3' | 'generic' | 'indraworks' | 'omron' | 'tiaportal' | 'tiaportal_double'
Default: 'codesys23'
See Also
Settings
Default: On
On
The Target IDE list displays the full set of supported IDEs. For more information, see “Supported
IDE Platforms”.
Off
The Target IDE list displays only the more commonly used IDEs. The default subset contains the
following IDEs:
• codesys23 — 3S-Smart Software Solutions CoDeSys Version 2.3 (default) target IDE
• studio5000 — Rockwell Automation Studio 5000 Logix Designer target IDE for AOI format
• step7 — Siemens SIMATIC STEP 7 target IDE
• omron — OMRON Sysmac Studio
• plcopen — PLCopen XML target IDE
You can customize the entries in the reduced Target IDE list by using the plccoderpref
function.
Command-Line Information
Parameter: PLC_ShowFullTargetList
Type: string
Value: 'on' | 'off'
Default: 'on'
You can change the contents of the reduced Target IDE list using the plccoderpref function. See
plccoderpref.
12-5
12 Configuration Parameters for Simulink PLC Coder Models
Settings
Tips
• When you change the Target IDE value, the value of this parameter changes.
• If you right-click the Subsystem block, the PLC Code > Generate and Import Code for
Subsystem command uses this value to import generated code.
• If your target IDE installation is standard, do not edit this parameter. Leave it as the default value.
• If your target IDE installation is nonstandard, edit this value to specify the actual installation path.
• If you change the path and click Apply, the changed path remains for that target IDE for other
models and between MATLAB sessions. To reinstate the factory default, use the command:
plccoderpref('plctargetidepaths','default')
Command-Line Information
See plccoderpref.
12-6
PLC Coder: General
See Also
Settings
Command-Line Information
Parameter: PLC_OutputDir
Type: string
Value: string
Default: 'plcsrc'
Tips
• If the target folder path is empty, a default value of ./plcsrc is used as the Code Output
Directory.
• If, you want to generate code in the current folder use . as the output directory.
• The Code Output Directory can have the same name as your current working folder.
See Also
Settings
Default: off
On
Enables generation of test bench code for subsystem.
Command-Line Information
Parameter: PLC_GenerateTestbench
Type: string
Value: 'on' | 'off'
Default: 'off'
12-7
12 Configuration Parameters for Simulink PLC Coder Models
See Also
Settings
Default: off
On
Enables generation of test bench code with additional diagnostic information.
Command-Line Information
Parameter: PLC_GenerateTestbenchDiagCode
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
This option is available on the PLC Code Generation pane in the Configuration Parameters dialog
box, when the Target IDE is set to Phoenix Contact PC WORX 6.0 or KW-Software
MULTIPROG 5.0.
Settings
Default: off
On
The generated Structured Text code contains Function instead of Function Block where
possible.
12-8
PLC Coder: General
Off
Switch to the default behavior of the software.
Command-Line Information
Parameter: PLC_EmitAsPureFunctions
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
When the Target IDE is set to Phoenix Contact PC WORX 6.0 or KW-Software MULTIPROG
5.0, in the Configuration parameters dialog box, PLC Code Generation pane, this option is
available.
Settings
Default: off
On
The generated Structured Text code contains Function instead of Function Blocks when
there is a function with no inputs.
Off
The generated Structured Text code contains function blocks and no functions.
Command-Line Information
Parameter: PLC_PureFunctionNoInputs
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
12-9
12 Configuration Parameters for Simulink PLC Coder Models
This option is available on the PLC Code Generation pane in the Configuration Parameters dialog
box, when the Target IDE is set to Phoenix Contact PC WORX 6.0 or KW-Software
MULTIPROG 5.0.
Settings
Default: off
On
The software automatically generates named types for array types in your Simulink model.
Off
Switch to the default behavior of the software.
Command-Line Information
Parameter: PLC_SuppressAutoGenType
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
This option is available on the PLC Code Generation pane in the Configuration Parameters dialog
box, when the Target IDE is set to Phoenix Contact PC WORX 6.0.
Settings
Default: off
On
The datatypeWorksheet tags are marked as separate tags in the generated code.
Off
No separate datatypeWorksheet tags are in the generated code.
Command-Line Information
Parameter: PLC_EmitDatatypeWorkSheet
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
12-10
PLC Coder: General
This option is available on the PLC Code Generation pane in the Configuration Parameters dialog
box, when the Target IDE is set to Rockwell Automation targets such as Rockwell Studio 5000:
AOI, Rockwell Studio 5000: Routine, Rockwell RSLogix 5000: AOI, or Rockwell
RSLogix 5000: Routine.
Settings
Default: off
On
Aggressively inlines Structured Text function calls for RSLogix IDE.
Off
Reverts to its default behavior and inlines only math function calls in the generated code.
Command-Line Information
Parameter:PLC_EnableAggressiveInlining
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
12-11
12 Configuration Parameters for Simulink PLC Coder Models
In this section...
“Comments Overview” on page 12-12
“Include Comments” on page 12-12
“Include Block Description” on page 12-13
“Simulink Block / Stateflow Object Comments” on page 12-14
“Show Eliminated Blocks” on page 12-14
Comments Overview
Control the comments that the Simulink PLC Coder software automatically creates and inserts into
the generated code.
See Also
Include Comments
Specify which comments are in generated files. This option is available on the PLC Code Generation
> Comments pane in the Configuration Parameters dialog box.
12-12
PLC Coder: Comments
Settings
Default: on
On
Places comments in the generated files based on the selections in the Auto generated
comments pane.
If you create links to requirements documents from your model using the Simulink Requirements
software, the links also appear in generated code comments.
Off
Omits comments from the generated files.
Command-Line Information
Parameter: PLC_RTWGenerateComments
Type: string
Value: 'on' | 'off'
Default: 'on'
See Also
Settings
Default: on
On
Places comments in the generated files based on the contents of the block properties General
tab.
Off
Omits block descriptions from the generated files.
Command-Line Information
Parameter: PLC_PLCEnableBlockDescription
Type: string
Value: 'on' | 'off'
Default: 'on'
See Also
12-13
12 Configuration Parameters for Simulink PLC Coder Models
Settings
Default: on
On
Inserts automatically generated comments that describe block code and objects. The comments
precede that code in the generated file.
Off
Suppresses comments.
Command-Line Information
Parameter: PLC_RTWSimulinkBlockComments
Type: string
Value: 'on' | 'off'
Default: 'on'
See Also
Settings
Default: off
On
Inserts statements in the generated code from blocks eliminated as the result of optimizations
(such as parameter inlining).
Off
Suppresses statements.
Command-Line Information
Parameter: PLC_RTWShowEliminatedStatement
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
12-14
PLC Coder: Optimization
In this section...
“Optimization Overview” on page 12-15
“Default Parameter Behavior” on page 12-16
“Signal Storage Reuse” on page 12-17
“Remove Code from Floating-Point to Integer Conversions That Wraps Out-Of-Range Values” on page
12-17
“Generate Reusable Code” on page 12-18
“Inline Named Constants” on page 12-19
“Reuse MATLAB Function Block Variables” on page 12-20
“Loop Unrolling Threshold” on page 12-20
Optimization Overview
Select the code generation optimization settings.
See Also
12-15
12 Configuration Parameters for Simulink PLC Coder Models
Description
Transform numeric block parameters into constant inlined values in the generated code.
Category: Optimization
Settings
Inlined
Set Default parameter behavior to Inlined to reduce global RAM usage and increase
efficiency of the generated code. The code does not allocate memory to represent numeric block
parameters such as the Gain parameter of a Gain block. Instead, the code inlines the literal
numeric values of these block parameters.
Tunable
Set Default parameter behavior to Tunable to enable tunability of numeric block parameters
in the generated code. The code represents numeric block parameters and variables that use the
storage class Auto, including numeric MATLAB variables, as tunable fields of a global parameters
structure.
Tips
• Whether you set Default parameter behavior to Inlined or to Tunable, create parameter data
objects to preserve tunability for block parameters. For more information, see “Create Tunable
Calibration Parameter in the Generated Code” (Simulink Coder).
• When you switch from a system target file that is not ERT-based to one that is ERT-based, Default
parameter behavior sets to Inlined by default. However, you can change the setting of Default
parameter behavior later.
• When a top model uses referenced models, or if a model is referenced by another model:
• All referenced models must set Default parameter behavior to Inlined if the top model has
Default parameter behavior set to Inlined.
• The top model can specify Default parameter behavior as Tunable or Inlined.
• If your model contains an Environment Controller block, you can suppress code generation for the
branch connected to the Sim port if you set Default parameter behavior to Inlined and the
branch does not contain external signals.
Command-Line Information
Parameter:PLC_PLCEnableVarReuse
Type: string
Value: 'on' | 'off'
Default: 'on'
12-16
PLC Coder: Optimization
See Also
Settings
Default: on
On
Reuses memory buffers allocated to store block input and output signals, reducing the memory
requirement of your real-time program.
Off
Allocates a separate memory buffer for each block's outputs. This allocation makes block outputs
global and unique, which in many cases significantly increases RAM and ROM usage.
Tips
Command-Line Information
Parameter:PLC_PLCEnableVarReuse
Type: string
Value: 'on' | 'off'
Default: 'on'
See Also
12-17
12 Configuration Parameters for Simulink PLC Coder Models
Settings
Default: on
On
Removes code from floating-point to integer conversions.
Off
Does not remove code from floating-point to integer conversions.
Tips
Command-Line Information
Parameter: PLC_PLCEnableEfficientCast
Type: string
Value: 'on' | 'off'
Default: 'on'
See Also
This option is available on the PLC Code Generation > Optimization pane in the Configuration
Parameters dialog box.
Settings
Default: off
On
Generates better reusable code for reusable subsystems.
Off
Reverts to its default behavior. Instead of a single reusable function block, the software generates
separate function blocks for individual instances of a reusable subsystem because of certain
differences in their inputs.
Tips
• If you find multiple function blocks in your generated code for multiple instances of the same
subsystem, select this option. The software performs better identification of whether two
12-18
PLC Coder: Optimization
instances of a subsystem are actually the same and whether it can combine the multiple blocks
into one reusable function block.
• If different instances of a subsystem have different values of a block parameter, you cannot
generate reusable code. Clear this option or use the same block parameter for all instances.
• Despite selecting this option, if you do not see reusable code for different instances of a
subsystem, you can determine the reason. To determine if two reusable subsystems are identical,
the code generator internally uses a checksum value. You can compare the checksum values for
two instances of a subsystem and investigate why they are not identical.
To get the checksum values for the two instances that you expect to be identical, use the function
Simulink.SubSystem.getChecksum. If the checksum values are different, investigate the
checksum details to see why the values are not identical.
Command-Line Information
Parameter:PLC_GenerateReusableCode
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
This option is available on the PLC Code Generation > Optimization pane in the Configuration
Parameters dialog box.
Settings
Default: off
On
Inlines named constants.
Off
Reverts to its default behavior and uses named constants in the generated code.
Command-Line Information
Parameter:PLC_InlineNamedConstant
Type: string
Value: 'on' | 'off'
Default: 'off'
12-19
12 Configuration Parameters for Simulink PLC Coder Models
See Also
This option is available on the PLC Code Generation > Optimization pane in the Configuration
Parameters dialog box.
Settings
Default: off
On
Generates code that reuses MATLAB Function block variables where appropriate.
Off
Reverts to its default behavior and does not reuse variables in the generated code.
Command-Line Information
Parameter:PLC_ReuseMLFcnVariable
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
Settings
Default: 5
Specify the array size at which the code generator begins to use a for loop instead of separate
assignment statements to assign values to the elements of a signal or parameter array.
When the loops are perfectly nested loops, the code generator uses a for loop if the product of the
loop counts for all loops in the perfect loop nest is greater than or equal to this threshold.
12-20
PLC Coder: Optimization
Command-Line Information
Parameter: PLC_RollThreshold
Type: string
Value: any valid value
Default: '5'
See Also
12-21
12 Configuration Parameters for Simulink PLC Coder Models
In this section...
“Identifiers Overview” on page 12-23
“Use Subsystem Instance Name as Function Block Instance Name” on page 12-23
“Override Target Default Maximum Identifier Length” on page 12-23
“Maximum Identifier Length” on page 12-24
“Override Target Default enum Name Behavior” on page 12-25
“Generate enum Cast Function” on page 12-25
“Remove Top-level Subsystem Ssmethod Type” on page 12-26
“Keep Top-Level ssmethod Name the Same As Non-Top Level” on page 12-26
“Generate Logging Code” on page 12-27
“Use the Same Reserved Names as Simulation Target” on page 12-27
12-22
PLC Coder: Identifiers
In this section...
“Reserved Names” on page 12-28
“Externally Defined Identifiers” on page 12-28
“Preserve Alias Type Names for Data Types” on page 12-29
Identifiers Overview
Select the automatically generated identifier naming rules.
See Also
This option is available on the PLC Code Generation > Identifiers pane in the Configuration
Parameters dialog box.
Settings
Default: off
On
Uses the subsystem instance name as the name of the Function block instances in the generated
code.
Off
Uses auto-generated index-based instance names for the Function blocks in the generated code.
Command-Line Information
Parameter: PLC_FBUseSubsystemInstanceName
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
12-23
12 Configuration Parameters for Simulink PLC Coder Models
This option is available on the PLC Code Generation > Identifiers pane in the Configuration
Parameters dialog box.
Settings
Default: off
On
Override target default maximum identifier length in the generated code.
Off
The generated code uses the default identifier length of the target IDE.
Command-Line Information
Parameter: PLC_OverrideDefaultNameLength
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
Settings
Default: 31
Minimum: 31
Maximum: 256
You can use this parameter to limit the number of characters in function, type definition, and variable
names. Many target IDEs have their own restrictions for these names. Simulink PLC Coder complies
with target IDE limitations.
Command-Line Information
Parameter: PLC_RTWMaxIdLength
Type: int
Value: 31 to 256
Default: 31
See Also
12-24
PLC Coder: Identifiers
This option is available on the PLC Code Generation > Identifiers pane in the Configuration
Parameters dialog box.
Settings
Default: off
On
Override target default enum behavior and always have enum names instead of enum values.
Off
The generated code uses the enum behavior of the target IDE.
Command-Line Information
Parameter: PLC_GenerateEnumSymbolicName
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
This option is available in the Configuration Parameters dialog box, PLC Code Generation >
Identifiers pane .
Settings
Default: off
On
Simulink PLC Coderautogenerates the enum type conversion code.
Off
Manually create a MATLAB function to convert the enum type value to an integer or to convert an
integer to an enum type value.
Command-Line Information
Parameter: PLC_GenerateEnumCastFunction
Type: string
Value: 'on' | 'off'
Default: 'off'
12-25
12 Configuration Parameters for Simulink PLC Coder Models
See Also
This option is available on the PLC Code Generation > Identifiers pane in the Configuration
Parameters dialog box.
Settings
Default: off
On
Remove top level function block ssmethod type in generated code.
Off
Generated code contains ssmethod type Function block and switch case statements.
Command-Line Information
Parameter: PLC_RemoveTopFBSSMethodType
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
This option is available on the PLC Code Generation > Identifiers pane in the Configuration
Parameters dialog box.
Settings
Default: off
On
Generated code for top-level block does not contain the SS_STEP type in generated code.
Off
Generated code contains SS_STEP AND SS_OUTPUT type function blocks.
12-26
PLC Coder: Identifiers
Command-Line Information
Parameter: PLC_RemoveSSStep
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
This option is available on the PLC Code Generation > Identifiers pane in the Configuration
Parameters dialog box.
Settings
Default: off
On
Generate Function block logging code for supported targets.
Off
No logging instrumentation is included in the generated code.
Command-Line Information
Parameter: PLC_GenerateLoggingCode
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
Settings
Default: off
12-27
12 Configuration Parameters for Simulink PLC Coder Models
On
Uses the same reserved names as those specified in the Reserved names filed of the Simulation
Target pane in the Configuration Parameters dialog box.
Off
Does not use the same reserved names as those specified in the Simulation Target >
Identifiers pane pane.
Command-Line Information
Parameter: PLC_RTWUseSimReservedNames
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
Reserved Names
Enter the names of variables or functions in the generated code that you do not want to be used. This
option is available on the PLC Code Generation > Identifiers pane in the Configuration Parameters
dialog box.
Settings
Default: ( )
Changes the names of variables or functions in the generated code to avoid name conflicts with
identifiers in custom code. Reserved names must be fewer than 256 characters in length.
Tips
Command-Line Information
Parameter: PLC_RTWReservedNames
Type: string
Value: string
Default: ''
See Also
12-28
PLC Coder: Identifiers
Settings
Default: ( )
Suppresses the definition of identifiers, such as those for function blocks, variables, constants, and
user types in the generated code. This suppression allows the generated code to refer to these
identifiers. When you import the generated code into the PLC IDE, you must provide these
definitions.
Tips
Command-Line Information
Parameter: PLC_ExternalDefinedNames
Type: string
Value: string
Default: ''
See Also
Using the Simulink.AliasType class, you can create an alias for a built-in Simulink data type. If
you assign an alias data type to signals and parameters in your model, when you use this option, the
generated code uses your alias data type to define variables corresponding to the signals and
parameters.
For instance, you can create an alias SAFEBOOL from the base data type boolean. If you assign the
type SAFEBOOL to signals and parameters in your model, the variables in the generated code
corresponding to those signals and parameters also have the type SAFEBOOL. Using this alias type
SAFEBOOL, you can conform to PLCopen safety specifications that suggest using safe data types for
differentiation between safety-relevant and standard signals.
Settings
Default: off
On
The generated code preserves alias data types from your model.
12-29
12 Configuration Parameters for Simulink PLC Coder Models
For your generated code to be successfully imported to your target IDE, the IDE must support
your alias names.
Off
The generated code does not preserve alias types from your model. Instead, the base type of the
Simulink.AliasType class determines the variable data type in generated code.
Tips
The alias that you define for a Simulink type must have the same semantic meaning as the base
Simulink type. It must not be a data type already supported in Structured Text and semantically
different from the base Simulink type. For instance, WORD is a data type supported in Structured Text
but is semantically different from an integer type. If you define an alias WORD for a Simulink built-in
integer type, for instance uint16, and preserve the alias name, the type WORD that appears in your
generated code is used semantically as a WORD and not as an INT. The generated code has a different
meaning from the semantics of the model.
Command-Line Information
Parameter: PLC_PreserveAliasType
Type: string
Value: 'on' | 'off'
Default: 'off'
12-30
PLC Coder: Report
In this section...
“Report Overview” on page 12-31
“Generate Traceability Report” on page 12-32
“Generate Model Web View” on page 12-32
“Open Report Automatically” on page 12-33
Report Overview
After code generation, specify whether a report must be produced. Control the appearance and
contents of the report.
The code generation report shows a mapping between Simulink model objects and locations in the
generated code. The report also shows static code metrics about files, global variables, and function
blocks.
12-31
12 Configuration Parameters for Simulink PLC Coder Models
See Also
Settings
Default: on
On
Creates code generation report as an HTML file.
Off
Suppresses creation of code generation report.
Command-Line Information
Parameter: PLC_GenerateReport
Type: string
Value: 'on' | 'off'
Default: 'on'
See Also
Simulink PLC Coder does not generate a traceability report file when generating Ladder Diagrams
from Stateflow charts. However, traceability report file is generated when generating Structured Text
from Stateflow charts.
Ladder Diagrams. charts. However, traceability report file is generated when generating Structured
Text from charts.
You can share your model and generated code outside of the MATLAB environment. You must have a
Simulink Report Generator to include a Web view (Simulink Report Generator) of the model in the
code generation report.
Settings
Default: Off
12-32
PLC Coder: Report
On
Includes model Web view in the code generation report.
Off
Omits model Web view in the code generation report.
Command-Line Information
Parameter: PLC_GenerateWebView
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
Settings
Default: off
On
Opens the code generation report as an HTML file.
Off
Suppresses opening of the code generation report.
Command-Line Information
Parameter: PLC_LaunchReport
Type: string
Value: 'on' | 'off'
Default: 'off'
See Also
12-33
13
External Mode
For Rockwell Automation targets, you can set up an Open Platform Communications (OPC) server and
use the Simulation Data Inspector in Simulink to visualize and monitor the logging data. The OPC
Toolbox™ is required to run the external mode visualization.
See Also
More About
• “Generate Structured Text Code with Logging Instrumentation” on page 13-3
• “Use the Simulation Data Inspector to Visualize and Monitor the Logging Data” on page 13-7
13-2
Generate Structured Text Code with Logging Instrumentation
The example in this topic shows generated code for the Rockwell Automation Studio 5000 IDE.
Generated code for other IDE platforms looks different.
1 Create a Simulink model ext_demo1.slx containing a top-level subsystem with two child
subsystems S1, S2, a MATLAB Function block and a Stateflowchart.
2 The S1, S2 blocks are identical and contain simple feedback loop.The Stateflow chart contains a
simple state machine.
13-3
13 External Mode
function y = fcn
persistent i;
if isempty(i)
i=0;
end
if (i>20)
i = 0;
else
i=i+1;
end
y = sin(pi*i/10);
4 Select the top-level subsystem and open the configuration parameters window. On the PLC Code
Generation pane, select the Target IDE as Rockwell Studio 5000: AOI. On the Identifiers
pane, select Generate logging code.
13-4
Generate Structured Text Code with Logging Instrumentation
5 In the model, select the top subsystem block, right-click, and choose PLC Code>Generate Code
for Subsystem.
This operation generates L5X AOI code for the top subsystem block and the children S1, S2,
MATLAB function, and Stateflow chart blocks. In the code folder, it also generates
plc_log_data.mat which has the logging data information.
13-5
13 External Mode
6 After generating the code, you can download and run the logging code from the PLC IDE.
See Also
More About
• “External Mode Logging” on page 13-2
• “Use the Simulation Data Inspector to Visualize and Monitor the Logging Data” on page 13-7
13-6
Use the Simulation Data Inspector to Visualize and Monitor the Logging Data
1 Start the Studio 5000 IDE and create project with the name ext_demo1.
2 Import the generated ext_demo.L5X to the Add-On Instructions tree node of the project.
3 In the MainProgram node, delete the ladder MainRoutine and create an ST MainRoutine
node.
6 Double-click MainRoutine tree node and type in the following code. The statement
Subsystem(i0_Subsystem, 23, Y1, Y2, Y3, i0_Subsystem_val) calls the logging
method (ssmethod value=23) to log in data to the i0_Subsystem_val tag.
13-7
13 External Mode
7 Compile the project in Studio 5000 IDE, connect, and download to the PLC target.
Use PLC External Mode Commands to Stream and Display Live Log
Data
After the RSLinx OPC Server is configured, you can use the PLC external mode commands to connect
to the server, stream, and display live logging data on the Simulink Data Inspector. The log data
information is in the plc_log_data.mat file which can be found in plcsrc folder. You can use the
plcdispextmodedata function to display the contents of the MAT-file. In the MATLAB command,
type:
>>cd plcsrc
>>plcdispextmodedata plc_log_data.mat
13-8
Use the Simulation Data Inspector to Visualize and Monitor the Logging Data
Log data:
#1: Y1: LREAL
#2: Y2: LREAL
#3: Y3: LREAL
#4: io_Chart.out: DINT
#5: io_Chart.ChartMode: DINT
#6: io_Chart.State_A: BOOL
#7: io_Chart.State_B: BOOL
#8: io_Chart.State_C: BOOL
#9: io_Chart.State_D: BOOL
#10: io_Chart.is_active_c3_Subsystem: USINT
#11: io_MATLABFunction.y: LREAL
#12: io_MATLABFunction.i: LREAL
#13: io_S1.y: LREAL
#14: io_S1.UnitDelay_DSTATE: LREAL
#15: i1_S1.y: LREAL
#16: i1_S1.UnitDelay_DSTATE: LREAL
The format for the log data information is index number, name, and type. The log data for non-top
subsystem function block output and state variables are named using the dot notation to represent
the function block instances that own the data. The index and name of the log data can be used with
the plcrunextmode command to specify a subset of log data for streaming and visualization.
Use the plcrunextmode function to connect to the OPC server and stream log data. For example,
executing plcrunextmode ('localhost', 'studio5000', 'ext_demo1',
'plc_log_data.mat'); command streams live log data for the example model in to Simulink Data
Inspector.
The plcrunextmode command continues to run and stream log data. To exit streaming, type Ctrl-C
in MATLAB to stop.
See Also
plcdispextmodedata | plcrunextmode
More About
• “External Mode Logging” on page 13-2
• “Generate Structured Text Code with Logging Instrumentation” on page 13-3
13-9
14
• Instructions that are implemented in Simulink using ladder diagram blocks with same name
• Instructions that are implemented in Simulink using other ladder diagram blocks.
14-2
Instructions Supported in Ladder Diagram
The special instructions that are implemented using another block in Simulink are:
14-3
15
15-2
16
Block Parameters
1 If the block in the subsystem has a Signal Attributes tab, navigate to that tab.
2 For the Integer rounding mode parameter, select Round.
3 Clear the Saturate on integer overflow check box.
4 For the Output data type parameter, select a fixed-point data type.
5 Click the Data Type Assistant button.
6 For the Word length parameter, enter 8, 16, or 32.
7 For the Mode parameter, select Fixed point.
8 For the Scaling parameter, select Binary point.
9 Click OK.
16-2
Model Parameters
Model Parameters
1 In model Configuration Parameters dialog box, click the Hardware Implementation node.
2 For the Device vendor parameter, select Generic.
3 For the Device type, select Custom.
4 For the Signed integer division rounds to, select Zero.
5 For the Number of bits, set char to 16.
16-3
16 Fixed Point Code Generation
Limitations
1 64-bit fixed-point data type is not supported.
16-4
17
• Solver options that are recommended or required for PLC code generation:
• Type:Fixed-step.
• Solver:Discrete(no continuous states). Other fixed-step solvers could be selected, but
this option is usually best for simulating discrete systems.
• Tasking mode: Must be explicitly set to SingleTasking. Do not set Tasking modeto Auto
• Change any continuous time signals in the top level subsystem to use discrete fixed sample times.
When you deploy code generated from a multirate model, you must run the code at the fundamental
sample rate.
Limitations
These are the limitations when generating Structured Text from multirate models:
• The B&R Automation Studio IDE is not supported for multirate model code generation.
17-2
18
• “Configuring the rand function for PLC Code generation” on page 18-2
• “Width block requirements for PLC Code generation” on page 18-3
• “Workspace Parameter Data Type Limitations” on page 18-4
• “Limitations” on page 18-5
18 Generating PLC Code for MATLAB Function Block
• 3S-Smart Software Solutions CODESYS Version 2.3 or 3.3 or 3.5 (SP4 or later)
• B&R Automation Studio 3.0 or 4.0
• Beckhoff TwinCAT 2.11 or 3
• OMRON Sysmac Studio Version 1.04, 1.05, 1.09 or 1.12
• Rexroth IndraWorks version 13V12 IDE
• Generic
• PLCopen XML
18-2
Width block requirements for PLC Code generation
18-3
18 Generating PLC Code for MATLAB Function Block
If you specify the type of the Simulink.Parameter object by using the DataType property, use a
typed expression when assigning a value to the parameter object. For example, if the
Simulink.Parameter object K1 is used to store a value of the type single, use a typed expression
such as single(0.3) when assigning a value to K1.
K1 = Simulink.Parameter;
K1.Value = single(0.3);
K1.StorageClass = 'ExportedGlobal';
K1.DataType = 'single';
18-4
Limitations
Limitations
These are the limitations when generating Structured Text from MATLAB Fubnction blocks :
18-5
19
• “Fixed Point Simulink PLC Coder Structured Text Code Generation” on page 19-2
• “Generating Simulink PLC Coder Structured Text Code For Multirate Models” on page 19-6
• “MATLAB Function Block Simulink PLC Coder Structured Text Code Generation” on page 19-8
19 Model Architecture and Design
In this section...
“Block Parameters” on page 19-2
“Model Parameters” on page 19-3
“Limitations” on page 19-4
Block Parameters
At the MATLAB command prompt type plcdemo_fixed_point. Once the example model opens ,
follow these instructions to configure the model for Structured Text code generation.
1 If the block in the subsystem has a Signal Attributes tab, navigate to that tab and jump to step
3.
2 If there are no blocks in the subsystem with a Signal Attributes tab use the Data Type
Conversion block. Add the Data Type Conversionblock to the model and continue to the next
step.
3 For the Integer rounding mode parameter, select Round.
4 Clear the Saturate on integer overflow check box.
5 For the Output data type parameter, select a fixed-point data type.
6 Click the Data Type Assistant button .
7 For the Word length parameter, enter 8, 16, or 32.
8 For the Mode parameter, select Fixed point.
9 For the Scaling parameter, select Binary point.
19-2
Fixed Point Simulink PLC Coder Structured Text Code Generation
10 Click OK.
Model Parameters
1 In the Model Configuration Parameters dialog box, click the Hardware Implementation node.
2 For the Device vendor parameter, select Generic or Custom Processor. If you select Custom
Processor proceed to step 4.
3 For the Device type, select Custom.
4 For the Signed integer division rounds to, select Zero.
5 For the Number of bits, set char to 16.
19-3
19 Model Architecture and Design
Limitations
• 64 bit fixed-point data type not supported.
19-4
Fixed Point Simulink PLC Coder Structured Text Code Generation
19-5
19 Model Architecture and Design
Before generating Structured Text from a multirate model, you must configure the model as follows:
• Solver options that are recommended or required for PLC code generation:
• Type:Fixed-step.
• Solver:Discrete(no continuous states). Other fixed-step solvers could be selected, but
this option is usually best for simulating discrete systems.
• Tasking mode: Must be explicitly set to Single Tasking. Do not set Tasking modeto Auto
• Change any continuous time input signals in the top level subsystem to use discrete fixed sample
times.
• In the top-level model, right-click the Subsystem block and select Block Parameters
(Subsystem).
• In the resulting block dialog box, select Treat as atomic unit.
19-6
Generating Simulink PLC Coder Structured Text Code For Multirate Models
When you deploy code generated from a multirate model, you must run the code at the fundamental
sample rate.
Limitations
The B&R Automation Studio does not support structured text code generation from multirate models.
• “Check System Compatibility for Structured Text Code Generation” on page 1-6
• “Generate and Examine Structured Text Code” on page 1-9
19-7
19 Model Architecture and Design
• 3S-Smart Software Solutions CODESYS Version 2.3 or 3.3 or 3.5 (SP4 or later)
• B&R Automation Studio 3.0 or 4.0
• Beckhoff TwinCAT 2.11 or 3
• OMRON Sysmac Studio Version 1.04, 1.05, 1.09 or 1.12
• Rexroth IndraWorks version 13V12 IDE
• PLCopen XML
If you specify the type of the Simulink.Parameter object by using the DataType property, use a
typed expression when assigning a value to the parameter object. For example, if the
Simulink.Parameter object K1 stores a value of the type single, use a typed expression such as
single(0.3) when assigning a value to K1.
K1 = Simulink.Parameter;
K1.Value = single(0.3);
K1.StorageClass = 'ExportedGlobal';
K1.DataType = 'single';
Limitations
When generating structured text from MATLAB Function blocks, these are the limitations :
19-8
MATLAB Function Block Simulink PLC Coder Structured Text Code Generation
19-9
20
Using Simulink PLC Coder, you can generate structured text and test bench code, and then import
the generated code into the target IDE.
Learning Objectives
In this tutorial you learn how to:
• Open the plcdemo_simple_subsystem model and prepare the model for code generation.
• Verify the code that you generated.
• Automatically or manually import your generated code into your target IDE.
Prerequisites
• Simulink PLC Coder
• Target IDE folder location (for automatic import).
Workflow
1 Open the plcdemo_simple_subsystem model.
2 Open the model settings and set Solver Selection to Fixed-step and Solver to discrete(no
continuous states).
3 If your target IDE is in the “PLC IDEs That Qualify for Importing Code Automatically” on page 1-
17 , see “Generate and Automatically Import Structured Text Code” on page 1-17. Otherwise ,
see “Importing Generated Structured Text Code Manually” on page 20-2
1 Right-click the Subsystem block and select PLC Code > Options.
20-2
Deploy Structured Text
2 On the PLC Code Generation pane, select an option from the Target IDE list, for example, 3S
CoDeSys 2.3.
The default Target IDE list displays the full set of supported IDEs. To see a reduced subset of the
target IDEs supported by Simulink PLC Coder, disable the option Show full target list. To
customize this list, use the plccoderpref function.
3 Click Apply.
4 Click Generate code.
This button:
• Generates Structured Text code (same as the PLC Code > Generate Code for Subsystem
option)
• Stores generated code in model_name.exp (for example,
plcdemo_simple_subsystem.exp)
When code generation is complete, a View diagnostics hyperlink appears at the bottom of the
model window. Click this hyperlink to open the Diagnostic Viewer window.
20-3
20 PLC Coder Code Deployment
This window has links that you can click to open the associated files. For more information, see
“Files Generated with Simulink PLC Coder” on page 1-14.
5 To import generated code into your target IDE import the generated files manually into your
target IDE.
20-4
Deploy Ladder Diagram
UsingSimulink PLC Coder you can generate Structured Text, along with test bench code and import
the generated code into the target IDE.
Learning Objectives
In this tutorial you will learn how to:
• Open the plcdemo_ladder_timers model and prepare the model for code generation.
• Verify the code you generated.
• Have your generated code either automatically or manually imported into your target IDE.
Prerequisites
• Simulink PLC Coder
• You have access to either Rockwell Automation RSLogix 5000 or Studio 5000 IDE.
Workflow
1 Open the plcdemo_ladder_timers model.
2 Open the model settings and set Solver Selection to Fixed-step and Solver to discrete(no
continuous states).
3 See “Importing Generated Ladder Diagram Code Manually” on page 20-5
You can manually import the generated L5X file into RSLogix 5000 or Studio 5000 IDEs.
1 Right-click the Motor Controller block and select PLC Code > Options.
20-5
20 PLC Coder Code Deployment
2 On the PLC Code Generation pane, from the Target IDE list, select either Rockwell Studio
5000:AOI or Rockwell RSLogix5000:AOI.
3 In Target IDE Path, enter the path to the folder where you want the generated L5X file to be
saved. In, Code Output Directory, enter the name of the folder to save the generated L5X file.
4 Click Apply.
5 Right-click the Motor Controller block and select PLC CodeGenerate Code for
Subsystem .
6 Upon, completion of code generation the Diagnostic window displays a message with the path to
the generated L5X file.
20-6
Deploy Ladder Diagram
20-7
21
• “Structured Text Code Generation Support for Simulink Data Dictionary” on page 21-2
• “Generate Structured Text Code For Simulink Data Dictionary Defined Model Parameters”
on page 21-3
21 Simulink PLC Coder Structured Text Code Generation For Simulink Data Dictionary (SLDD)
Limitations
Simulink PLC Coder does not support:
• The mixed use of the base workspace and SLDD files. Use the Simulink migration utility to
migrate your entire base workspace to SLDD files.
• Model workspace parameters and signals for code generation.
• MATLAB variables in SLDD files for code generation. To generate code convert these variables to
Simulink.Parameter objects.
Simulink.parameter types that have StorageClass options other than ExportedGlobal and
ImportedExtern are auto converted to ExportedGlobal StorageClass during code generation.
See Also
More About
• “What Is a Data Dictionary?” (Simulink)
• “Generate Structured Text Code For Simulink Data Dictionary Defined Model Parameters” on
page 21-3
• Simulink.Parameter
• Simulink.Signal
21-2
Generate Structured Text Code For Simulink Data Dictionary Defined Model Parameters
Learning Objectives
In this tutorial, you learn how to:
• Open the plcdemo_tunable_params model and migrate the model to use Simulink Data
Dictionary (SLDD).
• Generate code for the model.
Requirements
• Base workspace variable definition must match the variable definition in the SLDD file. If there is
a mismatch, Simulink PLC Coder displays an error during the code generation process.
• If your model has a Data Store Memory(DSM) object, you must have a matching
Simulink.Signal object in the SLDD file.
Workflow
Migrate the plcdemo_tunable_params model base workspace variables to an SLDD file for code
generation:
Note Copy the plcdemo_tunable_params model to your current working directory prior to
starting the workflow.
21-3
21 Simulink PLC Coder Structured Text Code Generation For Simulink Data Dictionary (SLDD)
10
To open the dictionary, in the Simulink Editor, click the model data badge in the bottom left
corner, then click the External Data link. To inspect the contents of the dictionary, in the Model
Explorer Model Hierarchy pane, under the External Data node, expand the dictionary node.
To generate code for the model, see “Generate and Examine Structured Text Code” on page 1-9 .
See Also
More About
• Simulink.Parameter
• Simulink.Signal
• Data Store Memory
• “Migrate Models to Use Simulink Data Dictionary” (Simulink)
• “Structured Text Code Generation Support for Simulink Data Dictionary” on page 21-2
21-4
22
• “Structured Text Code Generation Support for Enumerated Data Type Conversion”
on page 22-2
• “IDE Limitations” on page 22-4
22 Simulink PLC Coder Structured Text Code Generation For Enumerated Data Type
For this example, the myEnum.m script loads the enum class definition. Place this script file in the
same project folder as the menum_cast_enum_convert_int model file.
To open the Simulink test bench model, use the following command.
open_system('menum_cast_enum_convert_int')
To auto generate structured text code for the enum to int conversion, use “Generate enum Cast
Function” on page 12-25.
22-2
Structured Text Code Generation Support for Enumerated Data Type Conversion
4 Click OK.
generatedfiles = plcgeneratecode('menum_cast_enum_convert_int/Subsystem');
See Also
More About
• “Use Enumerated Data in Simulink Models” (Simulink)
• “Code Generation for Enumerations” (Simulink)
22-3
22 Simulink PLC Coder Structured Text Code Generation For Enumerated Data Type
IDE Limitations
The following IDEs support enum data type:
• 3S-Smart Software Solutions CODESYS Version 2.3 or 3.3 or 3.5 (SP4 or later). To generate code
enable “Generate enum Cast Function” on page 12-25 option.
• PHOENIX CONTACT Software MULTIPROG 5.0 or 5.50. To generate code enable “Override Target
Default enum Name Behavior” on page 12-25 and “Generate enum Cast Function” on page 12-25
options.
• Selectron CAP1131 IDE. To generate code enable “Override Target Default enum Name Behavior”
on page 12-25 and “Generate enum Cast Function” on page 12-25 options.
• Beckhoff TwinCAT 2.11 or 3. To generate code enable “Override Target Default enum Name
Behavior” on page 12-25 and “Generate enum Cast Function” on page 12-25 options.
• Rexroth IndraWorks version 13V12 IDE. To generate code enable “Override Target Default enum
Name Behavior” on page 12-25 and “Generate enum Cast Function” on page 12-25 options.
See Also
22-4
23
Open model
open_system('mSystemIntegration');
23-2
Use PLC_RemoveSSStep for Distributed Code Generation
23-3
23 Distributed Code Generation with Simulink PLC Coder
To autogenerate structured text code with the same ssMethod type for every component of your
model for external code integration later on, use “Keep Top-Level ssmethod Name the Same As Non-
Top Level” on page 12-26 function.
Code Generation
plcgeneratecode('mSystemIntegration/TopSystem/SubSystem1');
plcgeneratecode('mSystemIntegration/TopSystem/SubSystem2');
plcgeneratecode('mSystemIntegration/TopSystem/SubSystem3');
plcgeneratecode('mSystemIntegration/TopSystem');
23-4
Use PLC_RemoveSSStep for Distributed Code Generation
23-5
23 Distributed Code Generation with Simulink PLC Coder
To open the Simulink test bench model, use the following command.
open_system('mSubSysRefSystemIntegration')
23-6
Structured Text Code Generation for Subsystem Reference Blocks
generatedfiles = plcgeneratecode('mSubSysRefSystemIntegration/TopSystem');
See Also
More About
• “Subsystem Reference” (Simulink)
• “Distributed Code Generation Limitations” on page 23-8
23-7
23 Distributed Code Generation with Simulink PLC Coder
See Also
23-8