0% found this document useful (0 votes)
336 views286 pages

Simulink PLC Coder User's Guide

Uploaded by

peerawish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
336 views286 pages

Simulink PLC Coder User's Guide

Uploaded by

peerawish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 286

Simulink® PLC Coder™

User's Guide

R2020a
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


1 Apple Hill Drive
Natick, MA 01760-2098
Simulink® PLC Coder™ User's Guide
© COPYRIGHT 2010–2020 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied
only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form
without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through
the federal government of the United States. By accepting delivery of the Program or Documentation, the government
hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer
software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014.
Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain
to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government) and shall
supersede any conflicting contractual terms or conditions. If this License fails to meet the government's needs or is
inconsistent in any respect with federal procurement law, the government agrees to return the Program and
Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be
trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for
more information.
Revision History
March 2010 Online only New for Version 1.0 (Release 2010a)
September 2010 Online only Revised for Version 1.1 (Release 2010b)
April 2011 Online only Revised for Version 1.2 (Release 2011a)
September 2011 Online only Revised for Version 1.2.1 (Release 2011b)
March 2012 Online only Revised for Version 1.3 (Release 2012a)
September 2012 Online only Revised for Version 1.4 (Release 2012b)
March 2013 Online only Revised for Version 1.5 (Release 2013a)
September 2013 Online only Revised for Version 1.6 (Release 2013b)
March 2014 Online only Revised for Version 1.7 (Release 2014a)
October 2014 Online only Revised for Version 1.8 (Release 2014b)
March 2015 Online only Revised for Version 1.9 (Release 2015a)
September 2015 Online only Revised for Version 2.0 (Release 2015b)
March 2016 Online only Revised for Version 2.1 (Release 2016a)
September 2016 Online only Revised for Version 2.2 (Release 2016b)
March 2017 Online only Revised for Version 2.3 (Release 2017a)
September 2017 Online only Revised for Version 2.4 (Release 2017b)
March 2018 Online only Revised for Version 2.5 (Release 2018a)
September 2018 Online only Revised for Version 2.6 (Release 2018b)
March 2019 Online only Revised for Version 3.0 (Release 2019a)
September 2019 Online only Revised for Version 3.1 (Release 2019b)
March 2020 Online only Revised for Version 3.2 (Release 2020a)
Contents

Getting Started
1
Simulink PLC Coder Product Description . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

Prepare Model for Structured Text Generation . . . . . . . . . . . . . . . . . . . . . . 1-3


Tasking Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Configuring Simulink Models for Structured Text Code Generation . . . . . . 1-3
Check System Compatibility for Structured Text Code Generation . . . . . . 1-6

Generate and Examine Structured Text Code . . . . . . . . . . . . . . . . . . . . . . . 1-9


Generate Structured Text from the Model Window . . . . . . . . . . . . . . . . . . 1-9
Generate Structured Text with the MATLAB Interface . . . . . . . . . . . . . . . 1-10
View Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11

Propagate Block Descriptions to Code Comments . . . . . . . . . . . . . . . . . . 1-13

Files Generated with Simulink PLC Coder . . . . . . . . . . . . . . . . . . . . . . . . 1-14

Specify Custom Names for Generated Files . . . . . . . . . . . . . . . . . . . . . . . 1-16

Import Structured Text Code Automatically . . . . . . . . . . . . . . . . . . . . . . . 1-17


PLC IDEs That Qualify for Importing Code Automatically . . . . . . . . . . . . 1-17
Generate and Automatically Import Structured Text Code . . . . . . . . . . . . 1-17
Troubleshoot Automatic Import Issues . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18

Using Simulink Test with Simulink PLC Coder . . . . . . . . . . . . . . . . . . . . . 1-20


Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21

Simulation and Code Generation of Motion Instructions . . . . . . . . . . . . 1-22


Workflow for Using Motion Instructions in Model . . . . . . . . . . . . . . . . . . 1-22
Simulation of the Motion API Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-24
Structured Text Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-26
Adding Support for Other Motion Instructions . . . . . . . . . . . . . . . . . . . . 1-26

Mapping Simulink Semantics to Structured Text


2
Generated Code Structure for Simple Simulink Subsystems . . . . . . . . . . . 2-2

Generated Code Structure for Reusable Subsystems . . . . . . . . . . . . . . . . . 2-4

iii
Generated Code Structure for Triggered Subsystems . . . . . . . . . . . . . . . . 2-6

Generated Code Structure for Stateflow Charts . . . . . . . . . . . . . . . . . . . . . 2-8


Stateflow Chart with Event Based Transitions . . . . . . . . . . . . . . . . . . . . . . 2-8
Stateflow Chart with Absolute Time Temporal Logic . . . . . . . . . . . . . . . . . 2-9

Generated Code Structure for MATLAB Function Block . . . . . . . . . . . . . 2-12

Generated Code Structure for Multirate Models . . . . . . . . . . . . . . . . . . . 2-14

Generated Code Structure for Subsystem Mask Parameters . . . . . . . . . . 2-16

Global Tunable Parameter Initialization for PC WORX . . . . . . . . . . . . . . 2-20

Considerations for Nonintrinsic Math Functions . . . . . . . . . . . . . . . . . . . 2-21

Generating Ladder Diagram


3
Simulink PLC Coder Ladder Diagram Code Generation . . . . . . . . . . . . . . . 3-2
Ladder Diagram Generation Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4

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

Restrictions on Stateflow Chart for Ladder Diagram Generation . . . . . . 3-18

Supported Features in Ladder Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-20


Supported Ladder Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-20

Import L5X Ladder Files into Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22


Description of the Ladder Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22
Import Ladder Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-23

Modeling and Simulation of Ladder Diagrams in Simulink . . . . . . . . . . . 3-27


Model an AOI Prescan Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-31
Ladder Model Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-32

iv Contents
Generating Ladder Diagram Code from Simulink . . . . . . . . . . . . . . . . . . 3-34

Generating C Code from Simulink Ladder . . . . . . . . . . . . . . . . . . . . . . . . 3-36

Verify Generated Ladder Diagram Code . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38

Simulink PLC Coder Workflow vs. Rockwell Automation RSLogix IDE


Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-42

Create Custom Instruction in PLC Ladder Diagram Models . . . . . . . . . . 3-44


Create User-Defined Instruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-44
Calculate Square Root by using Custom Instruction Block . . . . . . . . . . . 3-45

Generating Test Bench Code


4
How Test Bench Verification Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2

Integrate Generated Code with Custom Code . . . . . . . . . . . . . . . . . . . . . . . 4-3

Import and Verify Structured Text Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4


Generate, Import, and Verify Structured Text . . . . . . . . . . . . . . . . . . . . . . 4-4
Import and Verify Structured Text to PHOENIX CONTACT (previously KW)
Software MULTIPROG 5.0 and Phoenix Contact PC WORX 6.0 IDEs . . . 4-4
Troubleshooting: Long Test Bench Code Generation Time . . . . . . . . . . . . . 4-5

Verify Generated Code with Multiple Test Benches . . . . . . . . . . . . . . . . . . 4-7


Troubleshooting: Test Data Exceeds Target Data Size . . . . . . . . . . . . . . . . 4-8
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9

Code Generation Reports


5
Information in Code Generation Reports . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2

Create and Use Code Generation Reports . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4


Generate a Traceability Report from Configuration Parameters . . . . . . . . . 5-4
Keep the Report Current . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
Trace from Code to Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
Trace from Model to Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6
Model Web View in Code Generation Report . . . . . . . . . . . . . . . . . . . . . . . 5-7
Generate a Static Code Metrics Report . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11
Generate a Traceability Report from the Command Line . . . . . . . . . . . . . 5-12

View Requirements Links from Generated Code . . . . . . . . . . . . . . . . . . . 5-13

Working with the Static Code Metrics Report . . . . . . . . . . . . . . . . . . . . . . 5-14


Workflow for Static Code Metrics Report . . . . . . . . . . . . . . . . . . . . . . . . 5-14
Report Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14

v
Function Block Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15

Working with Tunable Parameters in the Simulink PLC Coder


Environment
6
Block Parameters in Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2

Control Appearance of Block Parameters in Generated Code . . . . . . . . . . 6-4


Configure Tunable Parameters with Simulink.Parameter Objects . . . . . . . 6-4
Make Parameters Tunable Using Configuration Parameters Dialog Box . . . 6-6

Controlling Generated Code Partitions


7
Generate Global Variables from Signals in Model . . . . . . . . . . . . . . . . . . . 7-2

Control Code Partitions for Subsystem Block . . . . . . . . . . . . . . . . . . . . . . . 7-3


Control Code Partitions Using Subsystem Block Parameters . . . . . . . . . . . 7-3
One Function Block for Atomic Subsystems . . . . . . . . . . . . . . . . . . . . . . . 7-5
One Function Block for Virtual Subsystems . . . . . . . . . . . . . . . . . . . . . . . . 7-5
Multiple Function Blocks for Nonvirtual Subsystems . . . . . . . . . . . . . . . . . 7-6

Control Code Partitions for MATLAB Functions in Stateflow Charts . . . . 7-8

Integrating Externally Defined Identifiers


8
Integrate Externally Defined Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2

Integrate Custom Function Block in Generated Code . . . . . . . . . . . . . . . . 8-3

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

Use Internal Signals for Debugging in RSLogix 5000 IDE . . . . . . . . . . . . . 9-3

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

Siemens IDE Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6


Double-Precision Floating-Point Data Types . . . . . . . . . . . . . . . . . . . . . . . 9-6
int8 and Unsigned Integer Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
Unsigned Fixed-Point Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
Enumerated Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
INOUT Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6

Selectron CAP1131 IDE Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7


Double-Precision Floating-Point Data Types . . . . . . . . . . . . . . . . . . . . . . . 9-7
Enumerated Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7

Supported Simulink and Stateflow Blocks


10
Supported Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
View Supported Blocks Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Supported Simulink Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Supported Stateflow Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-9
Blocks with Restricted Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-9

Limitations
11
Simulink PLC Coder Structured Text Code Generation Limitations . . . . 11-2
General Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
Simulink PLC Coder Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2

Simulink PLC CoderLadder Logic Code Generation Limitations . . . . . . . 11-4


Simulink PLC Coderplcladderlib Limitations . . . . . . . . . . . . . . . . . . . . . . 11-4
Ladder Diagram Import Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-4
Ladder Diagram Modeling and Simulation Limitations . . . . . . . . . . . . . . 11-4
Ladder Diagram Code Generation Limitations . . . . . . . . . . . . . . . . . . . . . 11-4
Ladder Diagram Verification Limitations . . . . . . . . . . . . . . . . . . . . . . . . . 11-4

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

PLC Coder: Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-12


Comments Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-12
Include Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-12
Include Block Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-13
Simulink Block / Stateflow Object Comments . . . . . . . . . . . . . . . . . . . . 12-14
Show Eliminated Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-14

PLC Coder: Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-15


Optimization Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-15
Default Parameter Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-16
Signal Storage Reuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-17
Remove Code from Floating-Point to Integer Conversions That Wraps Out-
Of-Range Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-17
Generate Reusable Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-18
Inline Named Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-19
Reuse MATLAB Function Block Variables . . . . . . . . . . . . . . . . . . . . . . . 12-20
Loop Unrolling Threshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-20

PLC Coder: Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-22


Identifiers Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-23
Use Subsystem Instance Name as Function Block Instance Name . . . . . 12-23
Override Target Default Maximum Identifier Length . . . . . . . . . . . . . . . 12-23
Maximum Identifier Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-24
Override Target Default enum Name Behavior . . . . . . . . . . . . . . . . . . . 12-25
Generate enum Cast Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-25
Remove Top-level Subsystem Ssmethod Type . . . . . . . . . . . . . . . . . . . . 12-26
Keep Top-Level ssmethod Name the Same As Non-Top Level . . . . . . . . . 12-26
Generate Logging Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-27
Use the Same Reserved Names as Simulation Target . . . . . . . . . . . . . . 12-27
Reserved Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-28
Externally Defined Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-28
Preserve Alias Type Names for Data Types . . . . . . . . . . . . . . . . . . . . . . 12-29

PLC Coder: Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-31


Report Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-31
Generate Traceability Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-32
Generate Model Web View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-32
Open Report Automatically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-33

viii Contents
External Mode
13
External Mode Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2

Generate Structured Text Code with Logging Instrumentation . . . . . . . 13-3

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

Ladder Diagram Instructions


14
Instructions Supported in Ladder Diagram . . . . . . . . . . . . . . . . . . . . . . . 14-2

Ladder Diagram Blocks


15
Ladder Diagram Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2

Fixed Point Code Generation


16
Block Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2

Model Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-3

Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-4

Generating PLC Code for Multirate Models


17
Multirate Model Requirements for PLC Code Generation . . . . . . . . . . . . 17-2
Model Configuration Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2

ix
Generating PLC Code for MATLAB Function Block
18
Configuring the rand function for PLC Code generation . . . . . . . . . . . . . 18-2

Width block requirements for PLC Code generation . . . . . . . . . . . . . . . . 18-3

Workspace Parameter Data Type Limitations . . . . . . . . . . . . . . . . . . . . . . 18-4

Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-5

Model Architecture and Design


19
Fixed Point Simulink PLC Coder Structured Text Code Generation . . . . 19-2
Block Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-2
Model Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-3
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-4

Generating Simulink PLC Coder Structured Text Code For Multirate


Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-6
Multirate Model Requirements for PLC Code Generation . . . . . . . . . . . . 19-6

MATLAB Function Block Simulink PLC Coder Structured Text Code


Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-8
Configuring the rand function for PLC Code Generation . . . . . . . . . . . . . 19-8
SimulinkWidth Block Requirements for PLC Code generation . . . . . . . . . 19-8
Workspace Parameter Data Type Limitations . . . . . . . . . . . . . . . . . . . . . 19-8
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-8

PLC Coder Code Deployment


20
Deploy Structured Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Importing Generated Structured Text Code Manually . . . . . . . . . . . . . . . 20-2

Deploy Ladder Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-5


Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-5
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-5
Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-5
Importing Generated Ladder Diagram Code Manually . . . . . . . . . . . . . . 20-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

Generate Structured Text Code For Simulink Data Dictionary Defined


Model Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3
Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3
Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3

Simulink PLC Coder Structured Text Code Generation For


Enumerated Data Type
22
Structured Text Code Generation Support for Enumerated Data Type
Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2

IDE Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-4

Distributed Code Generation with Simulink PLC Coder


23
Use PLC_RemoveSSStep for Distributed Code Generation . . . . . . . . . . . 23-2

Structured Text Code Generation for Subsystem Reference Blocks . . . . 23-6

Distributed Code Generation Limitations . . . . . . . . . . . . . . . . . . . . . . . . . 23-8

xi
1

Getting Started

• “Simulink PLC Coder Product Description” on page 1-2


• “Prepare Model for Structured Text Generation” on page 1-3
• “Generate and Examine Structured Text Code” on page 1-9
• “Propagate Block Descriptions to Code Comments” on page 1-13
• “Files Generated with Simulink PLC Coder” on page 1-14
• “Specify Custom Names for Generated Files” on page 1-16
• “Import Structured Text Code Automatically” on page 1-17
• “Using Simulink Test with Simulink PLC Coder” on page 1-20
• “Simulation and Code Generation of Motion Instructions” on page 1-22
1 Getting Started

Simulink PLC Coder Product Description


Generate IEC 61131-3 Structured Text and Ladder Diagrams for PLCs and PACs

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

Prepare Model for Structured Text Generation


In this section...
“Tasking Mode” on page 1-3
“Solvers” on page 1-3
“Configuring Simulink Models for Structured Text Code Generation” on page 1-3
“Check System Compatibility for Structured Text Code Generation” on page 1-6

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.

Model Solver Setting


Variable-step Use a continuous solver. Configure a fixed sample time for the subsystem for
which you generate code.
Fixed-step Use a discrete fixed-step solver.

Configuring Simulink Models for Structured Text Code Generation


You must already have a model for which you want to generate and import code to a PLC IDE. Before
you use this model, perform the following steps.

1 In the Command Window, open your 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

5 Save the model with the new subsystem.


6 In the top-level model, right-click the Subsystem block and select Block Parameters
(Subsystem).
7 In the resulting block dialog box, select Treat as atomic unit.

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.

You are now ready to:

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.

Check System Compatibility for Structured Text Code Generation


You must already have a model that you have configured to work with the Simulink PLC Coder
software.

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

Generate and Examine Structured Text Code


In this section...
“Generate Structured Text from the Model Window” on page 1-9
“Generate Structured Text with the MATLAB Interface” on page 1-10
“View Generated Code” on page 1-11

Generate Structured Text from the Model Window


You must already have set up your environment and Simulink model to use the Simulink PLC Coder
software to generate Structured Text code. If you have not yet done so, see “Prepare Model for
Structured Text Generation” on page 1-3.

1 If you do not have the plcdemo_simple_subsystem model open, open it now.


2 Open the PLC Coder app. Click PLC Code tab.
3 Click Settings.

The Configuration Parameters dialog box is displayed.

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.

Generate Structured Text with the MATLAB Interface


You can generate Structured Text code for a subsystem in the Command Window with the
plcgeneratecode function. You must have already configured the parameters for the model or,
alternatively, you can use the default settings.

For example, to generate code from the SimpleSubsystem subsystem in the


plcdemo_simple_subsystem model:

1 Open the plcdemo_simple_subsystem model:

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

3 Select a target IDE.


4 Configure the subsystem as described in “Prepare Model for Structured Text Generation” on
page 1-3.
5 Generate code for the subsystem:
generatedfiles = plcgeneratecode('plcdemo_simple_subsystem/SimpleSubsystem')

When using plcgeneratecode for code generation, all diagnostic messages are printed to the
MATLAB command window.

View Generated Code


After generating the code, you can view it in the MATLAB Editor. For a description of how the
generated code for the Simulink components map to Structured Text components, see “PLC Code
Generation Basics”. In addition, note the following:

• 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

Propagate Block Descriptions to Code Comments


You can propagate block descriptions from the model to comments in your generated code.

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.

To propagate block descriptions to comments:

1 Enter a description for the block.

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.

Your block description appears as comments in the generated code.

1-13
1 Getting Started

Files Generated with Simulink PLC Coder


The Simulink PLC Coder software generates Structured Text code and stores it according to the
target IDE platform. These platform-specific paths are default locations for the generated code. To
customize generated file names, see “Specify Custom Names for Generated Files” on page 1-16.

Platform Generated Files


3S-Smart current_folder\plcsrc\model_name.exp — Structured Text file for importing to the
Software target IDE.
Solutions
CoDeSys 2.3
3S-Smart current_folder\plcsrc\model_name.xml — Structured Text file for importing to the
Software target IDE.
Solutions
CoDeSys 3.3
3S-Smart current_folder\plcsrc\model_name.xml — Structured Text file for importing to the
Software target IDE.
Solutions
CoDeSys 3.5
B&R Automation The following files in current_folder\plcsrc\model_name — Files for importing to the
Studio® IDE target IDE:

• Package.pkg — (If test bench is generated) Top-level package file for function blocks
library and test bench main program in XML format.

In the main folder (if test bench is generated):

• IEC.prg — Test bench main program definition file in XML format.


• mainInit.st — Text file. Test bench init program file in Structured Text.
• mainCyclic.st — Text file. Test bench cyclic program file in Structured Text.
• mainExit.st — Text file. Test bench exit program file in Structured Text.
• main.typ — Text file. Main program type definitions file in Structured Text.
• main.var — Text file. Main program variable definitions file in Structured Text.
®
Beckhoff current_folder\plcsrc\model_name.exp — Structured Text file for importing to the
TwinCAT® 2.11 target IDE.
Beckhoff current_folder\plcsrc\model_name.xml — Structured Text file for importing to the
TwinCAT 3 target IDE.
KW-Software current_folder\plcsrc\model_name.xml — Structured Text file, in XML format, for
MULTIPROG® 5.0 importing to the target IDE.
Phoenix Contact® current_folder\plcsrc\model_name.xml — Structured Text file, in XML format, for
PC WORX™ 6.0 importing to the target IDE.
Rockwell current_folder\plcsrc\model_name.L5X — (If test bench is generated) Structured
Automation Text file for importing to the target IDE using Add-On Instruction (AOI) constructs. This file
Studio 5000 IDE: is in XML format and contains the generated Structured Text code for your model.
AOI

1-14
Files Generated with Simulink PLC Coder

Platform Generated Files


Rockwell current_folder\plcsrc\model_name.L5X — (If test bench is generated) Structured
Automation Text file for importing to the target IDE using routine constructs. This file is in XML format
Studio 5000 IDE: and contains the generated Structured Text code for your model.
Routine
In current_folder\plcsrc\model_name (if test bench is not generated), the following
files are generated:

• subsystem_block_name.L5X — Structured Text file in XML format. Contains program


tag and UDT type definitions and the routine code for the top-level subsystem block.
• routine_name.L5X — Structured Text files in XML format. Contains routine code for
other subsystem blocks.
Rockwell current_folder\plcsrc\model_name.L5X — (If test bench is generated) Structured
Automation Text file for importing to the target IDE using Add-On Instruction (AOI) constructs. This file
RSLogix 5000 is in XML format and contains the generated Structured Text code for your model.
IDE: AOI
Rockwell current_folder\plcsrc\model_name.L5X — (If test bench is generated) Structured
Automation Text file for importing to the target IDE using routine constructs. This file is in XML format
RSLogix 5000 and contains the generated Structured Text code for your model.
IDE: Routine
In current_folder\plcsrc\model_name (if test bench is not generated), the following
files are generated:

• subsystem_block_name.L5X — Structured Text file in XML format. Contains program


tag and UDT type definitions and the routine code for the top-level subsystem block.
• routine_name.L5X — Structured Text files in XML format. Contains routine code for
other subsystem blocks.
Siemens current_folder\plcsrc\model_name\model_name.scl — Structured Text file for
SIMATIC® STEP® importing to the target IDE.
7 IDE
current_folder\plcsrc\model_name\model_name.asc — (If test bench is generated)
Text file. Structured Text file and symbol table for generated test bench code.
Siemens TIA current_folder\plcsrc\model_name\model_name.scl — Structured Text file for
Portal IDE importing to the target IDE.
Generic current_folder\plcsrc\model_name.st — Pure Structured Text file. If your target
IDE is not available for the Simulink PLC Coder product, consider generating and importing
a generic Structured Text file.
PLCopen XML current_folder\plcsrc\model_name.xml — Structured Text file formatted using the
PLCopen XML standard. If your target IDE is not available for the Simulink PLC Coder
product, but uses a format like this standard, consider generating and importing a PLCopen
XML Structured Text file.
Rexroth current_folder\plcsrc\model_name.xml — Structured Text file for importing to the
IndraWorks target IDE.
OMRON Sysmac current_folder\plcsrc\model_name.xml — Structured Text file for importing to the
Studio target IDE.

1-15
1 Getting Started

Specify Custom Names for Generated Files


The Simulink PLC Coder software generates Structured Text code and stores it according to the
target IDE platform. These platform-specific paths are default locations for the generated code. For
more information, see “Files Generated with Simulink PLC Coder” on page 1-14.

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.

Function name options Generated File Name


Auto Default. Uses the model name, as listed in
“Prepare Model for Structured Text
Generation” on page 1-3, for example,
plcdemo_simple_subsystem.
Use subsystem name Uses the subsystem name, for example,
SimpleSubsystem.
User specified Uses the custom name that you specify in the
Function name parameter, for example,
SimpleSubsystem.

1-16
Import Structured Text Code Automatically

Import Structured Text Code Automatically


In this section...
“PLC IDEs That Qualify for Importing Code Automatically” on page 1-17
“Generate and Automatically Import Structured Text Code” on page 1-17
“Troubleshoot Automatic Import Issues” on page 1-18

PLC IDEs That Qualify for Importing Code Automatically


If you are confident that your model produces Structured Text that does not require visual
examination, you can generate and automatically import Structured Text code to one of the following
target PLC IDEs:

• 3S-Smart Software Solutions CoDeSys Version 2.3


• PHOENIX CONTACT (previously KW) Software MULTIPROG Version 5.0 or 5.50
• Phoenix Contact PC WORX Version 6.0
• Rockwell Automation RSLogix 5000 Version 17, 18, or 19

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:

• Siemens SIMATIC Manager: Version V5.4+SP5+HF1, Revision K5.4.5.1


• S7-SCL: Version V5.3+SP5, Revision K5.3.5.0
• S7-PLCSIM: Version V5.4+SP3, Revision K5.4.3.0

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.

Generate and Automatically Import Structured Text Code


You can generate and automatically import Structured Text code. Before you start:

• In the target IDE, save your current project.


• Close open projects.
• Close the target IDE and target IDE-related windows.

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

1 If it is not already started, open the Command Window.


2 Open the plcdemo_simple_subsystem model.
3 Right-click the Subsystem block and select PLC Code > Generate and Import Code for
Subsystem.

The software:

a Generates the code.


b Starts the target IDE interface.
c Creates a project.
d Imports the generated code to the target IDE.

If you want to generate, import, and run the Structured Text code, see “Import and Verify Structured
Text Code” on page 4-4.

Troubleshoot Automatic Import Issues


Following are guidelines, hints, and tips for questions or issues you might have while using the
automatic import capability of the Simulink PLC Coder product.

Supported Target IDEs

The Simulink PLC Coder software supports only the following versions of target IDEs for automatic
import and verification:

• 3S-Smart Software Solutions CoDeSys Version 2.3


• PHOENIX CONTACT (previously KW) Software MULTIPROG 5.0 or 5.50 (English)
• Phoenix Contact PC WORX 6.0 (English)
• Rockwell Automation RSLogix 5000 Series Version 17, 18, 19 (English)

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”.

Unsupported Target IDEs

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.

• 3S-Smart Software Solutions CoDeSys Version 3.3


• 3S-Smart Software Solutions CoDeSys Version 3.5
• B&R Automation Studio IDE
• Beckhoff TwinCAT 2.11, 3

1-18
Import Structured Text Code Automatically

• Generic
• PLCopen
• Rockwell Automation Studio 5000 Logix Designer (both routine and AOI constructs)

Possible Automatic Import Issues

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

Using Simulink Test with Simulink PLC Coder


You can use Simulink Test™ with Simulink PLC Coder to author, manage, and execute simulation-
based tests of the generated code.

1 If you do not have the plcdemo_simple_subsystem model open, open it now.


2 Create a signal build test harness for the subsystem as shown. To create a test harness for a
subsystem, select the subsystem, right-click, and from the context menu, select Test Harness>
Create for <subsystem name>. Set test harness properties using the Create Test Harness
dialog box.

3 Open the PLC Coder app. Click PLC Code tab.


4 Click Settings. The Configuration Parameters dialog box is displayed.

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

Simulation and Code Generation of Motion Instructions


The Simulink PLC Coder software supports a workflow for the behavioral simulation and structured
text code generation for the Rockwell Automation RSLogix motion control instructions.

Workflow for Using Motion Instructions in Model


This workflow uses the “Simulating and Generating Structured Text Code for Rockwell Motion
Instructions” example in the plccoderdemos folder. This example provides a template that you can
use with motion instructions. It contains the following files:

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.

Simulation of the Motion API Model


You can run simulation on the model containing the motion instructions and see the state changes the
controller chart and the Drive subchart. You can also log the local data of the chart such as AXIS
and the MOTION_INSTRUCTION variables For more information, see “Configure States and Data for
Logging” (Stateflow).

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

Structured Text Code Generation


Use the plcgeneratemotionapicode function to prepare the model for code generation and
generate structured text code. The plcgeneratemotionapicode takes the full path name of
subsystem containing the original chart as an input and creates a new model from which structured
text code can be generated.

Adding Support for Other Motion Instructions


The plcdemo_motion_api_rockwell example has support for only the following motion
instructions:

• 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.

4 Create single transition with commands to set the output values.

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

6 Update the functionName variable in the getDriveTemplateNames.m file to include MAJ.

1-29
1 Getting Started

7 Update the DriveLibrary.slx file to respond to MAJ calls during simulation.

• Create isMAJ graphical function (similar to isMAM).

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

Mapping Simulink Semantics to


Structured Text

• “Generated Code Structure for Simple Simulink Subsystems” on page 2-2


• “Generated Code Structure for Reusable Subsystems” on page 2-4
• “Generated Code Structure for Triggered Subsystems” on page 2-6
• “Generated Code Structure for Stateflow Charts” on page 2-8
• “Generated Code Structure for MATLAB Function Block” on page 2-12
• “Generated Code Structure for Multirate Models” on page 2-14
• “Generated Code Structure for Subsystem Mask Parameters” on page 2-16
• “Global Tunable Parameter Initialization for PC WORX” on page 2-20
• “Considerations for Nonintrinsic Math Functions” on page 2-21
2 Mapping Simulink Semantics to Structured Text

Generated Code Structure for Simple Simulink Subsystems


This topic assumes that you have generated Structured Text code from a Simulink model. If you have
not yet done so, see “Generate Structured Text from the Model Window” on page 1-9.

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

A file like the following is displayed.

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

Generated Code Structure for Reusable Subsystems


This topic assumes that you have generated Structured Text code from a Simulink model. If you have
not yet done so, see “Generate Structured Text from the Model Window” on page 1-9.

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_reusable_subsystem model.


2 Open the PLC Coder app.
3 Click Generate PLC Code.

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.

Note This optimization is applicable only to IEC 61131-3 compatible targets.

2-5
2 Mapping Simulink Semantics to Structured Text

Generated Code Structure for Triggered Subsystems


This topic assumes that you have generated Structured Text code from a Simulink model. If you have
not yet done so, see “Generate Structured Text from the Model Window” on page 1-9.

The example in this topic shows generated code for the CoDeSys Version 2.3 PLC IDE. Generated
code for other IDE platforms looks different.

1 Open the plcdemo_cruise_control model.


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_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

Generated Code Structure for Stateflow Charts


The examples in this topic show generated code for the CoDeSys Version 2.3 PLC IDE. Generated
code for other IDE platforms looks different.

Stateflow Chart with Event Based Transitions


Generate code for the Stateflow chart ControlModule in the model
plcdemo_stateflow_controller. Here is the chart:

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.

Stateflow Chart with Absolute Time Temporal Logic


Generate code for the Stateflow chart Temporal in the model plcdemo_sf_abs_time. Here is the
chart:

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;

The variable temporalCounter_i1 is an instance of the function block PLC_CODER_TIMER defined


as:

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

Generated Code Structure for MATLAB Function Block


This topic assumes that you have generated Structured Text code from a Simulink model. If you have
not yet done so, see “Generate Structured Text from the Model Window” on page 1-9.

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_eml_tankcontrol model.


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_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

Generated Code Structure for Multirate Models


This example assumes that you have generated Structured Text code from a Simulink model. If you
have not yet done so, see “Generate Structured Text from the Model Window” on page 1-9.

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.

The generated code contains a global time step counter variable:

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:

IF plc_ts_counter1 >= 1 THEN


plc_ts_counter1 := 0;
ELSE
plc_ts_counter1 := plc_ts_counter1 + 1;
END_IF;

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:

(* Gain: '<S1>/Gain' incorporates:


* Inport: '<Root>/U1'
* Sum: '<S1>/Sum'
* UnitDelay: '<S1>/Unit Delay' *)
rtb_Gain := (U1 - UnitDelay_DSTATE) * 0.5;

(* Outport: '<Root>/Y1' *)
Y1 := rtb_Gain;
IF plc_ts_counter1 = 0 THEN

(* UnitDelay: '<S1>/Unit Delay1' *)


UnitDelay1 := UnitDelay1_DSTATE;

(* Gain: '<S1>/Gain1' incorporates:


* Inport: '<Root>/U2'

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;

(* Outport: '<Root>/Y3' incorporates:


* Sum: '<S1>/Sum2'
* UnitDelay: '<S1>/Unit Delay' *)
Y3 := UnitDelay_DSTATE - UnitDelay1;

(* Update for UnitDelay: '<S1>/Unit Delay' *)


UnitDelay_DSTATE := rtb_Gain;

IF plc_ts_counter1 = 0 THEN

(* Update for UnitDelay: '<S1>/Unit Delay1' *)


UnitDelay1_DSTATE := rtb_Gain1;

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

Generated Code Structure for Subsystem Mask Parameters


In the generated code for masked subsystems, the mask parameters map to function block inputs.
The values you specify in the subsystem mask are assigned to these function block inputs in the
generated code.

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' *)

i0_Filt1(ssMethodType := SS_INITIALIZE, InitV := In3,


InitF := In2, Input := In1,
rtp_Filt1_Order_Thau := 8.0,
rtp_InitialValue := 0.0,
rtp_Filt1_Order_Enable := TRUE);
Out1 := i0_Filt1.Out;

(* End of InitializeConditions for SubSystem: '<S1>/Filt1' *)

2-18
Generated Code Structure for Subsystem Mask Parameters

(* InitializeConditions for Atomic SubSystem: '<S1>/Filt2' *)


i1_Filt1(ssMethodType := SS_INITIALIZE, InitV := In6,
InitF := In5, Input := In4,
rtp_Filt1_Order_Thau := 5.0,
rtp_InitialValue := 4.0,
rtp_Filt1_Order_Enable := TRUE);
Out2 := i1_Filt1.Out;

(* End of InitializeConditions for SubSystem: '<S1>/Filt2' *)


SS_STEP:
(* Outputs for Atomic SubSystem: '<S1>/Filt1' *)

i0_Filt1(ssMethodType := SS_OUTPUT, InitV := In3, InitF := In2,


Input := In1, rtp_Filt1_Order_Thau := 8.0,
rtp_InitialValue := 0.0,
rtp_Filt1_Order_Enable := TRUE);
Out1 := i0_Filt1.Out;

(* End of Outputs for SubSystem: '<S1>/Filt1' *)

(* Outputs for Atomic SubSystem: '<S1>/Filt2' *)


i1_Filt1(ssMethodType := SS_OUTPUT, InitV := In6, InitF := In5,
Input := In4, rtp_Filt1_Order_Thau := 5.0,
rtp_InitialValue := 4.0,
rtp_Filt1_Order_Enable := TRUE);
Out2 := i1_Filt1.Out;

(* End of Outputs for SubSystem: '<S1>/Filt2' *)

2-19
2 Mapping Simulink Semantics to Structured Text

Global Tunable Parameter Initialization for PC WORX


For PC WORX, the coder generates an initialization function, PLC_INIT_PARAMETERS, to initialize
global tunable parameters that are arrays and structures. This initialization function is called in the
top-level initialization method.

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:

(* parameter initialization function starts *)<br/>


ParArrayXLUT[0] := LREAL#0.0;<br/>
ParArrayXLUT[1] := LREAL#2.0;<br/>
ParArrayXLUT[2] := LREAL#6.0;<br/>
ParArrayXLUT[3] := LREAL#10.0;<br/>
(* parameter initialization function ends *)<br/></div></html>

The PLC_INIT_PARAMETERS function is renamed i0_PLC_INIT_PARAMETERS, and called in the top-


level initialization method:

CASE SINT_TO_INT(ssMethodType) OF<br/>


0: <br/>
i0_PLC_INIT_PARAMETERS();<br/>

2-20
Considerations for Nonintrinsic Math Functions

Considerations for Nonintrinsic Math Functions


When Simulink PLC Coder encounters a math function that is not intrinsic, it generates Structured
Text by replacing the non-intrinsic function with an equivalent IEC-61131 compatible intrinsic
function. For such cases, an input value that is larger than the allowed input range, causes overflow
and generates a NaN value.

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

Generating Ladder Diagram

• “Simulink PLC Coder Ladder Diagram Code Generation” on page 3-2


• “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
• “Restrictions on Stateflow Chart for Ladder Diagram Generation” on page 3-18
• “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
• “Verify Generated Ladder Diagram Code” on page 3-38
• “Simulink PLC Coder Workflow vs. Rockwell Automation RSLogix IDE Workflow” on page 3-42
• “Create Custom Instruction in PLC Ladder Diagram Models” on page 3-44
3 Generating Ladder Diagram

Simulink PLC Coder Ladder Diagram Code Generation

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:

• The chart has started execution through the default transition.


• The previous active state is also State1 and the
conditions transitionCondition1 and transitionCondition2 are false.

State3 is active in one of these two cases:

• The previous active state is State1, transitionCondition1 is false, and


transitionCondition2 is true.
• The previous active state is also State3. State3 is a terminating state.

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.

Ladder Diagram Generation Workflow


1 Before generating Ladder Diagram code from your Stateflow chart, confirm that your chart is
ready for code generation.

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

Prepare Chart for Simulink PLC Coder Ladder Diagram Code


Generation

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.

Design PLC Application with Stateflow


Use Stateflow to design state machines that model PLC controllers. Your Stateflow chart must have
these properties:

• 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

For instance, in the following chart, transitionCondition1, and transitionCondition2 are


Boolean inputs to the model. State1, State2, and State3 correspond to Boolean outputs from the
model.

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.

Create Test Harness for Chart


If you want to generate a test bench for validation of the Ladder Diagram code, create a test harness
for the Stateflow chart. The test harness can consist of multiple test cases. Using the test harness,
Simulink PLC Coder can generate test benches for validation of the Ladder Diagram code.

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

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

This example shows how to:

• 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.

Stateflow Chart and Ladder Logic Diagram


The figure shows a Stateflow chart that implements three-aspect logic, a decision logic for many
railway signaling applications.

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.

Generate Ladder Diagram from Chart


To generate Ladder Diagram code from the model plcdemo_ladder_three_aspect:

1 Open the model.


2 Open the PLC Coder app. Click the PLC Code tab.
3 Specify the target IDE for which to generate the Ladder Diagram code.

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.

Generate Ladder Diagram Along with Test Bench


You can generate a test bench to validate the generated Ladder Diagram code. You import the code
together with the test bench in your IDE and validate the Ladder Diagram against the original
Stateflow chart using the test bench. To generate test bench along with the Ladder Diagram code:

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

Import Ladder Diagram Code to CODESYS 3.5 IDE and Validate


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.

Import Ladder Diagram XML


After code generation, you see the Ladder Diagram code XML file ModelName.xml in a subfolder
plcsrc of the current working folder. To import the generated XML and view the Ladder Diagram in
the CODESYS 3.5 IDE:

1 Create an empty project.


2 Import the Ladder Diagram code to the project.

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.

The transition appears in the Ladder Diagram in three steps:

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:

• CODESYS V3.5 SP6 Patch1: 3.5.4.30


• CODESYS V3.5 SP6 Patch3: 3.5.6.30
• CODESYS V3.5 SP8 Patch2: 3.5.8.20
• CODESYS V3.5 SP8 Patch4: 3.5.8.40

Verify Ladder Diagram with Test Bench


In your project, you see the generated test bench. To simulate using the test bench and validate your
generated code:

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

• The variable testCycleNum increases from 0 to the number of cycles.


• The variable testVerify remains TRUE as long as the test bench verification succeeds.

3-17
3 Generating Ladder Diagram

Restrictions on Stateflow Chart for Ladder Diagram Generation

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.

• The chart Action Language must be C.


• Disable the following chart properties:

• Enable Super Step Semantics


• Execute (enter) Chart At Initialization
• Initialize Outputs Every Time Chart Wakes Up
• The chart must have at least one input and output. The input and output data must be Boolean.
• Each output must correspond to a state in the chart. 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.

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

Supported Features in Ladder Diagram


The ladder import feature of Simulink PLC Coder allows you to import Ladder Diagram created with
Rockwell Automation IDEs such as RSLogix 5000 and Studio 5000 into the Simulink environment as a
model.

Supported Ladder Elements


Simulink PLC Coder supports the following ladder elements:

• 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:

L5X Data Types Simulink Types


BOOL Boolean datatype
SINT Int8 datatype
INT Int16 datatype
DINT Int32 datatype
REAL Single datatype
TIMER Timer bustype
COUNTER Counter bustype
CONTROL Control bustype
UDT UDT bustype
AOI AOI bustype
• Ladder diagram tags

• 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

• “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-21
3 Generating Ladder Diagram

Import L5X Ladder Files into Simulink


This example shows how to import a Ladder Diagram from an .L5X file created by using Rockwell
Automation IDEs such as RSLogix9 5000 and Studio 5000 into the Simulink environment. The import
operation is performed by using the plcimportladder function.

Description of the Ladder Diagram


The figure shows a Ladder Diagram with a simple timer. The Ladder Diagram consists of four rungs
with contacts (Switch_A, Light1, Motor_timer.DN), coils (Light1, Light2, Motor), and TON
timer function.

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>

Import Ladder Diagram


Before importing the .L5X file into Simulink :

• 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

Modeling and Simulation of Ladder Diagrams in Simulink


The ladder modeling feature of Simulink PLC Coder enables you to create Ladder Diagrams in the
Simulink environment as a model. After creating the Ladder Diagram, you can simulate and generate
code for the Ladder Diagram models from within the Simulink environment.

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

• Variable Name: Start, Stop, Switch


• Bit Access: MyInt.0, MyInt.31
• Array Element: A[1], B[2,3], C[idx], D[i, j]. Use of braces for indexing is not allowed in a tag
expression. For example, A(2) is illegal.
• Structure: A.B, C.D, E.F.G
• Mixture: A[1].B[i,j].C[3].D
• Expressions: A[3].B > C.D; A[3]+B[4].C
7 The tags can have attributes such as Data Type, Initial Value, and size. To change the
attributes of the tag, open the Program Variables table within the Ladder Diagram Program
block. You can delete the unused variables in the variable table by selecting the Delete option.
You must select Apply for the changes to take effect. Go to controller level block, and double-
click the Controller Tags table to specify the global variable and I/O symbol attributes.
8 To add rung comments to your model in Simulink, create a connected annotation (see Motor
Control Logic in image) to the rung terminal block. For more information on annotation
connectors, see “Associate Annotations with Blocks and Areas” (Simulink).

9 Update the ladder logic model to reflect changes. You have now created a simple ladder model in
Simulink.

Model an AOI Prescan Routine


1 Double-click the Function Block (AOI) inside the parent program unit.
2 Select the Allow Prescan Routine check box and click Apply button.
3 Click the Prescan Routine button.
4 Add the logic to Prescan Routine Ladder Diagram.

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.

Ladder Model Simulation


To perform Ladder Diagram simulation in Simulink, you must connect appropriate input and output
blocks to the ladder model.

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

Generating Ladder Diagram Code from Simulink


The following example demonstrates how to import a simple Ladder Diagram from an .L5X file
(simpleController.L5X) into the Simulink environment and then generate Ladder Diagram (L5X)
from the imported model. The Ladder Diagram .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.

1 Use the plcladderimport function to import the ladder into Simulink.


[mdlName,mdlLib,busScript] = plcimportladder('simpleController.L5X','OpenModel','On')
2 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 Generate code for the subsystem, simpleController/simpleController.

generatedFiles = plcgeneratecode('simpleController/simpleController');

3-34
Generating Ladder Diagram Code from Simulink

PLC code generation successful for 'simpleController/simpleController'.

Generated ladder files:


plcsrc\simpleController_gen.L5X

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

Generating C Code from Simulink Ladder


The following example demonstrates how to import a simple ladder diagram from an .L5X file
(simpleController.L5X) into the Simulink environment and then generate C code from the
imported model. You must have a valid Simulink Coder license and necessary compilers to generate C
code from the model. For more information, see “Get Started with Simulink Coder” (Simulink Coder).

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.

Use the plcladderimport function to import the ladder into Simulink.


[mdlName,mdlLib,busScript] = plcimportladder('simpleController.L5X','OpenModel','On')

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.

To generate C code for the subsystem, simpleController/simpleController you must first


enable 'FastSim' option for the Simulink Ladder Diagram model.
currentState = plcladderoption('simpleController/simpleController','FastSim','on');

3-36
Generating C Code from Simulink Ladder

Open the Configuration Parameters dialog box from the model editor by clicking Simulation >
Configuration Parameters.

Alternately, type the following commands at the MATLAB command prompt.

cs = getActiveConfigSet(model);
openDialog(cs);

Ensure that a valid Toolchain is selected.

In the model window, initiate code generation and the build process for the model by using any of the
following options:

• Click the Build Model button.


• Press Ctrl+B.
• Select Code > C/C++ Code > Build Model.
• Invoke the rtwbuild command from the MATLAB command line.

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

Verify Generated Ladder Diagram Code


The following example demonstrates how to import a simple Ladder Diagram from an .L5X file
(simpleXIC.L5X) into the Simulink environment and generate test bench code for it. The Ladder
Diagram .L5X file was created using RSLogix 5000 IDE and contains an AOI named simpleXIC with
contact and coil representing a switch and a light. The following is a snapshot of the ladder structure.

1 Use the plcladderimport function to import the ladder into Simulink.


[mdlName,mdlLib,busScript] = plcimportladder('simpleXIC.L5X',...
'OpenModel','On','TopAOI','simpleXIC')
2 The imported model contains an AOI Runner block named simpleXIC_runner, followed by a
Ladder Diagram Function (AOI) block named simpleXIC.

3 Add Signal Builder input block, Scope and output ports as shown.

3-38
Verify Generated Ladder Diagram Code

4 Modify the Signal Builder input to mimic a switch operation as shown.

3-39
3 Generating Ladder Diagram

5 Generate test-bench for the Ladder Diagram model.


Tbcode = plcgeneraterunnertb('simpleXIC_runner/simpleXIC_runner')

Tbcode =

1×1 cell array

{'C:\runnerTB\simpleXIC_runner.L5X'}

If the test-bench code generation is successful, a test-bench file simpleXIC_runner.L5X is


created. The generated AOI test bench file can be verified on Rockwell Automation IDE.

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

Simulink PLC Coder Workflow vs. Rockwell Automation RSLogix


IDE Workflow
These flowcharts show the workflow comparison in a ladder diagram created by Simulink PLC Coder
versus a ladder diagram created in the Rockwell AutomationRSLogixIDE.

• 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

Create Custom Instruction in PLC Ladder Diagram Models


You can create user-defined instructions for your ladder models by using the Custom Instruction
block. You can store these blocks containing custom instructions in a user-defined library named
plcuserlib.slx. You can also import, simulate, and export your ladder instructions by using your
custom blocks.

Create User-Defined Instruction


To create a user-defined instruction, use a Custom Instruction block added to the Simulink PLC Coder
Ladder Library.

1 To open the Ladder Library, at the MATLAB command line, enter:


plcladderlib

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.

Calculate Square Root by using Custom Instruction Block


This example shows how to calculate square root of an input signal by using a Custom Instruction
block.

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:

• With data type array and struct (composite) as arguments.


• That require internal data storage (states).

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

Generating Test Bench Code

• “How Test Bench Verification Works” on page 4-2


• “Integrate Generated Code with Custom Code” on page 4-3
• “Import and Verify Structured Text Code” on page 4-4
• “Verify Generated Code with Multiple Test Benches” on page 4-7
4 Generating Test Bench Code

How Test Bench Verification Works


The Simulink PLC Coder software simulates your model and automatically captures the input and
output signals for the subsystem that contains your algorithm. This set of input and output signal data
is the test bench data. The coder also automatically generates a test bench, or test harness, using the
test bench data.

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.

Data Type Comparison Error Tolerance


integer absolute 0
boolean absolute 0
single relative 0.0001
double relative 0.00001

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

Integrate Generated Code with Custom Code


For the top-level subsystem that has internal state, the generated FUNCTION_BLOCK code has
ssMethodType. ssMethodType is a special input argument that the coder adds to the input
variables section of the FUNCTION_BLOCK section during code generation. ssMethodType enables
you to execute code for Simulink Subsystem block methods such as initialization and computation
steps. The generated code executes the associated CASE statement based on the value passed in for
this argument.

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:

Has Internal State ssMethodType Contains...


Yes The generated function block for the block has an extra first parameter
ssMethodType of integer type. This extra parameter is in addition to the
function block I/O parameters mapped from Simulink block I/O ports. To use
the function block, first initialize the block by calling the function block with
ssMethodType set to integer constant SS_INITIALIZE. If the IDE does not
support symbolic constants, set ssMethodType to integer value 0. For each
follow-up invocation, call the function block with ssMethodType set to
constant SS_STEP. If the IDE does not support symbolic constants, set
ssMethodType to integer value 1. These settings cause the function block to
initialize or compute and return output for each time step. If you select Keep
top level ssMethod name same as non-top level, the
ssMethodType SS_STEP will be generated as SS_OUTPUT with integer value
3.
No The function block interface only has parameters mapped from Simulink block
I/O ports. There is no ssMethodType parameter. To use the function block in
this case, call the function block with I/O arguments.

For non top-level subsystems, in the generated code, the subsystem function block prototype has one
of the following formats:

Has Internal State ssMethodType Contains...


Yes The function block interface has the ssMethodType parameter. The generated
code might have SS_INITIALIZE, SS_OUTPUT, or other ssMethodType
constants to implement Simulink semantics.
No The function block interface only has parameters mapped from Simulink block
I/O ports. There is no ssMethodType parameter.

4-3
4 Generating Test Bench Code

Import and Verify Structured Text Code


After you generate code and test benches for your subsystem, you can import them to your target
IDE. Using the test bench data, you can verify that the results from your generated code match your
simulation results.

If you want to import the generated code, see “Generate and Automatically Import Structured Text
Code” on page 1-17.

Generate, Import, and Verify Structured Text


If you are working with the PHOENIX CONTACT (previously KW) Software MULTIPROG 5.0/5.50 or
Phoenix Contact PC WORX 6.0 IDE, 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.

Otherwise, to generate, import, and verify Structured Text code:

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:

a Generates the code and test bench.


b Starts the target IDE.
c Creates a project.
d Imports the generated code and test bench to the new project in the target IDE.
e Runs the generated code on the target IDE to verify it.

For information on:

• 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.

Import and Verify Structured Text to PHOENIX CONTACT (previously


KW) Software MULTIPROG 5.0 and Phoenix Contact PC WORX 6.0 IDEs
Before you can automatically import generated code to this IDE, create an Empty template. You must
have already set your target IDE to KW-Software MULTIPROG 5.0 or Phoenix Contact PC WORX 6.0.

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.

a In the Project Name field, type Empty,


b In the Project Path field, type or select a path to which you have write privileges.
c Click Next.
d In the remaining wizard pages, click Next to leave the default selections. At the end of the
wizard, click Finish.

The IDE is updated with the new Empty project tree.


4 In the project, delete everything under the following nodes:

• 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:

• PLC Code > Generate and Import Code for Subsystem


• PLC Code > Generate, Import, and Verify Code for Subsystem

If you automatically generate, import, and verify code, the software:

1 Generates the code and test bench.


2 Starts the target IDE.
3 Creates a project.
4 Imports the generated code and test bench to the new project in the target IDE.
5 Runs the generated code on the target IDE to verify it.

Troubleshooting: Long Test Bench Code Generation Time


If code generation with test bench takes too long, one possible reason is that the test bench data size
exceeds the limit that Simulink PLC Coder can handle. The test bench data size is directly related to
the number of times the input signal is sampled during simulation. For large simulation time or more
frequent sampling, the test bench data can be large.

To reduce test bench generation time, do one of the following:

• Reduce the duration of the simulation.


• Increase the simulation step size.

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

Verify Generated Code with Multiple Test Benches


You can generate code with multiple test benches from your subsystem. For the generated code to
have multiple test benches, the input to your subsystem must consist of multiple signal groups.

To generate multiple test benches for your subsystem:

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.

To create your Signal Builder block with Simulink Design Verifier:

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.

Troubleshooting: Test Data Exceeds Target Data Size


If the test data from the multiple signal groups exceeds the maximum data size on your target, you
can encounter compilation errors. If you encounter compilation errors when generating multiple test
benches, try one of the following:

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

Code Generation Reports

• “Information in Code Generation Reports” on page 5-2


• “Create and Use Code Generation Reports” on page 5-4
• “View Requirements Links from Generated Code” on page 5-13
• “Working with the Static Code Metrics Report” on page 5-14
5 Code Generation Reports

Information in Code Generation Reports


The coder creates and displays a Traceability Report file when you select one or more of these
options:

GUI Option Command-Line Property Description


Generate PLC_GenerateReport Specify whether to create code
traceability generation report.
report
Generate PLC_GenerateWebview Include the model web view in the code
model web view generation report to navigate between
the code and model within the same
window. You can share your model and
generated code outside of the MATLAB
environment.

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

Create and Use Code Generation Reports


In this section...
“Generate a Traceability Report from Configuration Parameters” on page 5-4
“Keep the Report Current” on page 5-5
“Trace from Code to Model” on page 5-5
“Trace from Model to Code” on page 5-6
“Model Web View in Code Generation Report” on page 5-7
“Generate a Static Code Metrics Report” on page 5-11
“Generate a Traceability Report from the Command Line” on page 5-12

Generate a Traceability Report from Configuration Parameters


To generate a Simulink PLC Coder code generation report from the Configuration Parameters dialog
box:
1 Verify that the model is open.
2 Open the PLC Coder app. Click the PLC Code tab.
3 Click Settings and navigate to the PLC Code Generation pane.
4 To enable report generation, select Report > Generate traceability report.
5 Click Apply.

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.

The HTML report appears:

For more information, see:

• “Trace from Code to Model” on page 5-5


• “Trace from Model to Code” on page 5-6

Keep the Report Current


If you generate a code generation report for a model, and then change the model, the report becomes
invalid. To keep your code generation report current, after modifying the source model, regenerate
code and the report. If you close and then reopen a model, regenerate the report.

Trace from Code to Model


You must have already generated code with a traceability report. 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.

To trace generated code to your model:

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.

Trace from Model to Code


You can select a component at any level of the model with model-to-code traceability. You can also
view the code references to that component in the HTML code generation report. You can select the
following objects for tracing:

• 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.

To trace a model component to the generated code:

1 Open the subsystem.


2 Click PLC Code.
3 Click the component to trace and in the Review Results section, click Navigate to Code.
4 Selecting Navigate to Code activates the HTML code generation report. The following figure
shows the result of tracing the Gain block within the subsystem.

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.

Model Web View in Code Generation Report


Model Web Views

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

Browser Requirements for Web Views

Web views require a web browser that supports Scalable Vector Graphics (SVG). Web views use SVG
to render and navigate models.

You can use the following web browsers:

• 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/.

Note Web views do not currently support Microsoft Internet Explorer 9.

Generate HTML Code Generation Report with Model Web View

This example shows how to create an HTML code generation report which includes a web view of the
model diagram.

1 Open the plcdemo_simple_subsystem model.


2 Open the PLC Coder app. Click the PLC Code tab.
3 Click Settings and navigate to the Code Generation pane.
4 To enable report generation, select Report > Generate traceability report.
5 To enable model web view, select Report > Generate model web view.
6 Click OK.

The dialog box looks something like this figure:

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:

• “Trace from Code to Model” on page 5-5


• “Trace from Model to Code” on page 5-6

Model Web View Limitations

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).

Generate a Static Code Metrics Report


The PLC Coder Static Code Metrics report provides statistics of the generated code. The report is
generated when you select Generate Traceability Report in the Configuration Parameters dialog
box. You can use the Static Code Metrics Report to evaluate the generated PLC code before
implementation in your IDE. For more information, see “Working with the Static Code Metrics
Report” on page 5-14.

The procedure is the same as generating the Traceability Report.

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

Generate a Traceability Report from the Command Line


To generate a Simulink PLC Coder code generation report from the command-line code for the
subsystem, plcdemo_simple_subsystem/SimpleSubsystem:

1 Open a Simulink PLC Coder model, for example:

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');

3 Generate the code.


generatedfiles = plcgeneratecode('plcdemo_simple_subsystem/SimpleSubsystem')

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.

If the model web view is also enabled, that view is displayed.

5-12
View Requirements Links from Generated Code

View Requirements Links from Generated Code


For requirements reviews, design reviews, traceability analysis, or project documentation, you can
create links to requirements documents from your model with the Simulink Requirements™ software.
If your model has links to requirements documents, you can also view the links from the 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.

To view requirements from generated code:

1 From your model, create links to requirements documents.

See, “Requirements Management Interface” (Simulink Requirements).


2 For the subsystem for which you want to generate code, specify the following configuration
parameters.

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

Working with the Static Code Metrics Report


In this section...
“Workflow for Static Code Metrics Report” on page 5-14
“Report Contents” on page 5-14
“Function Block Information” on page 5-15

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.

Workflow for Static Code Metrics Report


This is the basic workflow for using the Static Code Metrics Report with your model.

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.

Function Block Information


You can use the information in the Function Block Information table to assess the generated code
before implementation in your IDE. The leftmost column of the table lists function blocks with
hyperlinks. Clicking a function block name leads you to the function block location in the generated
code. From here, you can trace from the code to the model. For more information, see “Trace from
Code to Model” on page 5-5.

5-15
6

Working with Tunable Parameters in the


Simulink PLC Coder Environment

• “Block Parameters in Generated Code” on page 6-2


• “Control Appearance of Block Parameters in Generated Code” on page 6-4
6 Working with Tunable Parameters in the Simulink PLC Coder Environment

Block Parameters in Generated Code


Block parameters appear in the generated code as variables. You can choose how the variables
appear in the generated code. For instance, you can control the following variable characteristics:

• Whether the variables are inlined in generated code


• Whether the variables are local to a function block, global, or not defined

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:

Target IDE Parameter Storage Class


SimulinkGlobal ExportedGlobal ImportedExtern Imported‐
ExternPointer
CoDeSys 2.3 Local function block Global variable Variable is not defined Ignored. If you set the
variables in generated code and parameter to this
expected to be defined value, the software
externally. treats it the same as
ImportedExtern.
CoDeSys 3.3 Local function block Global variable Variable is not defined Ignored. If you set the
variables in generated code and parameter to this
expected to be defined value, the software
externally. treats it the same as
ImportedExtern.
CoDeSys 3.5 Local function block Global variable Variable is not defined Ignored. If you set the
variables in generated code and parameter to this
expected to be defined value, the software
externally. treats it the same as
ImportedExtern.
B&R Automation Local function block Local function block Local function block Ignored. If you set the
Studio 3.0 variable variable variable. parameter to this
value, the software
treats it the same as
ImportedExtern.
Beckhoff Local function block Global variable Variable is not defined Ignored. If you set the
TwinCAT 2.11 variable in generated code and parameter to this
expected to be defined value, the software
externally. treats it the same as
ImportedExtern.

6-2
Block Parameters in Generated Code

Target IDE Parameter Storage Class


SimulinkGlobal ExportedGlobal ImportedExtern Imported‐
ExternPointer
KW-Software Local function block Local function block Local function block Ignored. If you set the
MULTIPROG 5.0 variable variable variable. parameter to this
value, the software
treats it the same as
ImportedExtern.
Phoenix Contact Local function block Global variable Variable is not defined Ignored. If you set the
PC WORX 6.0 variable in generated code and parameter to this
expected to be defined value, the software
externally. treats it the same as
ImportedExtern.
RSLogix 5000 17, AOI local tags AOI input tags AOI input tags. Ignored. If you set the
18: AOI parameter to this
value, the software
treats it the same as
ImportedExtern.
RSLogix 5000 17, Instance fields of Program tags Variable is not defined Ignored. If you set the
18: Routine program UDT tags in generated code and parameter to this
expected to be defined value, the software
externally. treats it the same as
ImportedExtern.
Siemens SIMATIC Local function block Local function block Local function block Ignored. If you set the
STEP 7 variable variable variable. parameter to this
value, the software
treats it the same as
ImportedExtern.
Generic Local function block Global variable Variable is not defined Ignored. If you set the
variable in generated code and parameter to this
expected to be defined value, the software
externally. treats it the same as
ImportedExtern.
PLCopen Local function block Global variable Variable is not defined Ignored. If you set the
variable in generated code and parameter to this
expected to be defined value, the software
externally. treats it the same as
ImportedExtern.

6-3
6 Working with Tunable Parameters in the Simulink PLC Coder Environment

Control Appearance of Block Parameters in Generated Code


Unless you use constants for block parameters in your model, they appear in the generated code as
variables. You can choose how these variables appear in the generated code. For instance, you can
control the following variable characteristics:

• Whether the variables are inlined in generated code


• Whether the variables are local to a function block, global, or not defined

For more information, see “Block Parameters in Generated Code” on page 6-2.

To control how the block parameters appear in the generated code:

1 Use variables instead of constants for block parameters.


2 Define these parameters in the MATLAB workspace in one of the following ways:

• 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.

Configure Tunable Parameters with Simulink.Parameter Objects


This example shows how to create and modify a Simulink.Parameter object.

The model plcdemo_tunable_params_slparamobj illustrates these steps. The model contains a


Subsystem block SimpleSubsystem that has three Gain blocks with tunable parameters, K1, K2, and
K3.

1 Write a MATLAB script that defines the tunable parameters.

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';

% tunable parameter mapped to global variable


K2 = Simulink.Parameter;
K2.Value = 0.2;

6-4
Control Appearance of Block Parameters in Generated Code

K2.CoderInfo.StorageClass = 'ExportedGlobal';

% tunable parameter mapped to global const


K3 = Simulink.Parameter;
K3.Value = 0.3;
K3.CoderInfo.StorageClass = 'Custom';
K3.CoderInfo.CustomStorageClass = 'Const';
2 Specify that the script setup_tunable_params.m must execute before the model loads and
that the MATLAB workspace must be cleared before the model closes.

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

Variable Storage Class Generated Code (3S CoDeSys 2.3)


K1 Model default K1 is a local function block variable.

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

Make Parameters Tunable Using Configuration Parameters Dialog Box


This example shows how to make parameters tunable using the Model Configuration Parameters
dialog box.

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.

6 Generate code and inspect it.

Variable Storage Class Generated Code (3S CoDeSys 2.3)


K1 SimulinkGlobal K1 is a local function block variable.

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

Variable Storage Class Generated Code (3S CoDeSys 2.3)


K2 ExportedGlobal K2 is a global variable.

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

Controlling Generated Code Partitions

• “Generate Global Variables from Signals in Model” on page 7-2


• “Control Code Partitions for Subsystem Block” on page 7-3
• “Control Code Partitions for MATLAB Functions in Stateflow Charts” on page 7-8
7 Controlling Generated Code Partitions

Generate Global Variables from Signals in Model


If you want to generate a global variable in your code, use a global Data Store Memory block based
on a Simulink.Signal object in your model.

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

Control Code Partitions for Subsystem Block


Simulink PLC Coder converts subsystems to function block units according to the following rules:

• 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.

These topics use code generated with CoDeSys Version 2.3.

Control Code Partitions Using Subsystem Block Parameters


You can partition generated code using the following Subsystem block parameters on the Code
Generation tab. See the Subsystem block documentation for details.

• Function packaging
• Function name options

Leave the File name options set to the default, Auto.

Generating Separate Partitions and Inlining Subsystem Code

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:

Setting Coder Interpretation


Auto Uses the optimal format based on the type and
number of subsystem instances in the model.
Reusable function Generates a function with arguments that allows
reuse of subsystem code when a model includes
multiple instances of the subsystem.
Nonreusable function The Simulink PLC Coder does not support
Nonreusable function packaging. See,
“Simulink PLC Coder Restrictions” on page 11-
2.
Inline Inlines the subsystem unconditionally.

For example, in the plcdemo_hierarchical_virtual_subsystem, you can:

• 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

Changing the Name of a Subsystem

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 Save the new settings.


8 Generate code for the parent subsystem.
9 Observe the renamed function block.

One Function Block for Atomic Subsystems


The code for plcdemo_simple_subsystem is an example of generating code with one function
block. The atomic subsystem for which you generate code does not contain other subsystems.

One Function Block for Virtual Subsystems


The plcdemo_hierarchical_virtual_subsystem example contains an atomic subsystem that
has two virtual subsystems, S1 and S2, inlined. A virtual subsystem does not have the Treat as
atomic unit parameter selected. When you generate code for the hierarchical subsystem, the code
contains only the FUNCTION_BLOCK HierarchicalSubsystem component. There are no additional
function blocks for the S1 and S2 subsystems.

7-5
7 Controlling Generated Code Partitions

Multiple Function Blocks for Nonvirtual Subsystems


The plcdemo_hierarchical_subsystem example contains an atomic subsystem that has two
nonvirtual subsystems, S1 and S2. Virtual subsystems have the Treat as atomic unit parameter
selected. When you generate code for the hierarchical subsystem, that code contains the
FUNCTION_BLOCK HierarchicalSubsystem, FUNCTION_BLOCK S1, and FUNCTION_BLOCK S2
components.

7-6
Control Code Partitions for Subsystem Block

7-7
7 Controlling Generated Code Partitions

Control Code Partitions for MATLAB Functions in Stateflow


Charts
Simulink PLC Coder inlines MATLAB functions in generated code based on your inlining
specifications. To specify whether to inline a function:

1 Right-click the MATLAB function and select Properties.


2 For Function Inline Option, select Inline if you want the function to be inlined. Select
Function if you do not want the function to be inlined. For more information, see “Specify
MATLAB Function Properties in a Chart” (Stateflow).

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.

Here is the model.

7-8
Control Code Partitions for MATLAB Functions in Stateflow Charts

Here is the Stateflow chart.

7-9
7 Controlling Generated Code Partitions

The functions fcn1 to fcn4 are defined as follows.

7-10
Control Code Partitions for MATLAB Functions in Stateflow Charts

Function Inlining Specification Generated Code


fcn1: Specify that the fcn1 is inlined in the generated code.
function must be
function y = fcn1(u) inlined. is_c3_Chart := Chart_IN_A;
y = u+1; (* Outport: '<Root>/y1'
incorporates:
* Inport: '<Root>/u1' *)
(* Entry 'A': '<S1>:10' *)
(* MATLAB Function 'fcn1':
'<S1>:1' *)
(* '<S1>:1:3' *)
y1 := u1 + 1.0;
fcn2: Specify that the fcn2 is not inlined in the generated code.
function must not be
function y = fcn2(u) inlined. is_c3_Chart := Chart_IN_B;
y = u+2; (* Outport: '<Root>/y2'
incorporates:
* Inport: '<Root>/u2' *)
(* Entry 'B': '<S1>:11' *)
y2 := fcn2(u := u2);
.
.
.
FUNCTION fcn2: LREAL
VAR_INPUT
u: LREAL;
END_VAR
VAR_TEMP
END_VAR
(* MATLAB Function 'fcn2':
'<S1>:4' *)
(* '<S1>:4:3' *)
fcn2 := u + 2.0;
END_FUNCTION
fcn3: Specify that the fcn3 is inlined in the generated code
function must not be because it accesses local data from the
function y = fcn3(u) inlined. Stateflow chart.
% The function accesses
% local data x of is_c3_Chart := Chart_IN_C;
% parent chart (* Outport: '<Root>/y3'
y = u+3+x; incorporates:
* Inport: '<Root>/u3' *)
(* Entry 'C': '<S1>:15' *)
(* MATLAB Function 'fcn3':
'<S1>:9' *)
(* The function accesses
local data x of parent
chart *)
(* '<S1>:9:4' *)
y3 := (u3 + 3.0) + x;

7-11
7 Controlling Generated Code Partitions

Function Inlining Specification Generated Code


fcn4: Specify that the fcn4 is converted to a function block in
function must not be the generated code because it has
function [yy1,yy2] = inlined. multiple outputs.
fcn4(u)
yy1 = u+4; is_c3_Chart := Chart_IN_D;
yy2 = u+5; (* Entry 'D': '<S1>:28' *)
i0_fcn4(u := u4);
b_y4 := i0_fcn4.yy1;
b_y5 := i0_fcn4.yy2;
(* Outport: '<Root>/y4'
incorporates:
* Inport: '<Root>/u4' *)
y4 := b_y4;
(* Outport: '<Root>/y5' *)
y5 := b_y5;
.
.
.
FUNCTION_BLOCK fcn4
VAR_INPUT
u: LREAL;
END_VAR
VAR_OUTPUT
yy1: LREAL;
yy2: LREAL;
END_VAR
VAR
END_VAR
VAR_TEMP
END_VAR
(* MATLAB Function 'fcn4':
'<S1>:26' *)
(* '<S1>:26:3' *)
yy1 := u + 4.0;
(* '<S1>:26:4' *)
yy2 := u + 5.0;
END_FUNCTION_BLOCK

7-12
8

Integrating Externally Defined


Identifiers

• “Integrate Externally Defined Identifiers” on page 8-2


• “Integrate Custom Function Block in Generated Code” on page 8-3
8 Integrating Externally Defined Identifiers

Integrate Externally Defined Identifiers


The coder allows you to suppress identifier (symbol) definitions in the generated code. This
suppression allows you to integrate a custom element, such as user-defined function blocks, function
blocks, data types, and named global variable and constants, in place of one generated from a
Simulink subsystem. You must then provide these definitions when importing the code into the target
IDE. You must:

• 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

Integrate Custom Function Block in Generated Code


To integrate a custom function block, ExternallyDefinedBlock, this procedure uses the example
plcdemo_external_symbols.

1 In a Simulink model, add a MATLAB Function block.


2 Double-click the MATLAB Function block.
3 In the MATLAB editor, minimally define inputs, outputs, and stubs. For example:

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.

7 Open the Configuration Parameters dialog box for the model.


8 Add ExternallyDefinedBlock to PLC Code Generation > Identifiers > Externally
Defined Identifiers.
9 The plcdemo_external_symbols model also suppresses K1 and InBus. Add these symbol
names to the Externally Defined Identifiers field, separated by spaces or commas. For other
settings, see the plcdemo_external_symbols model.

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.

The reference of ExternallyDefinedBlock is:

The omission of ExternallyDefinedBlock is:

8-4
9

IDE-Specific Considerations

• “Integrate Generated Code with Siemens IDE Project” on page 9-2


• “Use Internal Signals for Debugging in RSLogix 5000 IDE” on page 9-3
• “Rockwell Automation RSLogix Requirements” on page 9-4
• “Siemens IDE Requirements” on page 9-6
• “Selectron CAP1131 IDE Requirements” on page 9-7
9 IDE-Specific Considerations

Integrate Generated Code with Siemens IDE Project


You can integrate generated code with an existing Siemens SIMATIC STEP 7 or Siemens TIA Portal
project. For more information on:

• 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.

Integrate Generated Code with Siemens SIMATIC STEP 7 Projects


1 In the Siemens SIMATIC STEP 7 project, right-click the Sources node and select Insert New
Object > External Source.
2 Navigate to the folder containing the generated code and open the file.

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.

Symbol addresses are automatically generated for Subsystem blocks.


6 In the SCL editor window, compile the model_name.scl file for the Subsystem block.

The new Function Block is now integrated and available for use with the existing Siemens SIMATIC
STEP 7 project.

Integrate Generated Code with Siemens TIA Portal Projects


1 In the Project tree pane, on the Devices tab, under the External source files node in your
project, select Add new external file.
2 Navigate to the folder containing the generated code and open the file.

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

Use Internal Signals for Debugging in RSLogix 5000 IDE


For debugging, you can generate code for test point outputs from the top-level subsystem of your
model. The coder generates code that maps the test pointed output to optional AOI output
parameters for RSLogix 5000 IDEs. In the generated code, the variable tags that correspond to the
test points have the property Required=false. This example assumes that you have a model
appropriately configured for the coder, such as plcdemo_simple_subsystem.

1 Open the plcdemo_simple_subsystem model.

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.

The Signal Properties dialog box is displayed.


4 On the Logging and accessibility tab, click the Test point check box.

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

Rockwell Automation RSLogix Requirements


Following are considerations for this target IDE platform.

Add-On Instruction and Function Blocks


The Structured Text concept of function block exists for Rockwell Automation RSLogix target IDEs as
an Add-On instruction (AOI). The Simulink PLC Coder software generates the AOIs for Add-On
instruction format, but not FUNCTION_BLOCK.

Double-Precision Data Types


The Rockwell Automation RSLogix target IDE does not support double-precision data types. At code
generation, Simulink PLC Coder converts this data type to single-precision data types in generated
code.

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.

Unsigned Integer Data Types


The Rockwell Automation RSLogix target IDE does not support unsigned integer data types. At code
generation, Simulink PLC Coder converts this data type to signed integer data types in 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.

Unsigned Fixed-Point Data Types


In the generated code, Simulink PLC Coder converts fixed-point data types to target IDE integer data
types. Because the Rockwell Automation RSLogix target IDE does not support unsigned integer data
types, do not use unsigned fixed-point data types in the model. For more information about coder
limitations for fixed-point data type support, see “Fixed Point Simulink PLC Coder Structured Text
Code Generation” on page 19-2.

Enumerated Data Types


The Rockwell Automation RSLogix target IDE does not support enumerated data types. At code
generation, Simulink PLC Coder converts this data type to 32 bit signed integer data type in
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.

Rockwell Automation IDE selection


Based on the L5X import file target IDE version you will choose the PLC target IDE to be
RSLogix5000 or Studio 5000. If importing into v24 or later choose Studio 5000 else for versions prior
to v24 choose RSLogix 5000.

9-5
9 IDE-Specific Considerations

Siemens IDE Requirements


Following are considerations for this target IDE platform.

Double-Precision Floating-Point Data Types


The Siemens SIMATIC STEP 7 target IDE does not support double-precision floating-point data types.
At code generation, the Simulink PLC Coder converts this data type to single-precision real data
types in the generated code. Design your model so that the possible precision loss of numerical
results of the generated code does not change the expected semantics of the model.

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.

int8 and Unsigned Integer Types


The SCL language for Siemens IDEs does not support int8 and unsigned integer data types. At code
generation, the Simulink PLC Coder converts int8 and unsigned integer data types to int16 or int32 in
the generated code.

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.

Unsigned Fixed-Point Data Types


In the generated code, Simulink PLC Coder converts fixed-point data types to target IDE integer data
types. Because the Siemens target IDEs do not support unsigned integer data types, do not use
unsigned fixed-point data types in the model. For more information about coder limitations for fixed-
point data type support, see “Fixed Point Simulink PLC Coder Structured Text Code Generation” on
page 19-2.

Enumerated Data Types


The Siemens SIMATIC STEP 7 target IDE does not support enumerated data types. The Siemens
SIMATIC STEP 7 converts this data type to 16–bit signed integer data type in the generated code.

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

Selectron CAP1131 IDE Requirements


For the Selectron CAP1131 target IDE platform, consider these limitations:

Double-Precision Floating-Point Data Types


The Selectron CAP1131 target IDE does not support double-precision floating-point data types. At
code generation, the Simulink PLC Coder converts this data type to single-precision real data types in
the generated code. Design your model so that the possible precision loss of numerical results of the
generated code numeric results does not change the model semantics that you expect.

Enumerated Data Types


The Selectron CAP1131 target IDE does not support enumerated data types. The Selectron CAP1131
IDE converts this data type to 32-bit signed integer data type in the generated code.

See Also

9-7
10

Supported Simulink and Stateflow


Blocks
10 Supported Simulink and Stateflow Blocks

Supported Blocks
For Simulink semantics not supported by Simulink PLC Coder, see “Simulink PLC Coder Structured
Text Code Generation Limitations” on page 11-2.

View Supported Blocks Library


To view a Simulink library of blocks that the Simulink PLC Coder software supports, type plclib in
the Command Window. The coder can generate Structured Text code for subsystems that contain
these blocks. The library window is displayed.

This library contains two sublibraries, Simulink and Stateflow. Each sublibrary contains the blocks
that you can include in a Simulink PLC Coder model.

Supported Simulink Blocks


The coder supports the following Simulink blocks.

Additional Math & Discrete/Additional Discrete

Transfer Fcn Direct Form II

Transfer Fcn Direct Form II Time Varying

10-2
Supported Blocks

Unit Delay Enabled (Obsolete)

Unit Delay Enabled External IC (Obsolete)

Unit Delay Enabled Resettable (Obsolete)

Unit Delay Enabled Resettable External IC (Obsolete)

Unit Delay External IC (Obsolete)

Unit Delay Resettable (Obsolete)

Unit Delay Resettable External IC (Obsolete)

Unit Delay With Preview Enabled (Obsolete)

Unit Delay With Preview Enabled Resettable (Obsolete)

Unit Delay With Preview Enabled Resettable External RV (Obsolete)

Unit Delay With Preview Resettable (Obsolete)

Unit Delay With Preview Resettable External RV (Obsolete)

Commonly Used Blocks

Inport

Bus Creator

Bus Selector

Constant

Data Type Conversion

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

Coulomb and Viscous Friction

Dead Zone Dynamic

Rate Limiter

Rate Limiter Dynamic

Relay

Saturation

Saturation Dynamic

Wrap To Zero

Discrete

Difference

Discrete Transfer Fcn

Discrete Derivative

Discrete FIR Filter

Discrete Filter

Discrete PID Controller

Discrete PID Controller (2 DOF)

Discrete State-Space

Discrete-Time Integrator

FIR Interpolation

Integer Delay

Memory

Tapped Delay

10-4
Supported Blocks

Transfer Fcn First Order

Transfer Fcn Lead or Lag

Transfer Fcn Real Zero

Unit Delay

Zero-Order Hold

Logic and Bit Operations

Bit Clear

Bit Set

Bitwise Operator

Compare To Constant

Compare To Zero

Detect Change

Detect Decrease

Detect Increase

Detect Fall Negative

Detect Fall Nonpositive

Detect Rise Nonnegative

Detect Rise Positive

Extract Bits

Interval Test

Interval Test Dynamic

Logical Operator

Shift Arithmetic

Lookup Tables

Dynamic-Lookup

Interpolation Using Prelookup

PreLookup

n-D Lookup Table

10-5
10 Supported Simulink and Stateflow Blocks

Math Operations

Abs

Add

Assignment

Bias

Divide

Dot Product

Gain

Math Function

Matrix Concatenate

MinMax

MinMax Running Resettable

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

Check Discrete Gradient

Check Dynamic Gap

Check Dynamic Range

Check Static Gap

Check Static Range

Check Dynamic Lower Bound

Check Dynamic Upper Bound

Check Input Resolution

Check Static Lower Bound

Check Static Upper Bound

Model-Wide Utilities

DocBlock

Model Info

Ports & Subsystems

Atomic Subsystem

CodeReuse Subsystem

Enabled Subsystem

Enable

Function-Call Subsystem

Subsystem

Inport

Outport

Signal Attributes

Data Type Conversion

Data Type Duplicate

Signal Conversion

10-7
10 Supported Simulink and Stateflow Blocks

Signal Routing

Bus Assignment

Bus Creator

Bus Selector

Data Store Memory

Demux

From

Goto

Goto Tag Visibility

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

Repeating Sequence Interpolated

Repeating Sequence Stair

User-Defined Functions

MATLAB Function (MATLAB Function Block)

Supported Stateflow Blocks


The coder supports the following Stateflow blocks.

Stateflow

Chart

State Transition Table

Truth Table

Blocks with Restricted Support


Simulink Block Support Exceptions

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.

Stateflow Chart Exceptions

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.

The chart Stateflow Editor dialog box is displayed.


2 Right-click in this dialog box.
3 In the context-sensitive menu, select Properties.

The Chart dialog box is displayed.


4 In the Chart dialog box, navigate to the States When Enabling parameter and select Held.
5 Click Apply and OK and save the model.

10-9
10 Supported Simulink and Stateflow Blocks

Data Store Memory Block

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).

Reciprocal Sqrt Block

The Simulink PLC Coder software does not support the Simulink Reciprocal Sqrt block signedSqrt
and rSqrt functions.

Lookup Table Blocks

Simulink PLC Coder has limited support for lookup table blocks. The coder does not support:

• Number of dimensions greater than 2


• Cubic spline interpolation method
• Begin index search using a previous index mode
• Cubic spline extrapolation method

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

Simulink PLC Coder Structured Text Code Generation


Limitations

General Limitations
The Simulink PLC Coder software does not support :

• Complex data types


• String data types
• Model reference
• Stateflow machine-parented data and events
• Stateflow messages
• Limited support for math functions
• Merge block
• Step block
• Clock block
• Signal and state storage classes
• Shared state variables between subsystems
• For Each Subsystem block
• Variable-size signals and parameters
• MATLAB System block or system objects
• MATLAB classes.
• The use of Simulink.CoderInfo Identifier name property with Simulink.Parameter and
Simulink.Signal objects.
• Simulink.Signal is supported only with data Store memory objects.
• code generation for Simulink signals that do not resolve to a Simulink.Signaldata store
memory object.
• code generation when UseRowMajorAlgorithm='on'.

Simulink PLC Coder Restrictions


The Structured Text language has inherent restrictions. As a result, the Simulink PLC Coder software
has the following restrictions:

• 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

• MATLAB 64-bit data types are not supported.

11-3
11 Limitations

Simulink PLC CoderLadder Logic Code Generation Limitations

Simulink PLC Coderplcladderlib Limitations


Simulink PLC Coder plcladderlib has these limitations:

• Only Rockwell Automation RSLogix 5000 and Studio 5000 IDEs can import ladder logic generated
using the plcladderlib library.

Ladder Diagram Import Limitations


• When importing an .L5X file that contains a continuous task, the imported Simulink model has a
sample time of -1. For periodic tasks, the sample time is the value specified in the .L5X file. Event
tasks are not supported.
• Simulink PLC Coder may not follow the same initialization order specified in the Prescan mode.
Do not read variables that are read by the Prescan mode because this leads to different behavior
in simulation of the model when compared to execution in the IDE. The affected Simulink PLC
Coder plcladderlib blocks are: OTE, ONS, OSF, OSR, CTD, CTU, TON, TOF, RTO, JSR, AOI, and
FBC
• If you Ladder Diagram implementation has multiple AOI or subroutine instances with the same
name, the software does not check if these instances refer to the same implementation. It is
recommended to use different names if these structures contain different functionality.

Ladder Diagram Modeling and Simulation Limitations


• Ladder models do not support unsigned integer types. Use signed integer instead.
• Ladder models do not support double type. Instead, use single type.
• The Rockwell Automation IDEs have limitations on the character length used for names. The
length should not be more than 40 characters. For supported name lengths consult the Rockwell
documentation.
• Label the Port numbers in the Controller Tags uniquely and sequentially, when modeling Ladder
Diagrams in Simulink.

Ladder Diagram Code Generation Limitations


• Code generation requires a controller, task, program model, AOI runner, or AOI model hierarchy
• 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.
• The Rockwell Automation IDEs have limitations on the character length used for names. The
length should not be more than 40 characters. For supported name lengths consult the Rockwell
documentation.

Ladder Diagram Verification Limitations


• Ladder test bench generation is supported for only AOI Runner block.

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

Configuration Parameters for Simulink


PLC Coder Models

• “PLC Coder: General” on page 12-2


• “PLC Coder: Comments” on page 12-12
• “PLC Coder: Optimization” on page 12-15
• “PLC Coder: Identifiers” on page 12-22
• “PLC Coder: Report” on page 12-31
12 Configuration Parameters for Simulink PLC Coder Models

PLC Coder: General

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

PLC Coder: General Tab Overview


Set up general information about generating Structured Text code to download to target PLC IDEs.

12-2
PLC Coder: General

Configuration

To enable the Simulink PLC Coder options pane, you must:


1 Create a model.
2 Add either an Atomic Subsystem block, or a Subsystem block for which you have selected the
Treat as atomic unit check box.
3 Right-click the subsystem block and select PLC Code > Options.

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

“Prepare Model for Structured Text Generation” on page 1-3

“Generate Structured Text from the Model Window” on page 1-9

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.

For version numbers of supported IDEs, see “Supported IDE Platforms”.

Settings

Default: 3S CoDeSys 2.3

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

Beckhoff TwinCAT 2.11


Generates Structured Text code for Beckhoff TwinCAT 2.11 software.
Beckhoff TwinCAT 3
Generates Structured Text code for Beckhoff TwinCAT 3 software.
KW-Software MULTIPROG 5.0
Generates Structured Text code in PLCopen XML for PHOENIX CONTACT (previously KW)
Software MULTIPROG 5.0 or 5.50.
Phoenix Contact PC WORX 6.0
Generates Structured Text code in PLCopen XML for Phoenix Contact PC WORX 6.0.
Rockwell RSLogix 5000: AOI
Generates Structured Text code for Rockwell Automation RSLogix 5000 using Add-On Instruction
(AOI) constructs.
Rockwell RSLogix 5000: Routine
Generates Structured Text code for Rockwell Automation RSLogix 5000 routine constructs.
Rockwell Studio 5000: AOI
Generates Structured Text code for Rockwell Automation Studio 5000 Logix Designer using Add-
On Instruction (AOI) constructs.
Rockwell Studio 5000: Routine
Generates Structured Text code for Rockwell Automation Studio 5000 Logix Designer routine
constructs.
Siemens SIMATIC Step 7
Generates Structured Text code for Siemens SIMATIC STEP 7.
Siemens TIA Portal
Generates Structured Text code for Siemens TIA Portal.
Siemens TIA Portal: Double Precision
Generates Structured Text code for Siemens TIA Portal. The code uses LREAL type for double
data type in the model and can be used on Siemens PLC devices that support the LREAL type.
Generic
Generates a pure Structured Text file. If the target IDE that you want is not available for the
Simulink PLC Coder product, consider generating and downloading a generic Structured Text file.
PLCopen XML
Generates Structured Text code formatted using PLCopen XML standard.
Rexroth Indraworks
Generates Structured Text code for Rexroth IndraWorks version 13V12 IDE.
OMRON Sysmac Studio
Generates Structured Text code for OMRON® Sysmac® Studio Version 1.04, 1.05, or 1.09.
Selectron CAP1131
Generates Structured Text code for Selectron CAP1131 v 11 IDE.

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

“Generate Structured Text from the Model Window” on page 1-9

Show Full Target List


View the full list of supported target IDEs in the Target IDE drop-down list. For more information,
see“Target IDE” on page 12-3. This option is available on the PLC Code Generation pane in the
Configuration Parameters dialog box.

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

Target IDE Path


Specify the target IDE installation path. The path already specified is the default installation path for
the target IDE. Change this path if your IDE is installed in a different location. This option is available
on the PLC Code Generation pane in the Configuration Parameters dialog box.

Settings

Default: C:\Program Files\3S Software

C:\Program Files\3S Software


Default installation path for 3S-Smart Software Solutions CoDeSys software Version 2.3.
C:\Program Files\3S CoDeSys
Default installation path for 3S-Smart Software Solutions CoDeSys software Version 3.3 and 3.5.
C:\Program Files\BrAutomation
Default installation path for B&R Automation Studio 3.0 and 4.0 software.
C:\TwinCAT
Default installation path for Beckhoff TwinCAT 2.11 and 3 software.
C:\Program Files\KW-Software\MULTIPROG 5.0
Default installation path for PHOENIX CONTACT (previously KW) Software MULTIPROG 5.0
software. For MULTIPROG 5.50, the installation path may be different, change accordingly.
C:\Program Files\Phoenix Contact\Software Suite 150
Default installation path for Phoenix Contact PC WORX 6.0 software.
C:\Program Files\Rockwell Software
Default installation path for Rockwell Automation RSLogix 5000 software.
C:\Program Files\Siemens
Default installation path for Siemens SIMATIC STEP 7 5.4 software.
C:\Program Files\Siemens\Automation
Default installation path for Siemens TIA Portal software.

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

“Import Structured Text Code Automatically” on page 1-17

Code Output Directory


Enter a path to the target folder into which code is generated. This option is available on the PLC
Code Generation pane in the Configuration Parameters dialog box.

Settings

Default: plcsrc subfolder in your working folder

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

“Generate Structured Text from the Model Window” on page 1-9

Generate Testbench for Subsystem


Specify the generation of test bench code for the subsystem. This option is available on the PLC
Code Generation pane in the Configuration Parameters dialog box.

Settings

Default: off

On
Enables generation of test bench code for subsystem.

Disables generation of test bench code for subsystems.

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

“Generate Structured Text from the Model Window” on page 1-9

Include Testbench Diagnostic Code


Specify the generation of test bench code with additional diagnostic information that will help you
identify output variables causing test bench failures. This option is available on the PLC Code
Generation pane in the Configuration Parameters dialog box. To enable this parameter, you must
select the Generate testbench for subsystem option

Settings

Default: off

On
Enables generation of test bench code with additional diagnostic information.

Disables generation of test bench code with additional diagnostic information.

Command-Line Information
Parameter: PLC_GenerateTestbenchDiagCode
Type: string
Value: 'on' | 'off'
Default: 'off'

See Also

“Generate Structured Text from the Model Window” on page 1-9

Generate Functions Instead of Function Block


Use this option to control whether the generated Structured Text code contains Function instead of
Function Block. This option is available for only the Phoenix Contact PC WORX or the PHOENIX
CONTACT (previously KW) Software MULTIPROG target. There are certain cases where you may not
be able to generate code with Function instead of Function Block. For example, if your Simulink
subsystem or MATLAB Function block has internal state or persistent variables. In such cases, the
software issues a diagnostic warning.

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

“Generate Structured Text from the Model Window” on page 1-9

Allow Functions with Zero Inputs


Emit a function with no inputs as a function instead of a function block. This option is available for
only the Phoenix Contact PC WORX or the PHOENIX CONTACT (previously KW) Software
MULTIPROG target.

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

“Generate Structured Text from the Model Window” on page 1-9

Suppress Auto-Generated Data Types


Use this option to control whether the generated Structured Text code contains auto-generated data
types for array types. This option is available for only the Phoenix Contact PC WORX or the PHOENIX
CONTACT (previously KW) Software MULTIPROG target.

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

“Generate Structured Text from the Model Window” on page 1-9

Emit Data type Worksheet Tags for PCWorx


Use this option to control whether datatypeWorksheet tags are represented in code generated for
Phoenix Contact PC WORX target. This option allows you to have finer control and generate multiple
datatypeWorksheet definitions.

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

“Generate Structured Text from the Model Window” on page 1-9

12-10
PLC Coder: General

Aggressively Inline Structured Text Function Calls


Using this option, you can control inlining of Structured Text function calls for Rockwell Automation
targets. By default, the software attempts to inline only math functions where possible. With this
option, the software aggressively inlines all function calls so that the generated code has less number
of Function blocks.

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

• “Generate Structured Text from the Model Window” on page 1-9


• “Generated Code Structure for Simple Simulink Subsystems” on page 2-2

12-11
12 Configuration Parameters for Simulink PLC Coder Models

PLC Coder: Comments

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

“Generate Structured Text from the Model Window” on page 1-9

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

“Generate Structured Text from the Model Window” on page 1-9

Include Block Description


Specify which block description comments are in generated files. This option is available on the PLC
Code Generation > Comments pane in the Configuration Parameters dialog box.

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

• “Propagate Block Descriptions to Code Comments” on page 1-13


• “Generate Structured Text from the Model Window” on page 1-9

12-13
12 Configuration Parameters for Simulink PLC Coder Models

Simulink Block / Stateflow Object Comments


Specify whether to insert Simulink block and Stateflow object comments. This option is available on
the PLC Code Generation > Comments pane in the Configuration Parameters dialog box.

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

“Generate Structured Text from the Model Window” on page 1-9

Show Eliminated Blocks


Specify whether to insert eliminated block comments. This option is available on the PLC Code
Generation > Comments pane in the Configuration Parameters dialog box.

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

“Generate Structured Text from the Model Window” on page 1-9

12-14
PLC Coder: Optimization

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

“Generate Structured Text from the Model Window” on page 1-9

12-15
12 Configuration Parameters for Simulink PLC Coder Models

Default Parameter Behavior


Transform numeric block parameters into constant inlined values in the generated code. This option
is available on the PLC Code Generation > Optimization pane in the Configuration Parameters
dialog box.

Description

Transform numeric block parameters into constant inlined values in the generated code.

Category: Optimization

Settings

Default: Tunable for GRT targets | Inlined for ERT targets

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

“Generate Structured Text from the Model Window” on page 1-9

Signal Storage Reuse


Reuse signal memory. This option is available on the PLC Code Generation > Optimization pane in
the Configuration Parameters dialog box.

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

• This option applies only to signals with storage class Auto.


• Signal storage reuse can occur among only signals that have the same data type.
• Clearing this option can substantially increase the amount of memory required to simulate large
models.
• Clear this option if you want to:

• Debug a C-MEX S-function.


• Use a Floating Scope or a Display block with the Floating display option selected to inspect
signals in a model that you are debugging.
• If you select Signal storage reuse and attempt to use a Floating Scope or floating Display block
to display a signal whose buffer has been reused, an error dialog box opens.

Command-Line Information

Parameter:PLC_PLCEnableVarReuse
Type: string
Value: 'on' | 'off'
Default: 'on'

See Also

“Generate Structured Text from the Model Window” on page 1-9

Remove Code from Floating-Point to Integer Conversions That Wraps


Out-Of-Range Values
Enable code removal for efficient casts. This option is available on the PLC Code Generation >
Optimization pane in the Configuration Parameters dialog box.

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

Use this parameter to optimize code generation.

Command-Line Information

Parameter: PLC_PLCEnableEfficientCast
Type: string
Value: 'on' | 'off'
Default: 'on'

See Also

“Generate Structured Text from the Model Window” on page 1-9

Generate Reusable Code


Using this option, you can generate better reusable code for reusable subsystems. For instance, if
your model contains multiple instances of the same subsystem and some instances have constant
inputs, by default, the generated code contains separate function blocks for each instance. If you
select this option, the software does not consider whether the inputs to the subsystem are constant
and generates one function block for the multiple instances.

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

• “Generate Structured Text from the Model Window” on page 1-9


• “Generated Code Structure for Reusable Subsystems” on page 2-4

Inline Named Constants


Using this option, you can control inlining of global named constants. By default, the generated code
contains named ssMethodType constants for internal states or other Simulink semantics. If you
select this option, the software replaces the named constants with its integer value.

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

• “Generate Structured Text from the Model Window” on page 1-9


• “Generated Code Structure for Simple Simulink Subsystems” on page 2-2

Reuse MATLAB Function Block Variables


You can use this option to enable reuse of MATLAB function block variables in the generated code.

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

• “Generate Structured Text from the Model Window” on page 1-9


• “Generated Code Structure for MATLAB Function Block” on page 2-12

Loop Unrolling Threshold


Specify the minimum signal or parameter width for which a for loop is generated. This option is
available on the PLC Code Generation > Optimization pane in the Configuration Parameters
dialog box.

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

“Generate Structured Text from the Model Window” on page 1-9

12-21
12 Configuration Parameters for Simulink PLC Coder Models

PLC Coder: Identifiers

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

“Generate Structured Text from the Model Window” on page 1-9

Use Subsystem Instance Name as Function Block Instance Name


Specify how you want the software to name the Function block instances it generates for the
subsystem. When you select this option, the software uses the subsystem instance name as the name
of the Function blocks in the generated code. By default, the software generates index-based instance
names.

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

“Generate Structured Text from the Model Window” on page 1-9

Override Target Default Maximum Identifier Length


If your custom target IDE version supports long name identifiers, you can use this option along with
the Maximum identifier length to specify the maximum number of characters in the generated
function, type definition, and variable names. By default, the software complies with the maximum
identifier length of standard versions of the target IDE and ignores unsupported values specified in
the Maximum identifier length.

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

“Generate Structured Text from the Model Window” on page 1-9

Maximum Identifier Length


Specify the maximum number of characters in generated function, type definition, and variable
names. This option is available on the PLC Code Generation > Identifiers pane in the
Configuration Parameters dialog box.

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

“Generate Structured Text from the Model Window” on page 1-9

12-24
PLC Coder: Identifiers

Override Target Default enum Name Behavior


Use this option to enable enum names to be used as the identifier names instead of enum values. The
PLC target IDE must support enum type.

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

“Generate Structured Text from the Model Window” on page 1-9

Generate enum Cast Function


Autogenerate the enum type conversion code. The target PLC IDE must support enum type.

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

“Generate Structured Text from the Model Window” on page 1-9

Remove Top-level Subsystem Ssmethod Type


Use this option to remove the ssmethod type from the top-level subsystem argument interface. When
this option is enabled, the software removes the ssmethod type and converts the subsystem
initialization code from switch case statement to conditional if statement. As a result, the generated
code has the same interface as the model subsystem.

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

“Generate Structured Text from the Model Window” on page 1-9

Keep Top-Level ssmethod Name the Same As Non-Top Level


Prevent renaming the SS_OUTPUT type to SS_STEP type from the top-level subsystem argument
interface. When you select this option, the software emits the same ssMethod type in the code
generation for both top and non-top level blocks.

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

“Generate Structured Text from the Model Window” on page 1-9

Generate Logging Code


With this option, you can generate code with logging instrumentation to collect run-time data on
supported PLC targets. The PLC target IDEs must have support for inout variables. For Rockwell
Automation targets, you can set up an Open Platform Communications (OPC) server and use the
Simulation Data Inspector (SDI) in Simulink to visualize and monitor the logging data.

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

“Generate Structured Text from the Model Window” on page 1-9

Use the Same Reserved Names as Simulation Target


Specify whether to use the same reserved names as those specified in the Reserved names field of
the Simulation Target pane in the Configuration Parameters dialog box. This option is available on
the PLC Code Generation > Identifiers pane in the Configuration Parameters dialog box.

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

“Generate Structured Text from the Model Window” on page 1-9

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

• Start each reserved name with a letter or an underscore.


• Each reserved name must contain only letters, numbers, or underscores.
• Separate the reserved names by using commas or spaces.

Command-Line Information
Parameter: PLC_RTWReservedNames
Type: string
Value: string
Default: ''

See Also

“Generate Structured Text from the Model Window” on page 1-9

Externally Defined Identifiers


Specify the names of identifiers for which you want to suppress definitions. This option is available on
the PLC Code Generation > Identifiers pane in the Configuration Parameters dialog box.

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

• Start each name with a letter or an underscore.


• Each name must contain only letters, numbers, or underscores.
• Separate the names by using spaces or commas.

Command-Line Information
Parameter: PLC_ExternalDefinedNames
Type: string
Value: string
Default: ''

See Also

• “Generate Structured Text from the Model Window” on page 1-9


• “Integrate Externally Defined Identifiers” on page 8-2
• Integrating User Defined Function Blocks, Data Types, and Global Variables
into Generated Structured Text

Preserve Alias Type Names for Data Types


Specify that the generated code must preserve alias data types from your model. This option is
available on the PLC Code Generation > Identifiers pane in the Configuration Parameters dialog
box.

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

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

“Generate Structured Text from the Model Window” on page 1-9

Generate Traceability Report


Specify whether to create a code generation report. This option is available on the PLC Code
Generation > Report pane in the Configuration Parameters dialog box.

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

“Generate Structured Text from the Model Window” on page 1-9

Traceability Report Limitations

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.

Generate Model Web View


To navigate between the code and the model within the same window, include the model web view in
the code generation report. This option is available on the PLC Code Generation > Report pane in
the Configuration Parameters dialog box.

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

“Generate Structured Text from the Model Window” on page 1-9

Open Report Automatically


Specify whether to open the code generation report automatically. This option is available on the PLC
Code Generation > Report pane in the Configuration Parameters dialog box.

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

“Generate Structured Text from the Model Window” on page 1-9

12-33
13

External Mode

• “External Mode Logging” on page 13-2


• “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 External Mode

External Mode Logging


With external mode logging, you can generate code from Simulink models with logging
instrumentation to collect run-time data on PLC targets. You can enable this feature by using
Generate logging code option in the configuration parameters or by using the
PLC_GenerateLoggingCode command-line property. The PLC target IDEs must have support for
inout variables. You can generate logging code for one of the following target PLC IDEs:

• 3S-Smart Software Solutions CoDeSys Version 2.3


• 3S-Smart Software Solutions CoDeSys Version 3.5
• Rockwell Automation RSLogix 5000
• Rockwell Automation Studio 5000
• Beckhoff TwinCAT 2.11
• Beckhoff TwinCAT 3
• Generic
• PLCopen XML
• Rexroth IndraWorks
• OMRON Sysmac Studio

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

Generate Structured Text Code with Logging Instrumentation


This topic assumes that you have generated Structured Text code from a Simulink model. If you have
not yet done so, see “Generate Structured Text from the Model Window” on page 1-9.

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

3 The MATLAB function block implements the following code:

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

Use the Simulation Data Inspector to Visualize and Monitor the


Logging Data
This workflow is supported for Rockwell Automation targets. This workflow shows you how to set up
an Open Platform Communications (OPC) server and use the Simulation Data Inspector in Simulink to
visualize and monitor the logging data.

Set Up and Download Code to the Studio 5000 IDE


The following procedure shows you how to create a Studio 5000 project to import the generated
logging code. You can use a similar procedure to import the generated code into an existing project.

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.

4 In ST MainRoutine, define the following tags:

Tag Name Tag Type


i0_Subsystem Subsystem
i0_Subsystem_val Subsystem_log
Init BOOL
Y1 REAL
Y2 REAL
Y3 DINT
5 The tag definition looks like the following in Studio 5000 IDE, i0_Subsystem tag is the
instance of the top subsystem AOI, the i0_Subsystem_val tag is the log data with structure
type Subsystem_log. Set the initial value of init tag to 1.

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.

Configure RSLinx OPC Server


1 Start RSLinx Classic Gateway, select the menu item DDE/OPC->Topic Configuration.
2 In the resulting pop-up dialog box, create a topic ext_demo1 by using the New button. Select the
target PLC from the PLC list.

3 Click Yes button to update the topic (ext_demo1).


4 To verify that the log data is set up on the OPC server, select the menu item Edit->Copy
DDE/OPC Link. The i0_Subsystem_val tag for log data must be shown on the RSLinx OPC
Server.

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

Ladder Diagram Instructions


14 Ladder Diagram Instructions

Instructions Supported in Ladder Diagram


The supported ladder diagram instructions are useful while importing the ladder into Simulink. The
instructions can be categorised into two:

• Instructions that are implemented in Simulink using ladder diagram blocks with same name
• Instructions that are implemented in Simulink using other ladder diagram blocks.

The table lists the instructions that map to blocks in Simulink

L5X Instructions Ladder Model Blocks


ADD ADD Block
AFI AFI Block
AND AND Block
CLR CLR Block
COP COP Block
CTD CTD Block
CTU CTU Block
DIV DIV Block
EQU EQU Block
FBC FBC Block
FLL FLL Block
GEQ GEQ Block
GRT GRT Block
JMP JMP Block
LBL LBL Block
LEQ LEQ Block
LES LES Block
MCR MCR Block
MOV MOV Block
MUL MUL Block
NCP NCP Block
NEQ NEQ Block
NOT NOT Block
OR OR Block
OTE OTE Block
OTL OTL Block
OTU OTU Block
RES RES Block
RTO RTO Block

14-2
Instructions Supported in Ladder Diagram

L5X Instructions Ladder Model Blocks


SUB SUB Block
TND TND Block
TOF TOF Block
TON TON Block
XIC XIC Block
XIO XIO Block

The special instructions that are implemented using another block in Simulink are:

• JSR instruction is implemented by using a Subroutine block.


• AOI call instruction is implemented by using an Inline AOI block

14-3
15

Ladder Diagram Blocks


15 Ladder Diagram Blocks

Ladder Diagram Blocks


The Ladder Diagram Blocks that are a part of Ladder Diagram Library are listed.

XIC XIO OTE OTL


OTU TON TOF RTO
CTU CTD RES JMP
LBL TND AFI NOP
MCR ADD SUB MUL
DIV FRD CPT AND
OR NOT ONS OSR
OSF NEQ EQU
LEQ GEQ LES GRT
MOV CLR COP FLL
Power Rail Start Power Rail Terminal RungTerminal Junction
Variable Read Variable Write PLC Controller Task
Program Subroutine Function Block (AOI)

15-2
16

Fixed Point Code Generation

• “Block Parameters” on page 16-2


• “Model Parameters” on page 16-3
• “Limitations” on page 16-4
16 Fixed Point Code Generation

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

Generating PLC Code for Multirate


Models
17 Generating PLC Code for Multirate Models

Multirate Model Requirements for PLC Code Generation


In this section...
“Model Configuration Parameters” on page 17-2
“Limitations” on page 17-2

Model Configuration Parameters


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 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

Generating PLC Code for MATLAB


Function Block

• “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

Configuring the rand function for PLC Code generation


Simulink PLC Coder generates Structured Text code for MATLAB Function blocks and Stateflow
charts that use rand functions from the library. The rand function is implemented using a pseudo
random number generator that only works with PLC IDEs supporting the uint32 data type. The
software has conformance checks to report diagnostics for incompatible targets. Currently, the
following targets have been tested for rand function support.

• 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

Width block requirements for PLC Code generation


Use a MATLAB Function block instead. In the MATLAB function on the block, use the length
function to compute input vector width.

18-3
18 Generating PLC Code for MATLAB Function Block

Workspace Parameter Data Type Limitations


If the data type of the MATLAB work space parameter value does not match that of the block
parameter used in your model, the value of the variable in the generated code is set to zero.

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 :

• Cell arrays in MATLAB Function blocks


• In MATLAB Function blocks, only standard MATLAB functions are supported. Functions from
toolboxes have not been tested and may result in issues during code generation or produce
incorrect results. For a list of standard functions supported for code generation, see the items
listed under the MATLAB category in the “Functions and Objects Supported for C/C++ Code
Generation” (Simulink) table.

18-5
19

Model Architecture and Design

• “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

Fixed Point Simulink PLC Coder Structured Text Code


Generation

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

You are now ready to:

• “Prepare Model for Structured Text Generation” on page 1-3


• “Check System Compatibility for Structured Text Code Generation” on page 1-6
• “Generate and Examine Structured Text Code” on page 1-9

19-5
19 Model Architecture and Design

Generating Simulink PLC Coder Structured Text Code For


Multirate Models

Multirate Model Requirements for PLC Code Generation


At the MATLAB command prompt type in plcdemo_multirate. Once the demo model opens up
follow the instructions below to configure the model for Structured Text code generation:

Model Configuration Parameters

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.

You are now ready to:

• “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

MATLAB Function Block Simulink PLC Coder Structured Text


Code Generation
In this section...
“Configuring the rand function for PLC Code Generation” on page 19-8
“SimulinkWidth Block Requirements for PLC Code generation” on page 19-8
“Workspace Parameter Data Type Limitations” on page 19-8
“Limitations” on page 19-8

Configuring the rand function for PLC Code Generation


Simulink PLC Coder generates structured text code for MATLAB Function blocks and Stateflow
charts that use the MATLAB rand function. You implement the rand function by using a pseudo
random number generator that works with PLC IDEs supporting the uint32 data type. The software
has conformance checks to report diagnostics for incompatible targets. These targets have been
tested for rand function support.

• 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

SimulinkWidth Block Requirements for PLC Code generation


Instead of using the Simulink Width block , inside the MATLAB Functionuse the MATLAB length
function to compute the input vector width.

Workspace Parameter Data Type Limitations


If the data type of the MATLAB work space parameter value does not match that of the block
parameter in your model, the value of the variable in the generated code is set to zero.

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

• Cell arrays in MATLAB Function blocks are not supported.


• If you want to use a function from a toolbox within the MATLAB Function block, you must check
the toolbox function page to see if that block supports code generation from Simulink PLC Coder.

19-9
20

PLC Coder Code Deployment

• “Deploy Structured Text” on page 20-2


• “Deploy Ladder Diagram” on page 20-5
20 PLC Coder Code Deployment

Deploy Structured Text


In this section...
“Learning Objectives” on page 20-2
“Prerequisites” on page 20-2
“Workflow” on page 20-2
“Importing Generated Structured Text Code Manually” on page 20-2

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

Importing Generated Structured Text Code Manually


If your target IDE does not automatically import generated code:

1 Right-click the Subsystem block and select PLC Code > Options.

The Configuration Parameters dialog box is displayed.

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

Deploy Ladder Diagram


In this section...
“Learning Objectives” on page 20-5
“Prerequisites” on page 20-5
“Workflow” on page 20-5
“Importing Generated Ladder Diagram Code Manually” on page 20-5

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.

Importing Generated Ladder Diagram Code Manually


For L5X import file generation:

1 Right-click the Motor Controller block and select PLC Code > Options.

This displays the PLC Code Generation configuration parameters window:

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

Simulink PLC Coder Structured Text


Code Generation For Simulink Data
Dictionary (SLDD)

• “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)

Structured Text Code Generation Support for Simulink Data


Dictionary
Simulink Data Dictionary (SLDD) is the preferred Model-Based-Design (MBD) data modeling and
management tool. SLDD provides advantages such as data separation, logical partitioning,
traceability, and so on. To achieve traceability between your generated code and model, and for code
reusability and model and data sharing, use 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

Generate Structured Text Code For Simulink Data Dictionary


Defined Model Parameters
In this section...
“Learning Objectives” on page 21-3
“Requirements” on page 21-3
“Workflow” on page 21-3

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.

1 Open the plcdemo_tunable_params model .


2 From the Simulink Editor Modeling tab, click Model Explorer.
3 Under the Model Hierarchy pane, click Base Workspace . The Contents pane displays the
base workspace variables.
4 Right-click K1, K2, and K3. Choose the Convert to parameter object option to convert
them to the Simulink.Parameter type.
5 Right-click plcdemo_tunable_params, and then select Properties.
6 Select the External Data tab.
7 Click New. Enter the file name as plcdemo_tunable_params.
8 Click the Migrate data button. Then click Apply in response to the Link Model to Data
Dictionarymessage and Migrate in response to the Migrate Data message.
9 Click OK.

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

Simulink PLC Coder Structured Text


Code Generation For Enumerated Data
Type

• “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

Structured Text Code Generation Support for Enumerated Data


Type Conversion
This example shows how to autogenerate structured text code for the enum to integer conversion
model

Load enum class

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.

Open Simulink Model

To open the Simulink test bench model, use the following command.

open_system('menum_cast_enum_convert_int')

Configure Subsystem For Enum To Integer Function Generation

To auto generate structured text code for the enum to int conversion, use “Generate enum Cast
Function” on page 12-25.

1 Open Simulink PLC Coder.


2 Select the Subsystem block.
3 Click Settings. Navigate to PLC Code Generation > Identifiers. Select the checkbox next to
Generate enum cast function.

22-2
Structured Text Code Generation Support for Enumerated Data Type Conversion

4 Click OK.

Generate Code for the Subsystem

To generate code for the subsystem use plcgeneratecode

generatedfiles = plcgeneratecode('menum_cast_enum_convert_int/Subsystem');

### Generating PLC code for 'menum_cast_enum_convert_int/Subsystem'.


### Using <a href="matlab:configset.showParameterGroup('menum_cast_enum_convert_int', { 'PLC Code
### Gathering test vectors for PLC testbench.
### Begin code generation for IDE <a href="matlab:configset.showParameterGroup('menum_cast_enum_c
### Emit PLC code to file.
### PLC code generation successful for 'menum_cast_enum_convert_int/Subsystem'.
### Generated files:
<a href="matlab: edit('tb\menum_cast_enum_convert_int.exp')">tb\menum_cast_enum_convert_int.exp</

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

Distributed Code Generation with


Simulink PLC Coder

• “Use PLC_RemoveSSStep for Distributed Code Generation” on page 23-2


• “Structured Text Code Generation for Subsystem Reference Blocks” on page 23-6
• “Distributed Code Generation Limitations” on page 23-8
23 Distributed Code Generation with Simulink PLC Coder

Use PLC_RemoveSSStep for Distributed Code Generation


This example shows how to generate structured text code for different components of your model,
and then allow external integration by keeping ssMethod case names the same.

Open model

Open the model by using the following command:

open_system('mSystemIntegration');

23-2
Use PLC_RemoveSSStep for Distributed Code Generation

23-3
23 Distributed Code Generation with Simulink PLC Coder

Configure Model Components for Distributed Code Generation

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

1 Open Simulink PLC Coder.


2 Select the Subsystem1 block.
3 Click Settings. Navigate to PLC Code Generation > Identifiers. Select the check box next to
Keep top level ssMethod name same as non-top level.
4 Click OK.
5 Repeat steps 2 through 4 for SubSystem2, SubSystem3, and TopSystem.

Generate Code for the Subsystem

To generate code for the individual subsystem use, plcgeneratecode function:

plcgeneratecode('mSystemIntegration/TopSystem/SubSystem1');
plcgeneratecode('mSystemIntegration/TopSystem/SubSystem2');
plcgeneratecode('mSystemIntegration/TopSystem/SubSystem3');

### Generating PLC code for 'mSystemIntegration/TopSystem/SubSystem1'.


### Using <a href="matlab:configset.showParameterGroup('mSystemIntegration', { 'PLC Code Generati
### Gathering test vectors for PLC testbench.
### Begin code generation for IDE <a href="matlab:configset.showParameterGroup('mSystemIntegratio
### Emit PLC code to file.
### Creating PLC code generation report <a href="matlab:web('C:\TEMP\Bdoc20a_1326390_8984\ib9D036
### PLC code generation successful for 'mSystemIntegration/TopSystem/SubSystem1'.
### Generated files:
<a href="matlab: edit('codesys23_plcsrc\SubSystem1.exp')">codesys23_plcsrc\SubSystem1.exp</a>
### Generating PLC code for 'mSystemIntegration/TopSystem/SubSystem2'.
### Using <a href="matlab:configset.showParameterGroup('mSystemIntegration', { 'PLC Code Generati
### Gathering test vectors for PLC testbench.
### Begin code generation for IDE <a href="matlab:configset.showParameterGroup('mSystemIntegratio
### Emit PLC code to file.
### Creating PLC code generation report <a href="matlab:web('C:\TEMP\Bdoc20a_1326390_8984\ib9D036
### PLC code generation successful for 'mSystemIntegration/TopSystem/SubSystem2'.
### Generated files:
<a href="matlab: edit('codesys23_plcsrc\SubSystem2.exp')">codesys23_plcsrc\SubSystem2.exp</a>
### Generating PLC code for 'mSystemIntegration/TopSystem/SubSystem3'.
### Using <a href="matlab:configset.showParameterGroup('mSystemIntegration', { 'PLC Code Generati
### Gathering test vectors for PLC testbench.
### Begin code generation for IDE <a href="matlab:configset.showParameterGroup('mSystemIntegratio
### Emit PLC code to file.
### Creating PLC code generation report <a href="matlab:web('C:\TEMP\Bdoc20a_1326390_8984\ib9D036
### PLC code generation successful for 'mSystemIntegration/TopSystem/SubSystem3'.
### Generated files:
<a href="matlab: edit('codesys23_plcsrc\SubSystem3.exp')">codesys23_plcsrc\SubSystem3.exp</a>

Generate Code for the Integrated Model

To generate code for the integrated model:

plcgeneratecode('mSystemIntegration/TopSystem');

23-4
Use PLC_RemoveSSStep for Distributed Code Generation

### Generating PLC code for 'mSystemIntegration/TopSystem'.


### Using <a href="matlab:configset.showParameterGroup('mSystemIntegration', { 'PLC Code Generati
### Gathering test vectors for PLC testbench.
### Begin code generation for IDE <a href="matlab:configset.showParameterGroup('mSystemIntegratio
### Emit PLC code to file.
### Creating PLC code generation report <a href="matlab:web('C:\TEMP\Bdoc20a_1326390_8984\ib9D036
### PLC code generation successful for 'mSystemIntegration/TopSystem'.
### Generated files:
<a href="matlab: edit('codesys23_plcsrc\mSystemIntegration.exp')">codesys23_plcsrc\mSystemIntegra

23-5
23 Distributed Code Generation with Simulink PLC Coder

Structured Text Code Generation for Subsystem Reference


Blocks
This example shows how to autogenerate structured text code for subsystem reference blocks.

Open Simulink Model

To open the Simulink test bench model, use the following command.
open_system('mSubSysRefSystemIntegration')

23-6
Structured Text Code Generation for Subsystem Reference Blocks

Generate Code for the Subsystem

To generate code for the subsystem use plcgeneratecode

generatedfiles = plcgeneratecode('mSubSysRefSystemIntegration/TopSystem');

### Generating PLC code for 'mSubSysRefSystemIntegration/TopSystem'.


### Using <a href="matlab:configset.showParameterGroup('mSubSysRefSystemIntegration', { 'PLC Code
### Begin code generation for IDE <a href="matlab:configset.showParameterGroup('mSubSysRefSystemI
### Emit PLC code to file.
### Creating PLC code generation report <a href="matlab:web('C:\TEMP\Bdoc20a_1326390_8984\ib9D036
### PLC code generation successful for 'mSubSysRefSystemIntegration/TopSystem'.
### Generated files:
<a href="matlab: edit('plcsrc\mSubSysRefSystemIntegration.exp')">plcsrc\mSubSysRefSystemIntegrati

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

Distributed Code Generation Limitations


The Simulink PLC Coder software does not support:

• Code generation inside subsystem reference blocks.


• Code generation for nested subsystem reference blocks.

See Also

23-8

You might also like