You are on page 1of 279

Overview

TwinCAT 3 New Automation Technology

Training fr Umsteiger

Presentation of the system

TwinCAT 3 New Automation Technology

Training fr Umsteiger

Overview of contents

Motivation why
TwinCAT 3
eXtended Automation
(XA) overview
Architecture (XAA)
Engineering (XAE)
Runtime (XAR)

Connectivity
TwinCAT 2 Migration
Functions
TwinCAT 3 | Overview

23.05.2012

Motivation why TwinCAT 3


Integration of PLC, Motion and HMI in one software on one CPU
Scalable hardware
Scalable software modules
Reduced interface complexity
Improved diagnosis
One project storage place for hardware and software
One debugging environment
PC-based control technology as open control concept
Program - abstraction as principle
Functions implemented in software
Independent of the hardware employed
Scalability in performance and costs due to the use of standard CPUs
Automation and IT world share the same advantages of PC technology:
Continuous increase in performance
Continuous reduction in costs
TwinCAT 3 | Overview

23.05.2012

eXtended Automation (XA) overview


Architecture (XAA)

Engineering (XAE)

Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

eXtended Automation (XA)


Architecture (XAA)
eXtended
Architecture (XAA)

TcCOM

Safety

C++
Module

TcCOM

TcCOM

TcCOM

eXtended
Automation
Runtime (XAR)

PLC

TcCOM

Modular runtime system


NC

TwinCAT 3
eXtended
Automation (XA)
eXtended
Automation
Engineering (XAE)

TwinCAT 3 development environment


based on Visual Studio 2010
TwinCAT 3
Standard

TwinCAT 3
Integrated

Visual Studio
2010 Shell

Visual Studio
2010

TwinCAT 3 | Overview

23.05.2012

eXtended Automation (XA)


Architecture (XAA): subdivision into
engineering/runtime
eXtended Automation
Engineering (XAE)

eXtended Automation
Runtime (XAR)

Visual Studio 2010 for


real-time programming in
IEC 61131-3 and C/C++

Execution of the created


modules in real-time

Visual Studio 2010 for


the configuration of the
complete system

Support for multi-core


CPUs
Support for 64-bit systems

TwinCAT 3 | Overview

23.05.2012

Architecture (XAA)
PC System
Windows 32/64 bit
TwinCAT 3 Engineering Environment based on Visual Studio
System Manager
- Configuration

Programming
- IEC 61131-3
- objectoriented extensions
- C/C++

eXtended
Automation Engineering (XAE)

TwinCAT Transport Layer - ADS


TwinCAT 3 Runtime

TcCOM

TcCOM

CPLC
Module

C++
PLC
Module

TcCOM

Simulink
PLC
Module

NC
PLC

TcCOM

TcCOM

CNC
PLC

Safety
PLC

TcCOM

TcCOM

PLC
PLC

TcCOM

Real-time Kernel

PLC
PLC

eXtended
Automation Runtime (XAR)

TwinCAT Automation Device Driver - ADD

Fieldbus
TwinCAT 3 | Overview

23.05.2012

eXtended Automation (XA) overview


Architecture (XAA)

Engineering (XAE)

TwinCAT 3 Standard
TwinCAT 3 Integrated
System Manager
PLC
Motion Control
C/C++ programming
Matlab/Simulink
Integration
C#/ .NET programming

Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

eXtended Automation
Engineering (XAE)

TwinCAT 3 | Overview

23.05.2012

10

eXtended Automation
Engineering (XAE)
eXtended Automation Engineering (XAE)
TwinCAT 3
One programming environment
One project folder
One debugging environment for IEC and C/C++ - code
Integration of the familiar TwinCAT System Manager
Programming in IEC 61131-3 3rd Edition (NEU:
NEU object-orientated extension)
Real-time programming in C/C++
Integration and sequence of the C/C++ - program in the IEC environment or
execution as independent real-time code
Link to Matlab/Simulink
TwinCAT 2 PLC projects can be converted into a TwinCAT 3 PLC project
The old TwinCAT System Manager file (*.tsm file) can be converted
Embedded in Microsoft Visual Studio 2010
TwinCAT 3 | Overview

23.05.2012

11

eXtended Automation
Engineering (XAE) - variants
TwinCAT 3 Standard
Based on the Microsoft
Visual Studio Shell
Integrated System
Manager
Integrated IEC-61131-3
3rd edition programming
(OOP)
Integrated Safety PLC

TwinCAT 3 Integrated
Integration in an existing
Microsoft Visual Studio 2010
Integrated System Manager
Integrated IEC-61131-3 3rd
edition programming (OOP)
Integrated Safety PLC
C/C++ programming
Matlab/Simulink
C# and .NET programming for
non-real-time applications
Optional: implementation of thirdparty software tools
TwinCAT 3 | Overview

23.05.2012

12

Engineering (XAE)
TwinCAT 3 Standard

For (standard) PLC


programmers and users
of existing, compiled
modules (e.g. C/C++,
Matlab/Simulink)

TwinCAT 3 Engineering Environment

System Manager
Configuration
I/O
PLC
MC
NC
CNC
Safety
others

Configuration,
parameterisation and
diagnosis
Debugging of the PLC
code

Programming

IEC 61131

Objectoriented
extensions

IEC Compiler

TwinCAT Transport Layer ADS

TwinCAT 3 Runtime

TwinCAT 3 | Overview

23.05.2012

13

Engineering (XAE)
TwinCAT 3 Integrated

For PLC and C/C++


programmer
Configuration,
parameterisation
and diagnosis
Module development
(C/C++ or
Matlab/Simulink)
Debugging (PLC,
C/C++,
Matlab/Simulink)

Matlab/
Simulink

TwinCAT 3 Engineering Environment based on Visual Studio


System Manager
Configuration
I/O
PLC
C/C++
MC
NC
CNC
Safety
others

Third-party
programming
tool

Programming
Non
real-time

Real-time

C#.NET

IEC 61131

Objectoriented
extensions

IEC Compiler

Real-time
Workshop

C/C++

C/C++

Microsoft C Compiler

TwinCAT Transport Layer ADS

TwinCAT 3 Runtime

TwinCAT 3 | Overview

23.05.2012

14

Engineering (XAE)
TwinCAT 3 Integrated integrated working area
Workbench integration - integrated working area
TwinCAT 3 framework = Microsoft Visual Studio 2010
Use of the commonest development environment
Supported by Microsoft

Ultimate

Extendable via plug-ins (e.g. third party modules)


Usable with many common source-safe databases
Use of C/C++ source code for the programming of automation
devices
Use of .NET languages for non-real-time applications (e.g.
visualisations)

Professional

Improved help system on the basis of Microsoft Visual Studio


2010 Help (Microsoft Help system)
Premium
TwinCAT 3 | Overview

23.05.2012

15

Engineering (XAE)
Parallel programming of IEC 61131 and C++
C++ Code

IEC Code

TwinCAT 3 | Overview

23.05.2012

16

eXtended Automation (XA) - overview


Architecture (XAA)

Engineering (XAE)

TwinCAT 3 Standard
TwinCAT 3 Integrated
System Manager
PLC
Motion Control
C/C++ programming
Matlab/Simulink
Integration
C#/ .NET programming

Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

17

Engineering (XAE)
Integrated System Manager | Directory tree

System configuration

Motion control configuration

PLC configuration
Safety PLC configuration
C++ module configuration
I/O configuration
TwinCAT 3 | Overview

23.05.2012

18

Engineering (XAE)
Integrated System Manager | Mapping
Mapping of the process image
Open for all common fieldbuses
Support for all PC hardware interfaces
Simple diagnosis of the fieldbus data
Correlation between logical and physical fieldbus
A change of the bus system does not entail a
change of the PLC code!
TwinCAT process images
Virtual
process
images

Physical
process
images

Inputs

Inputs

Outputs

Fieldbus 1

Outputs

Inputs

Outputs

Inputs

Fieldbus 2
TwinCAT 3 | Overview

Outputs

Fieldbus 3
23.05.2012

19

eXtended Automation (XA) - overview


Architecture (XAA)

Engineering (XAE)

TwinCAT 3 Standard
TwinCAT 3 Integrated
System Manager
PLC
Motion Control
C/C++ programming
Matlab/Simulink
Integration
C#/ .NET programming

Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

20

Engineering (XAE)
TwinCAT 3 PLC
Multiple numbers of PLC projects:
Number of possible tasks: 65,000 (compare here to TwinCAT 2: 4x4)
Number of possible PLC projects limited only by the memory capacity of the automation
device (instead of 4 runtime systems in TwinCAT 2)
Programming
Standard IEC 61131-3 languages (IL, ST, FBD, LD, SFC) +CFC
Use of the object-orientated extensions of IEC 61131-3, 3rd edition
Call and data exchange of code developed in C/C++ and Matlab/Simulink
Large number of import and export interfaces
No direct addressing (necessary)
Commissioning/maintenance
Source code upload/download
Online Change
Complete debugging (breakpoints, monitoring, sequence control etc.) of IEC and C/C++
code

TwinCAT 3 | Overview

23.05.2012

21

Engineering (XAE)
TwinCAT 3 PLC | Development environment
Common tree structure for hardware and software

Common output of diagnosis and error messages (PLC, C++, system etc.)
TwinCAT 3 | Overview

23.05.2012

22

eXtended Automation (XA) - overview


Architecture (XAA)

Engineering (XAE)

TwinCAT 3 Standard
TwinCAT 3 Integrated
System Manager
PLC
Motion Control
C/C++ programming
Matlab/Simulink
Integration
C#/ .NET programming

Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

23

Engineering (XAE)
TwinCAT 3 Motion Control
Scalable solutions (from stepper motor to servo)
Higher flexibility in use and exchange of technology
Shortened development time faster delivery
Fast commissioning, diagnosis and maintenance
Abstraction level - identical access:
PLC/SCADA/HMI always access the same objects, irrespective of the type of
axis or fieldbus employed.
Conversion of mechanical to electronic systems:
Electronic cam plate
Electronic gearing
Electronic coupling
Electronic cam shaft
Flying saw

TwinCAT 3 | Overview

23.05.2012

24

+
PLC

SP

Pos Ctrl
-

Velo Preset

Limit
+

+
Scale & Limit

Pos Meas.

Drives
Layer

Fieldbus
Layer

Soft Motion
Layer

Soft SPS
Layer

Engineering (XAE)
TwinCAT 3 Motion Control | Abstraction level

TwinCAT 3 | Overview

23.05.2012

25

Engineering (XAE)
TwinCAT 3 Motion Control | From PTP to Robot Control
Covered functionality

NC PTP

NC I

CNC

Robotics

Point-to-Pointmovement

Interpolated motion
with 3 axes and
5 additional axes

Complete CNC
functionality

Interpolated motion
for robotic control

interpolated
movement for
up to 32 axes
per channel
various
transformations

support for a wide


rande of kinematic
systems
optional torque
pre-control

gearing
camming
superposition
flying saw

programming
according to DIN 66025
technological features
straightforward
utilisation through
function blocks from
the PLC

TwinCAT 3 | Overview

23.05.2012

26

eXtended Automation (XA) - overview


Architecture (XAA)

Engineering (XAE)

TwinCAT 3 Standard
TwinCAT 3 Integrated
System Manager
PLC
Motion Control
C/C++ programming
Matlab/Simulink
Integration
C#/ .NET programming

Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

27

Engineering (XAE)
C/C++ programming languages
Reusability of already existing C/C++ code
Common use of C/C++ and PLC code
Real-time applications available for all platforms (CE, 7)
Opening up of a completely new world for automation technology
Renowned and well-known programming language
Standardised (C: ISO/IEC 9899 TC3, C++: IEC 14882)
The creation of Automation Device Drivers (ADD) enables you to implement your
own drivers (e.g. for your own fieldbus system or the like)
Beckhoff SDK supports (similar to PLC libraries)
ADS
No t
et a
yMotion
vaila
File I/O ble!

TwinCAT 3 | Overview

23.05.2012

28

Engineering (XAE)
C/C++ programming languages | Integration

TwinCAT 3 | Overview

23.05.2012

29

eXtended Automation (XA) - overview


Architecture (XAA)

Engineering (XAE)

TwinCAT 3 Standard
TwinCAT 3 Integrated
System Manager
PLC
Motion Control
C/C++ programming
Matlab/Simulink
Integration
C#/ .NET programming

Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

30

Engineering (XAE)
Matlab/Simulink
Well-known from science and measurement technology
Large variability of toolboxes (e.g. fuzzy etc.)
Generation, simulation and optimisation of controller structures
Debug interface between Simulink and TwinCAT
Code generation
Design: Simulink
Automatic generation of C code by the Simulink real-time workshop
Compilation with the Visual Studio C compiler
Parameterisation in the TwinCAT System Manager
Download and execution in the TwinCAT 3 runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

31

Engineering (XAE)
Matlab/Simulink | Integration

TwinCAT 3 | Overview

23.05.2012

32

eXtended Automation (XA) - overview


Architektur (XAA)

Engineering (XAE)

TwinCAT 3 Standard
TwinCAT 3 Integrated
System Manager
PLC
Motion Control
C/C++ programming
Matlab/Simulink
Integration
C#/ .NET programming

Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

33

Engineering (XAE)
C#/.NET programming

HMI/
Windows processes

PLC module
C++ module
Real-time Code

TwinCAT 3 | Overview

23.05.2012

34

eXtended Automation (XA) - overview


Architecture (XAA)

Engineering (XAE)

Runtime (XAR)

Modular runtime system


TwinCAT modules
Multi-core support

TwinCAT 3 | Overview

23.05.2012

35

eXtended Automation
Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

36

eXtended Automation
Runtime (XAR) | Modular runtime systems
Debugging

PLC
C++
Module

Task

TcCOM

Task

TcCOM

TcCOM

Call

PLC
Simulink
Module

PLC
CNC
Task

Task

PLC
NC

Call

PLC
PLC

C++
Module

TcCOM

Task

TcCOM

Task

Call

PLC
C
Module

TcCOM

PLC

TcCOM

Task

TcCOM

TwinCAT Object Manager

TcCOM

Firmly defined interface (e.g. TwinCAT


Component Object Model - TcCOM)

TC Configuration

TcCOM

Management of the modules with the


TwinCAT Object Manager

TwinCAT Transport Layer - ADS

TwinCAT Real-time
Kernel

Dynamic environment for the execution


and management of TwinCAT 3
modules
Standard PLC code
NC code
C++ code

PLC
Simulink
Module

PLC
Safety
TwinCAT 3 Runtime

TwinCAT Automation Device Driver - ADD

Fieldbus

TwinCAT 3 | Overview

23.05.2012

37

eXtended Automation
Runtime (XAR) | TwinCAT modules
Must
Description (methods, functions, names
etc.)
StateMachine (Init, PreOp, Op)
TcCom Interface

TwinCAT Module
Module Description
State Machine
ITComObject Interface

Can

Interfaces

Parameter

Interfaces
Pointers

Interfaces
Parameter
Data Areas

Contexts

Data Areas

Categories

ADS Port

TwinCAT 3 | Overview

Data Area
Pointers

23.05.2012

38

eXtended Automation
TwinCAT 3 Multi-core support

TwinCAT 3 | Overview

23.05.2012

39

Runtime (XAR)
TwinCAT 3 Multi-core support
Support for multi-core systems
Assignment of the individual projects to
different cores
PLC, NC, HMI etc. each assigned
to their own core
Scalable basic time for each core
Scalable CPU limit adjustable for each
core

Multi-core CPU
Core 0

Core 1

Core 2

Core 3

Core ...

Windows
Apps

PLC Control

User HMI

PLC Runtime 0

PLC Runtime 1

NC Runtime 1

Windows
Drivers

ADS

ADS

ADS

Task 0 Task 1
ADS

ADS

ADS Router Engine

L2 Shared Cache

ADS Router Message Queues

System Memory

TwinCAT 3 | Overview

23.05.2012

40

Runtime (XAR)
TwinCAT 3 Multi-core support | Assignment
Activation of the cores

Definition of the CPU limits


Definition of the basic time

Assignment of the task to the core/CPU

TwinCAT 3 | Overview

23.05.2012

41

Overview of contents

Motivation why
TwinCAT 3
eXtended Automation
(XA) - overview
Architecture (XAA)
Engineering (XAE)
Runtime (XAR)

Connectivity
TwinCAT 2 Migration
Functions
TwinCAT 3 | Overview

23.05.2012

42

eXtended Automation
Connectivity

TwinCAT 3 | Overview

23.05.2012

43

eXtended Automation
Connectivity | ADS to Communication
(PLC) PC 1

(PLC) PC 2

TwinCAT
TwinCAT

TwinCAT

TwinCAT

Automation
Protocols

Industry
Protocols

IT
Protocols

Web
Server Ils

TwinCAT

Automation
Device
Specification
(ADS)

OPC UA,
Modbus
TCP, Modbus
RTU
3964R/RK512

IEC 61850,
IEC 61400-25,
IEC 60870-510x,
BACnet, FIAS,
Creston

WLAN,
Bluetooth,
TCP, UDP,
RAS,
FTP, VPN,
SNMP, SNTP,
SMS, SMTP

XML, AJAX,
ASP,
DPWS/WSD

Automation
Device
Specification
(ADS)

TwinCAT ADS Router

Acyclic
TCP, UDP, Serial,
Fieldbus

TwinCAT ADS
Router

Cyclic
EtherCAT Automation
Protocol (EAP),
Network variables

TwinCAT 3 | Overview

23.05.2012

44

Overview of contents

Motivation why
TwinCAT 3
eXtended Automation
(XA) - overview
Architecture (XAA)
Engineering (XAE)
Runtime (XAR)

Connectivity
TwinCAT 2 Migration
Functions
TwinCAT 3 | Overview

23.05.2012

45

eXtended Automation
TwinCAT 2 Migration | Opening old projects
The opening of projects created with TwinCAT 2 results in:
1.) Conversion of old projects to the TwinCAT 3 format
Process can not be undone!
TwinCAT 3 projects can not be saved in the TwinCAT 2 project format!
Conversion of existing TwinCAT 2 projects to the TwinCAT 3 format means:
Extension of the project by new features
Increased reusability of the existing code in new project parts
Use of the same tools for all projects
Conversion of PLC Control and System Manager files

TwinCAT 3 | Overview

23.05.2012

47

Overview of contents

Motivation why
TwinCAT 3
eXtended Automation
(XA) - overview
Architecture (XAA)
Engineering (XAE)
Runtime (XAR)

Connectivity
TwinCAT 2 Migration
Functions
TwinCAT 3 | Overview

23.05.2012

48

eXtended Automation
TwinCAT Functions
The previously familiar TwinCAT supplements also exist in TwinCAT 3
The designation changes to TwinCAT Functions: TFxxxx

TwinCAT 2 supplement licences


cannot be used in TwinCAT 3!
New (if necessary trial) licences
must be generated for this.

TwinCAT 3 | Overview

23.05.2012

49

TwinCAT 3 | New Automation Technology

Overview

Training fr Umsteiger
Thank you very much for your
attention!

New Automation Technology

01.10.2012

eXtended Automation (XA) - overview


Architecture (XAA)

Engineering (XAE)

Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

eXtended Automation (XA)


Architecture (XAA)
eXtended
Architecture (XAA)

TcCOM

Safety

C++
modules

TcCOM

TcCOM

TcCOM

eXtended
Automation
Runtime (XAR)

PLC

TcCOM

Modular runtime system


NC

TwinCAT 3
eXtended
Automation (XA)
eXtended
Automation
Engineering (XAE)

TwinCAT 3 development environment


based on Visual Studio 2010
TwinCAT 3
Standard

TwinCAT 3
Integrated

Visual Studio
2010 Shell

Visual Studio
2010

23.05.2012

eXtended Automation (XA)


Architecture (XAA) - notebook example (XAE) CX
eXtended
Automation
Engineering (XAE)

TwinCAT 3 development environment


Visual Studio 2010
TwinCAT 3
Standard

TwinCAT 3
Integrated

Visual Studio
2010 Shell

Visual Studio
2010

eXtended
Automation
Runtime (XAR)

TwinCAT 3 | Overview

23.05.2012

eXtended Automation (XA)


Architecture (XAA) - notebook example (XAE) CX
Ethernet interface used as
programming interface

eXtended
Automation
Runtime (XAR)

TcCOM

Safety

C++
modules

TcCOM

TcCOM

TcCOM

PLC

TcCOM

Modular runtime system


NC

EtherCAT

TwinCAT 3 | Overview

23.05.2012

eXtended Automation (XA)


Architecture (XAA) - notebook example (XAE) CX
TwinCAT 3 development environment on
notebook

TwinCAT 3 runtime on CX /IPC

TwinCAT 3
Standard / Integrated
TwinCAT Transport Layer - ADS
TwinCAT 3 Runtime
Real-time Kernel

Simulink
PLC
modules

C++
PLC
modules

PLC
PLC

IO

TwinCAT Transport Layer - ADS

CNC
PLC

TwinCAT 3 | Overview

23.05.2012

eXtended Automation (XA)


Architecture (XAA) - notebook example (XAE) CX
TwinCAT 3 development
environment PC

TwinCAT 3 runtime on CX /IPC

TwinCAT 3
Standard / Integrated

TwinCAT Transport Layer - ADS

Real-time Kernel
CNC
PLC

Simulink
PLC
modules

C++
PLC
modules

PLC
PLC

IO

TwinCAT Transport Layer - ADS

TwinCAT 3 Runtime

Config Mode:
to enable communication (programming)
XAE status
PC
taskbar

scanning of hardware / IO test in Freerun


Run Mode : PLC NC IO etc. operate in real-time

TwinCAT 3 | Overview

23.05.2012

eXtended Automation (XA)


Architecture (XAA) - notebook example (XAE) CX

TwinCAT XAE displays TwinCAT


state on the target system

TwinCAT on the target computer


(CX / IPC)

PC taskbar

The target computer


must be in the RUN
state in order to logon
to the PLC

Real-time load in %

TwinCAT 3 | Overview

23.05.2012

Establishment of a connection
Practical part

Establishment of a
connection

TwinCAT 3 | Overview

23.05.2012

Establishment of a connection
Requirement: TC3 is successfully installed on the programming computer and the
target computer
Hardware with PC (XAE)
Target system CX with BK1120 Bus Station

01.10.2012

10

Hardware
Example hardware
PC with TwinCAT3 XAE,
CX with EtherCAT
adaptor
TwinCAT3 XAE / XAR
on the same computer
(local)
BK1120 Bus Coupler
2* KL1XX2 2-CHANNEL
DIG IN
2* KL2XX4 4-CHANNEL
DIG OUT
1* KL2531 Stepper
Terminal
01.10.2012

11

Starting the VS2010 / 2010 shell


Taskbar TwinCAT
VS2010 symbol

01.10.2012

12

Enter higher-level headline

Starting the VS2010 / 2010 shell


New Project
XAE Project

01.10.2012

13

Setting the target system

01.10.2012

14

Establishment of a connection
To search, first select Local Target System

01.10.2012

15

Establishment of a connection

searches
for TC
controllers
IPC/ CX

Connection
to both
devices
(enter PC
target
system)

01.10.2012

16

Establishment of a connection
Logon information: user name and password for computer.
Training CX 1020
CX training:

Administrator
1

01.10.2012

17

Establishment of a connection

Connection
valid

01.10.2012

18

Establishment of a connection

01.10.2012

19

Status of connection establishment


TwinCAT XAE displays TwinCAT
state on the target system

TwinCAT on the target computer


(CX / IPC)

PC taskbar

01.10.2012

20

State of the TwinCAT symbol


TwinCAT XAE displays TwinCAT
state on the target system

The TwinCAT system on the XAE


computer must be in the Config
Mode for logging on.

The target system must


be in Config Mode for
scanning and freerun test
of the hardware

The target computer


must be in the RUN state
in order to logon to the
PLC later

Run Mode is also possible if the XAE computer


simultaneously represents a control computer
(XAR)

01.10.2012

21

Scan and Freerun


Practical part

Hardware test

Scanning
Freerun Mode

TwinCAT 3 | Overview

22

23.05.2012

Enter higher-level headline

Scan Hardware
Check Config
Mode, activate
Config Mode if
necessary
Scan

01.10.2012

23

Enter higher-level headline

Scan Hardware
Scan Hardware

01.10.2012

24

Enter higher-level headline

Freerun
In Freerun Mode,
I/O can be tested
without PLC program

01.10.2012

25

PLC Program
Practical part

Create PLC program

Generate global variables


Linkage with the hardware

TwinCAT 3 | Overview

26

23.05.2012

Enter higher-level headline

Add PLC project


Create PLC project

01.10.2012

27

Enter higher-level headline

Global Variable List


PLC project from
template
Generate global variable
list

01.10.2012

28

Enter higher-level headline

Global Variable List


Name

01.10.2012

29

Enter higher-level headline

Global Variable List


Create global variables

01.10.2012

30

Enter higher-level headline

Linking
Link

01.10.2012

31

Enter higher-level headline

Linking
Link

01.10.2012

32

Enter higher-level headline

Linking
Further links

01.10.2012

33

Enter higher-level headline

Activate
Activating the
configuration
Wait for Run Mode

01.10.2012

34

Enter higher-level headline

Activate
If TwinCAT XAR is not
registered, a 7-day
licence can be created

01.10.2012

35

Enter higher-level headline

Login
Logon to PLC project

Login

Start
PLC

PLC
Online

PLC RUN

01.10.2012

36

Online

XAE offline + PLC not in Run Mode


XAE online + PLC not in Run Mode
XAE offline + PLC in Run Mode
XAE online + PLC in Run Mode

TwinCAT in Run Mode

Enter higher-level headline

Monitoring
Global variables online

Write
Value
s
01.10.2012

38

Enter higher-level headline

Extending the program


Logout
Create FB

01.10.2012

39

Enter higher-level headline

Extending the program


Create FB

01.10.2012

40

Enter higher-level headline

Extending the program


Edit FB
Toolbox: VIEW>TOOLBOX

01.10.2012

41

Enter higher-level headline

Extending the program


Edit FB
Adapt connection with
Set output connection

01.10.2012

42

Enter higher-level headline

Extending the program


Edit FB
Adapt connection with
Set output connection

01.10.2012

43

Enter higher-level headline

Extending the program


Call block in Main (ST)
with input assistant and
Auto Declare

01.10.2012

44

Enter higher-level headline

Extending the program


Call block in Main (ST)
with input assistant
and Auto Declare

01.10.2012

45

Enter higher-level headline

Extending the program


Call block in Main (ST)
with input assistant
and Auto Declare
Configure input and
output

01.10.2012

46

Autostart
Practical part

Settings for automatic start of


the XAR

Activate boot project


Enable boot project start
Set TwinCAT autostart for
RUN

TwinCAT 3 | Overview

47

23.05.2012

Enter higher-level headline

Autostart
Boot project
Enable autostart
Creating a boot project

01.10.2012

48

Enter higher-level headline

Autostart
TwinCAT autostart

01.10.2012

49

Enter higher-level headline

Autostart
User name and
password for the
control computer

01.10.2012

50

TR3020 | Training for new users | Overview

TwinCAT 3 New Automation Technology

Training fr Umsteiger

Identifier
Indentifier serves to assign individual names to variables, data types,
functions, etc.
The identifier starts with a letter or underscore
followed by numbers, letters and underscore
No distinction is made between upper and lower case
The following are not permitted
special characters (!, , , $, etc.)
spaces
consecutive underscores
umlauts

TwinCAT Training: Programmer

01.10.2012

Keywords
Keywords are identifiers specified by IEC61131-3. They are thus fixed
components of the syntax and therefore may not be used for other
purposes.
Examples
Standard operators AND, OR, NOT
Standard types BOOL, INT, REAL...
Types TYPE, STRUCT
Block types FUNCTION, FUNCTION_BLOCK, PROGRAM

TwinCAT Training: Programmer

01.10.2012

Keywords and comments


The comments are delimited by character strings with (* or *) at the beginning
and at the end. Comments may be placed wherever spaces are also permitted.
Exception: within string literals.
(*digitale Eingnge*)
bStart AT %IX0.0 :BOOL;(*Anlagenstart*)
(*analoge Eingnge*)
TemK1 AT %IW10 (*Byte 10-11*) :WORD;
Comments to the end of the line
bStart AT %IX0.0 :BOOL; // Anlagenstart

TwinCAT Training: Programmer

01.10.2012

Elementary data types


Type

Lower

Upper

BOOL

FALSE

TRUE

Size

Prefix
x
b

BYTE

8 BIT

by

Bitstring

WORD

16 BIT

Bitstring

DWORD

32 BIT

dw

Bitstring

TwinCAT Training: Programmer

01.10.2012

Elementary data types

Detail slides
Overflows
Example: EL3102
Example: KL2531
TwinCAT Training: Programmer

01.10.2012

Data types 1: Elementary data types


Type

Lower

Upper

Size

Prefix

TIME_OF_DAY

TOD#0:0:0

TOD#23:59:
59

32 Bit

tod

DATE

D#1970:01:01

D#2106 ???

32 Bit

date

DATE_AND_TIME

DT#1970:01:01:00:00:00

DT#2106
???

32 Bit

dt

TIME

T#0s

T#49d17h2m 32BIT
47s295ms

tim

Detail slides
DT example - reading the system time
DT example - working with standard operators

TwinCAT Training: Programmer

01.10.2012

Elementary data types


Type

Lower

Upper

Size

Prefix

REAL

4 Byte

LREAL

8 Byte

lr

TwinCAT Training: Programmer

01.10.2012

Data types: STRING


Type

Description

Example

Size

Prefix

STRING

String in ASCII
code. Standard
length 80
characters.
Maximum length
255. Strings are
zero-terminated

1234ABCDE

80 +1

ABCDE$R$L
ABCDE$0D$0A

String length specifications


Example
declaration

Assignment

Result SIZEOF

Result LEN

sVar : STRING;

sVar:=ABC;

81

sVar1 :STRING(1);

sVar := X;

sVar: STRING(255);

sVar:=ABC;

256

TwinCAT Training: Programmer

01.10.2012

Data types: STRING


Constants
$<2 Hex values>

ASCII Code

$0D

CR

$R

$r

CR

$L

$l

Line Feed

$N

$n

New Line

$T

$t

Tab

Detail slides
Example: FIND
Example: string functions LEN, REPLACE
String conversion with Union

TwinCAT Training: Programmer

01.10.2012

10

Data types: WSTRING


Type

Description

Example

Description

Pre
fix

WSTRING

String in Unicode
format

Level 0,Block
0x0400-0x4FFF
Cyrillic

ws

Training, seminar

Level 0
Block 0x00000x007F
Basic Latin

TwinCAT Training: Programmer

01.10.2012

11

Data types: Examples of literals


Variable Type

Examples

BOOL

TRUE

2#1

16#1

FALSE

2#0

16#0

WORD,
DWORD

2#1010111111111110

16#AFFE

45054

INT

2#1000000000000001

16#8001

-32768

TIME

t#1h

t#60m

t#3600000ms

t#0.5d

t#12h

t#43200000ms

day

hours

min

sec

ms

ms

REAL

t#30m18s90ms

t#0.505025h

0.3333

3.333e-1

t#1818090ms

TwinCAT Training: Programmer

01.10.2012

12

Data types 1: Variable declaration el. data types


A variable possesses a name behind which a value (number, string,
date, etc.) is concealed. The variable name is a type of description of
the path to the declared data. Variables are characterised above all by
the fact that their contents can be changed at runtime.

Identifier

Data type

Initial value

bStellerUntenLinks:BOOL:=TRUE;

The physical-logical storage


location of this variable is
unknown to the user
(unlocated)

The degrees of freedom and restrictions in the


assignment of the identifiers can be found on
the slide entitled Identifiers and Prefixes
TwinCAT Training: Programmer

01.10.2012

13

Data types 1: Located variables


It is possible when declaring a variable to link the name with an
address that must be explicitly specified. For the allocation of inputs
and outputs of the hardware the incomplete location is to be carried
out with I* and Q*
Identifier

AT

%I

Data type;

%Q*

TwinCAT Training: Programmer

01.10.2012

14

Data types 1: Located variables


Completely located variables.
Identifier

AT

%I

%Q

%M

Byte

Bit

Type

Byte

These variables possess a clear address


(located)
In TwinCAT 3 incompletely located variables can be used for inputs and
outputs
Applications for %M variables can be solved simply with Unions and
direct masking

Detail slides
Detail - Replace %MB by UNION
TwinCAT Training: Programmer

01.10.2012

15

Data types 1: Address division


Examples:
IX10.7

IX10.6

IX10.5

IX10.4

IX10.3

IX10.2

IX10.1

IX10.0

Din0 AT%IX10.0 : BOOL;

IB10

IB1

IB0

Ain AT%IB0 : INT;


equivalent

IW0

Ain AT%IW0 : INT;


IX22.7

IX22.6

IX22.5

IB23

IX22.4

IX22.3

IB22

IX22.2

IX22.1

IB21

IW22

IB20
IW20

ID20

IX22.0

BitVar AT%IX22.1 : BOOL;


Posi AT%IB20 : UDINT;
equivalent

Posi AT%ID20 : UDINT;

TwinCAT Training: Programmer

01.10.2012

16

Data types 1: Variable classes, scope


Local variables are restricted
to the block in which they
were declared.
Keywords
VAR ..
END_VAR
VAR_INPUT ..
END_VAR
VAR_IN_OUT ..

Global variables are


known in each block
within a project.
Keywords
VAR_GLOBAL ..
END_VAR
VAR_CONFIG ..
END_VAR

END_VAR
VAR_OUTPUT ..
END_VAR

TwinCAT Training: Programmer

01.10.2012

17

Data types 1: I/O directly in an FB instance


In an FB the inputs and outputs to the periphery are to be created
directly as local variables

Implementation
TwinCAT Training: Programmer

01.10.2012

18

Data types 1: Access via the located variables


The variable locVar locally declared in Program B can be directly
accessed from Program A via address %MB2.

Project machine
PROGRAM A

PROGRAM B

VAR

VAR
locVar AT%MB2:WORD;
END_VAR

END_VAR

LD %MB2

TwinCAT Training: Programmer

01.10.2012

19

Data types 1: Overlaps in the scope


Project machine
VAR_GLOBAL
Var1:WORD;
END_VAR
PROGRAM A
VAR
Var1 :WORD;
END_VAR

Example
name:
Gvl1

As shown on the left, there is


an overlap in the scope.
In this case the locally
declared variable Var1 is
loaded into the accumulator.
The global variable can also
be accessed with
Namespaces.

LD Var1
LD Gvl1.Var1

TwinCAT Training: Programmer

01.10.2012

20

Data types 1: PERSISTENT attribute


Special properties of variables can be defined using attributes.
Example:
The variable(s) are saved when the PLC is shut down and loaded back on
restarting.

TwinCAT Training: Programmer

01.10.2012

21

Data types 1: Initialisation and CONSTANT


Initial values, the variables are to be preset with a certain value when
starting/resetting the PLC.
VAR
AccelerationTime : TIME := T#3s200ms;
END_VAR
Read-only:
VAR_GLOBAL CONSTANT
pi:REAL:=3.141592654;
END_VAR
VAR CONSTANT
pi:REAL:=3.141592654;

Global

Also locally
possible

END_VAR
TwinCAT Training: Programmer

01.10.2012

22

Data Types 2: Derived data types


The user can create his own data types on the basis of the elementary
data types or data types that have already been created. The newlycreated data types are visible in the entire project.
The declaration starts with TYPE and ends with END_TYPE.

Parent type

Name

Data type

New value

Derivation

Name

Data type

Initial value

Area

Inherit
ance

Initial value

Area

TwinCAT Training: Programmer

01.10.2012

23

Data Types 2: References (alias types)


The purpose of the selfdefined data type Reference is
to generate an alternative
name for a variable, constant
or function block.
Create your references as
objects in the object organiser
on the Data Types tab.
They start with the keyword
TYPE and end with
END_TYPE.

Syntax:
TYPE
<Bezeichner>:<Zuweisungsausdruck>;
END_TYPE
Type

Declaration

TwinCAT Training: Programmer

01.10.2012

24

Data Types 2: References (alias types)


Example: A global string variable is transferred to various blocks. If
changes are made to the Global Variables, the declarations must also
be changed in every block

TwinCAT Training: Programmer

01.10.2012

25

Data Types 2: References (alias types)


If a type has been created for the string, further changes are made
only to the type

TwinCAT Training: Programmer

01.10.2012

26

Data Types 2: References (alias types)


If a type has been created for the string, further changes are made
only to the type

TwinCAT Training: Programmer

01.10.2012

27

Data Types 2: References (alias types)


If a type has been created for the string, further changes are made
only to the type

TwinCAT Training: Programmer

01.10.2012

28

Data Types 2: Enumerated type (Enum)


An enumerated type is a self-defined data type consisting of a number
of string constants. These constants are called enumeration values.
The enumeration values are always known in the entire project. It is
best to create your enumerated types as objects in the object
organiser on the Data Types tab. They start with the keyword TYPE
and end with END_TYPE.
Syntax:
TYPE <Bezeichner>:(<Enum_0> ,<Enum_1>, ...,<Enum_n>);
END_TYPE
Example:
TYPE Woche:(Mo, Di, Mi, Dn, Fr, Sa, So:=10);(*Mo = 0 Di = 1..
.. Sa = 6 So = 10*)
END_TYPE
TYPE Richtung:(Up, Dn);(*Up = 0 Dn = 1*)
END_TYPE

The same enumeration value can be used twice via Namespace.


Example: Woche.Dn Richtung.Dn
TwinCAT Training: Programmer

01.10.2012

29

Data Types 2: Enumerated type (Enum)


Example: signal light without Enum:
Declaration

Use

Online

TwinCAT Training: Programmer

01.10.2012

30

Data Types 2: Enumerated type (Enum)


Example: signal light with Enum:
Type

Use

Declaration

Online

TwinCAT Training: Programmer

01.10.2012

31

Data Types 2: Structure declaration


Example: KL5101 Encoder Terminal Structures are self-defined data types.
They are an important aid to better
administration of the process data. In
addition, the structures are suitable
for encapsulated data transfer to
function blocks. Structures can be
used like individual element variables.

TwinCAT Training: Programmer

01.10.2012

32

Data Types 2: Structures instancing

ST_KL5101In_1 AT%I* : KL5101_IN


ST_KL5101Out_1 AT%Q* : KL5101_OUT

TwinCAT Training: Programmer

01.10.2012

33

Data Types 2: Arrays


Arrays represent lists or data fields. All elements in the arrays are of the
same type. Naturally arrays can also consist of own data types (structures).
One, two and three-dimensional arrays are possible.
VAR
Feld_1 :ARRAY[0..9] OF BYTE;
Feld_2 :ARRAY[0..9, 0..1] OF UINT;
Feld_3 :ARRAY[0..9, 0..1,0..1] OF DINT;
END_VAR

1-dimensional
2-dimensional
3-dimensional

There is a possibility to place a data field in a directly addressed memory


location
VAR
Feld_1 AT%MB100:ARRAY[1..10] OF BYTE;
END_VAR
Access to the sub-elements of a data field
Feld_1[2] := 120; (* Expliziter Zugriff*)
Feld_2[i,j] := EXPT(i,j); (*Indizierter Zugriff*)

TwinCAT Training: Programmer

01.10.2012

34

Data Types 2: Limit transgressions


A dangerous state can arise if an area outside the data field is
accessed in the PLC program.
VAR
Feld_1 :ARRAY[1..10] OF BYTE;
Feld_2 :ARRAY[1..10, 2..5] OF UINT;
END_VAR

i:= 9
Feld_1[i+2] := 120;

Feld_1[9];

Feld_2[1,2];

120

TwinCAT Training: Programmer

01.10.2012

35

Data Types 2: CheckBounds (FUN)


The access can be monitored by
the PLC at PLC runtime
This function enables a limit
transgression occurring in the
program to be recognised and
rectified.

FUNCTION CheckBounds :DINT


VAR_INPUT
I,L,U : DINT;
END_VAR
IF I< L THEN
Error case

CheckBounds := L;

ELSIF I > U THEN


Error case
i
Min
Max

Limited
value

CheckBounds := U;

ELSE
OK case

CheckBounds := I;

END_IF

TwinCAT Training: Programmer

01.10.2012

36

Data Types 2: Adding CheckBounds 1 (FUN)


Adding Checkbounds:

TwinCAT Training: Programmer

01.10.2012

37

Data Types 2: Adding CheckBounds 2 (FUN)

TwinCAT Training: Programmer

01.10.2012

38

Data Types 2: Method of operation of CheckBounds (FUN)


Example: user error
source code

Checkbounds is compiled-in
in XAR

10

Do not write,
it is called
automatically
(not visible in
the code)

10

9
Can be checked with call build:
TwinCAT Training: Programmer

01.10.2012

39

Note about further checker functions


The following further checker functions are possible from
TwinCAT 2.8:

Check for division by 0


CheckDivByte
CheckDivWord
CheckDivDWord
CheckDivReal

Check value ranges


CheckRangeSigned
CheckRangeUnsigned
(see appendix)

TwinCAT Training: Programmer

01.10.2012

40

Data Types 2: Combination: structures and arrays


An array can consist of structures:
Structure:
TYPE DrillPos :
STRUCT
XPos:
FeedrateX:
AccelerationX:
DeccelerationX:
JerkX:
YPos:
FeedrateY:
AcceleartionY:
DeccelerationY:
JerkY:
FeedDrill:
Kuehlen:
END_STRUCT
END_TYPE

LREAL;
LREAL;
LREAL;
LREAL;
LREAL;
LREAL;
LREAL;
LREAL;
LREAL;
LREAL;
LREAL;
BOOL; (*Pumpe ?*)

Declaration of the array:

Positions :ARRAY[0..100] OF DrillPos;


TwinCAT Training: Programmer

01.10.2012

41

Data Types 2: Combination: structures and arrays


Access to Drillpos 55:
Access:
MoveXAx (*FB Instanz*)
(
Execute:=

TRUE,

Position:=

Positions[55].XPos ,

Velocity:=

Positions[55].FeedrateX

Acceleration:=

Positions[55].AccelerationX,

Deceleration:=

Positions[55].DeccelerationX,

Jerk:=

Positions[55].JerkX,

Direction:=

.........,

Axis:=

.............,

);
TwinCAT Training: Programmer

01.10.2012

42

Block types
In IEC61131-3 there are three types of block covered by the generic
term POU (PROGRAM ORGANISATION UNIT):
Program
Function Block
Function

TwinCAT Training: Programmer

01.10.2012

43

Block types: program PRG


Program PRG
Called by a task (one program can call another)
Calls: FBs, functions, (programs)
Local variable: static, i.e. the local data are available again in the next cycle.
Inputs: usually 0, but VAR_INPUT possible
Outputs: usually 0, but VAR_OUTPUT possible
Transfer by reference VAR_IN_OUT likewise possible
Monitoring: Local data are immediately visible in the online mode of the PLC
control
Use: Main programs, Main, Manual, Automatic, etc.

TwinCAT Training: Programmer

01.10.2012

44

Block types: function block FB


Function block FB
Called by programs or other FBs
Calls: FBs, functions,
Local variable: static, i.e. the local data are available again in the next cycle.
Can be instanced in case of multiple calls (multipliable). Each FB call can have
its own local data.
Inputs: 0,1,2,3VAR_INPUT
Outputs 0,1,2,3.. VAR_OUTPUT
Transfer by reference 0,1,2,3.. VAR_IN_OUT
Monitoring: In the online mode of the PLC control the instance of the call
concerned must first be specified. The local data are then visible for each call.
Use: multiple-used modules, each of which requires its own data area. Step
chains...

TwinCAT Training: Programmer

01.10.2012

45

Block types: Function: FC


Function: FC
Called by programs, function blocks and other functions
Calls: Functions
Local variable: temporary, i.e. the local data are available only for the
processing time of the function. Afterwards this data area is used by
other functions.
Inputs:

1,2,3........ VAR_INPUT

Outputs:
precisely 1!, but structure variable possible. The name of
the output is at the same time the name of the function.
Transfer by reference

1,2,3........ VAR_IN_OUT ,

Monitoring: In the online mode of the PLC control only ??? are visible
for the local variables, since this data area is used by all functions in the
cycle and monitoring (debug) takes place only at the cycle limits.
Remedy: program development with breakpoints
Use: algorithms where the result is available after a run. Scaling,
comparison, etc.

TwinCAT Training: Programmer

01.10.2012

46

ST Structured Text: Operators


Operation
put in parentheses
Function call
Exponentiation
Negate
Build. complements
Multiply
Divide
Modulo
Add
Subtract
Compare
Equal to
Not Equal to
BOOL AND
BOOL XOR
BOOL OR

Symbol
Binding strength
(expression)
Strongest binding
Function name (parameter list)
EXPT
NOT
*
Same binding strength,
processing from left to right
/
(10/2*5 = 25 )
MOD
+
Same binding strength
<,>,<=,>=
=
<>
AND
XOR
Weakest binding
OR
TwinCAT Training: Programmer

01.10.2012

47

ST Structured Text: Instructions


Instruction

Example

Assignment:=

PosWert := 10;

Calling a Function Block

Ton1(IN:=Start, PT:=T2s); Output:= Ton1.Q;

RETURN

RETURN;

IF

more precise explanations and examples on the


following pages

CASE
FOR
WHILE
REPEAT
EXIT
Empty instruction

TwinCAT Training: Programmer

01.10.2012

48

ST: IF instruction
Is needed to branch in a program, depending on conditions. With the
IF instructions its not possible to jump back in the PLC cycle.
GOTO is also not available

Keywords:
IF

THEN

ELSIF
ELSE
END_IF

TwinCAT Training: Programmer

01.10.2012

49

ST: IF instruction

IF Condition THEN
Instruction block;
END_IF

No
Condition
Yes

Instruction block

TwinCAT Training: Programmer

01.10.2012

50

ST: IF instruction

IF a>b THEN
Instruction block A;
ELSE
Instruction block B;
END_IF

Condition

No

Yes

Instruction block A

Instruction block B

TwinCAT Training: Programmer

01.10.2012

51

ST: IF instruction
IF Condition1 THEN
Instruction block A;
ELSE
IF Condition2 THEN
Instruction block B;
Condition 1
ELSE
No
Yes
IF Condition3 THEN
Condition 2
Instruction block C;
ELSE
Yes
Instruction block D;
END_IF
END_IF
END_IF
Instruction
Instruction
block A

block B

No
Condition 3
No
Yes
Instruction
block C

Instruction
block D

TwinCAT Training: Programmer

01.10.2012

52

ST: IF instruction

IF Condition1 THEN
Instruction block A;
ELSIF Condition2 THEN
Instruction block B;
ELSIF Condition3 THEN
Instruction block C;
ELSE
Instruction block D;
END_IF

Condition 1
No
Yes
Condition 2
No
Yes
Condition 3
No
Yes
Instruction
block A

Instruction
block B

Instruction
block C

Instruction
block D

TwinCAT Training: Programmer

01.10.2012

53

ST: IF instruction
What can the BOOLEAN EXPRESSION be?
Conditions:
BOOLEAN variable
Comparison
Function calls

Querying of FB instances
NO FB call!

IF bVar THEN
.
IF a>b THEN
.
IF LEFT(STR:= strVar, SIZE:=7) =
'TwinCAT' THEN
.
IF Ton1.Q THEN
.
IF Ton1(IN:=bVar, PT:=T#1s ) THEN

TwinCAT Training: Programmer

01.10.2012

54

ST CASE Instruction
CASE Selection criterion OF
1:

Selection criterion = 2
or 4 or 6

Instruction 1

2, 4, 6: Instruction 2
7..10: Instruction 3

Selection
criterion = 1

Selection criterion = 7
or 8 or 9 or 10?

No

Yes

..

No

ELSE

Yes

Default
instructions

No
Yes

END_CASE;
Two identical values
may not be available
for selection in the list.

Instruction 1

Instruction 2

Instruction 3

Default
instructions

TwinCAT Training: Programmer

01.10.2012

55

ST: CASE instruction: possibility for a step chain /


state machine
Instructions for the step
(Actions)

CASE State OF
0:

Q0:=TRUE;
IF Transition THEN state := 1; END_IF

1:

Q1:=TRUE;
IF Transition THEN state := 2; END_IF

2:

Step-further condition
(Transition)

Q2:=TRUE;
IF Transition THEN state := 3; END_IF

3:

Q3:=TRUE;
IF Transition THEN state := 0; END_IF

END_CASE

TwinCAT Training: Programmer

01.10.2012

56

ST: CASE instruction Integer Selector Value


with constants
CASE State OF
0:

Instructions;(*State=0*)
IF THEN

Instructions
if state = 0

1:

Instructions;(*State=1*)

Instructions
if state = 1

2:

Instructions;(*State=2*)

Instructions
if state = 2

3:

Instructions;(*State=3*)

Instructions
if state = 3

END_CASE

TwinCAT Training: Programmer

01.10.2012

57

ST: CASE instruction Integer Selector Value


with Enum types

Enum-Typ:
TYPE Schritte :
(INIT:=0, START, AUTOMATIK, ENDE);
END_TYPE

CASE State OF
INIT:

Instructions;(*State=0*)

START:

Instructions;(*State=1*)

AUTOMATIK:

Instructions;(*State=2*)

ENDE:

Instructions;(*State=3*)

END_CASE

TwinCAT Training: Programmer

01.10.2012

58

ST: CASE instruction: suggestion for a step chain /


state machine
TYPE Schritte :
( INIT:=0, START, AUTOMATIK, ENDE);
END_TYPE

Instructions for the step


(Actions)

CASE State OF
INIT:

Q0:=TRUE;
IF Transition THEN state := START; END_IF

START:

Step-further condition
(Transition)

Q1:=TRUE;
IF Transition THEN state := AUTOMATIK; END_IF

AUTOMATIK: Q2:=TRUE; Step


IF Transition THEN state := ENDE; END_IF
ENDE:

Q3:=TRUE;
IF Transition THEN state := INIT; END_IF

END_CASE
TwinCAT Training: Programmer

01.10.2012

59

ST: CASE instruction Integer Selector Value


with constants
CASE State OF

VAR CONSTANT
Step1 : INT:=

0;

Step1:

Instructions;(*State=0*)

Step2 : INT:=

1;

Step2:

Instructions;(*State=1*)

Step3 : INT:=

2;

Step3..Step4:

Instructions;(*State=2 oder 3*)

Step4 : INT:=

3;

END_CASE

END_VAR
VAR
State:INT;
END_VAR

TwinCAT Training: Programmer

01.10.2012

60

ST: Repeat instructions


The process sequence often requires the multiple processing of
precisely the same program sequences, where their number is known
only at runtime.
Disadvantage of loops:
In the case of wrong programming, an infinite number of repetitions
takes place.
If a continuous loop is executed, this does not impair the start of the
time slices (real-time). Tasks with a higher priority will still be executed
on time. Tasks with a lower priority will no longer be executed.
Forced switchover
to Win NT

1
e.g.: 1ms

2
2ms

3
3ms

Begin of a new
time slice

4
4ms

1
5ms

TwinCAT Training: Programmer

01.10.2012

61

ST: Loops (overview)


All loops can be terminated with the help of the EXIT instruction,
regardless of the abort condition.

Expression

Processing

n cycle fix

FOR

SINT/INT/DINT

Instructions
Yes
follow condition

WHILE

BOOL

Instructions
No
follow condition

REPEAT

BOOL

Condition
follows
instructions

No

TwinCAT Training: Programmer

01.10.2012

62

ST: FOR loop


At the beginning of the loop the
Cycle n
control variable i is set to the
starting value (see example).
The control variable is
decremented or incremented in
each loop, depending on the step
size (value after the keyword BY).
If i exceeds the end value
(after TO), the loop is no longer
processed.
FOR i:=1 TO 12 BY 2 DO

Start i:=StartValue

Yes

i
>EndValue
No
Instruction block

i: = i + step size

Feld[i]:=i*2;(*Anweisung*)
END_FOR
Cycle n
TwinCAT Training: Programmer

01.10.2012

63

ST: WHILE loop


The instruction block of a WHILE loop
is executed continuously until the
Boolean expression returns TRUE.
The abort condition can contain
variables that can be changed in the
instruction block.
If the Boolean expression is FALSE at
the beginning, then the instruction
block of the WHILE loop is not
processed.
i:=0;
WHILE i<100 DO
Feld[i]:=i*2;(*Anweisung*)
i:=i+1;
END_WHILE

Cycle n

Yes

Boolean
expression

No

Instruction block
i: = i + step size

Cycle n
TwinCAT Training: Programmer

01.10.2012

64

ST: REPEAT loop


Cycle n

The instruction block of a REPEAT


loop is executed as long as the
Boolean expression is satisfied.
The instruction block is processed at
least once.

Instruction block
i:= i + step size

i:=0;
REPEAT
Feld[i]:=i*2;(*Anweisung*)
i:=i+1;
UNTIL i>100

No

Boolean
expression
Yes

END_REPEAT
Cycle n
TwinCAT Training: Programmer

01.10.2012

65

ST: FB calls in ST
VAR
TON1:TON;
END_VAR
TON1 (IN:= NOT TON1.Q , PT:=T#1s );
Q0:= TON1.Q;

TON1(IN:= NOT TON1.Q, PT:=T#1s , Q=>Q0 );

TwinCAT Training: Programmer

01.10.2012

66

ST: FB calls in ST (alternative)


VAR
TON1:TON;
END_VAR

TON1.IN:= NOT TON1.Q;


TON1. PT:=T#1s;
TON1();
Q0:= TON1.Q;

TwinCAT Training: Programmer

01.10.2012

67

ST: FC calls in ST
Result:=Scale (x:=Eingang, xug:=0.0, xog:=32767.0, yug:=0.0,yog:=100.0);
(* Gleichwertig:*)
Result:=Scale (Eingang, 0.0, 32767.0, 0.0, 100.0);
(* Gleichwertig:*)
Result:=Scale (

xog:=

x:=

Eingang,

xug:=

0.0,

32767.0,
yug:=

0.0,

yog:=

100.0

);
In case of functions, all inputs must be occupied
TwinCAT Training: Programmer

01.10.2012

68

ST: FC calls in ST
Result := Scale (x:=Eingang, xug:=0.0, xog:=32767.0, yug:=0.0,yog:=100.0);

Result

CALL

Input parameters

(* Gleichwertig:*)
Result:=Scale

(
x:=

Eingang,

xug:=

0.0,

xog:=

32767.0,

yug:=

0.0,

yog:=

100.0

);

TwinCAT Training: Programmer

01.10.2012

69

TwinCAT 3 | New Automation Technology

Advanced IEC features | Keywords


New keywords:
METHOD : Action on FB with own variables
PROPERTY: POE pair for Set/Get of attribute
THIS : in Method/Property for the current FB instance
SUPER : in Method for access to the basic class instance
EXTENDS : Inheritance between FBs
INTERFACE : defines abstract object type (FB without implementation)
IMPLEMENTS in the FB: Instances can be called via the named interface

Call syntax for methods:


Object.Methodname()

Special methods:
FB_Init, FB_Exit, FB_Reinit
TwinCAT 3 | Training | Object-orientated
programming in IEC

70

03.05.2012

Short information: OOP with example

TwinCAT Training: Programmer

01.10.2012

71

TwinCAT 3 | New Automation Technology

Advanced IEC features | Keywords


New keywords:
METHOD : Action on FB with own variables
PROPERTY: POE pair for Set/Get of attribute
THIS : in Method/Property for the current FB instance
SUPER : in Method for access to the basic class instance
EXTENDS : Inheritance between FBs
INTERFACE : defines abstract object type (FB without implementation)
IMPLEMENTS in the FB: Instances can be called via the named interface

Call syntax for methods:


Object.Methodname()

Special methods:
FB_Init, FB_Exit, FB_Reinit
TwinCAT Training: Programmer

01.10.2012

72

TwinCAT 3 | New Automation Technology

Advanced IEC features | Application


Object-orientated extensions of IEC 61131-3, 3rd edition:
the concept of the functional blocks has been extended by
Classes
Interfaces
Methods
Inheritance
Attributes
Keywords such as THIS, SUPER

Use of the extensions


Possible in all IEC languages
Independent of the hardware employed
Not absolutely necessary
TwinCAT Training: Programmer

01.10.2012

73

TwinCAT 3 | New Automation Technology

Advanced IEC features | SUPER and THIS


SUPER is available in every FB and represents a pointer to the basic FB instance.
THIS uses the local instance (e.g. a method).

Complete program: Sample06


TwinCAT Training: Programmer

01.10.2012

74

TwinCAT 3 | New Automation Technology

Advanced IEC features | SUPER and THIS


SUPER is available in every FB and represents a pointer to the basic FB instance.
THIS uses the local instance (e.g. a method).

TwinCAT Training: Programmer

01.10.2012

75

TwinCAT 3 | New Automation Technology

Advanced IEC features | SUPER and THIS


PUBLIC all methods can be accessed
PRIVATE can be used only in the FB. Not from outside as FB.Method()
PROTECTED cannot be overwritten in the derived FB
INTERNAL Methods Properties in a library cannot be overwritten

03.05.2012

TwinCAT Training: Programmer

01.10.2012

76

Example task
Example: a clock generator FB is to be created
that should be able to do the following:
generate a flashing cycle
generate a PWM signal (e.g. heating)
Parameter
fixed flashing time for flashing cycle
clock output for flashing signal
MaxCycles defines number of PLC cycles 100% duty cycle for PWM
generator
DCPercent; duty cycle in %
Enable: BOOL, enable for PWM signal
Vendor, name of the manufacturer as a string

TwinCAT Training: Programmer

01.10.2012

77

Standard procedure
All parameters are transferred with VAR_INPUT VAR_OUTPUT
The sub-functions are programmed in the FB and run through with the complete FB

to flashing
cycle
to PWM
generator

to flashing
cycle
to PWM
generator

TwinCAT Training: Programmer

01.10.2012

78

Standard procedure
This block is to be extended later
clock ratio of the flashing cycle is to be modified
the PWM generator is given a target profile generator (e.g. temperature profile)

Co
py
ex and
ten
d

TwinCAT Training: Programmer

01.10.2012

79

Alternative
With the new options
Methods
Features
Inheritance
Overwrite

TwinCAT Training: Programmer

01.10.2012

80

Example
A clock generator FB is to be created
Methods:
m_ClockGenerator generates the flashing cycle
M_Pwm generates a PWM signal (e.g. heating)
Features
p_CycleTime specifies flashing time for flashing cycle
p_MaxCycles defines number of PLC cycles 100% duty cycle
for PWM generator
p_Vendor
queries a string

TwinCAT Training: Programmer

01.10.2012

81

Example

FB_ClockGenerator
m_ClockGenerator()
m_Pwm()
p_Vendor
p_CycleTime

TwinCAT Training: Programmer

01.10.2012

82

The basic clock generator block is to be further developed. Name


FB_ClockGenerator_EX. All methods and properties are initially to be adopted from
the basic block.
Modifications:
the ClockGenerator method is to be given a different on/off ratio
the Vendor property is to be overwritten. (Different text)
A further method is to be created in m_PwmProfile. This method generates a
certain profile for the duty cycle (ramp) of the pwm generator (example:
temperature profile). This value is to go onto the pwm generator of the basic
class.
For execution, see training examples

TwinCAT Training: Programmer

01.10.2012

83

Example
FB_ClockGenerator
m_ClockGenerator()
m_PwmProfile()
p_Vendor
p_CycleTime

FB_ClockGeneratorEX
m_ClockGenerator() overwrite
m_PwmProfile() (new)
p_Vendor (overwrite)

TwinCAT Training: Programmer

01.10.2012

84

Extension
Block
see training examples

TwinCAT Training: Programmer

01.10.2012

85

Appendix: Standard IEC operators and FBs

The function blocks and functions are made available by integrating the
Standard.LIB. This is automatically integrated into the PLC project when
the project is created.
Standard blocks
Function Blocks
Timer

Functions
String Functions

Counter
Memory
Trigger

TwinCAT Training: Programmer

01.10.2012

86

Appendix: Logical operators

FBD /CFC

ST

Comments
BOOL
AND

WORD
AND

DWORD
AND

TwinCAT Training: Programmer

01.10.2012

87

Appendix: Numerical operators


FBD /CFC

ST

Comments
Arithmetic Operators
Overloading possible,
beware of overflow with
integers.

- * /

Determines integral
remainder of a division
(in this case 4)

TwinCAT Training: Programmer

01.10.2012

88

Appendix: Selection operators, SEL


Operator

Comments

FBD /CFC

Selection inputs can be


overloaded
SEL

ST
StrVarMode := SEL(Mode1, , Mode1Selected );

Example:
If Mode1 = TRUE, StrVarmode
contains Mode1Selected,
otherwise an empty string

TwinCAT Training: Programmer

01.10.2012

89

Appendix: Selection operators, MUX

FBD /CFC

Selection with
integer variable,
inputs can be
overloaded

ST:
Online:

TwinCAT Training: Programmer

01.10.2012

90

Appendix: Conversions
Operator

ST

Comments
Time values are resolved
in ms rt1:REAL
iT1:INT

bVar1:BOOL
Rounding up takes place:
0.4 output goes FALSE
>=0.5 output goes TRUE

TwinCAT Training: Programmer

01.10.2012

91

Appendix: Conversions
FBD /CFC

ST

Comments
Result 20000.0
Implicit conversion also
possible
Conversion to INT with
rounding up/down
Conversion to INT without
rounding up/down
Beware of overflows
(Result is negative)

TwinCAT Training: Programmer

01.10.2012

92

Appendix: Edge blocks R_TRIG F_TRIG


FBD /CFC

CLK
R_TRIG
Q
CLK
F_TRIG
Q

ST

CLK

BOOL

Trigger input

R_TRIG: Rising Edge

BOOL

Signal output (for 1 PLC cycle on)

F_TRIG: Falling Edge

TwinCAT Training: Programmer

01.10.2012

93

Appendix: Memory modules SR RS


FBD /CFC

SET1

SR

RESET1
Q1

SET1

RS

ST

RESET1
Q1

SET1

BOOL

Set

SR: priority is set

RESET1 BOOL

Reset

RS: priority is reset

Q1

Output

BOOL

TwinCAT Training: Programmer

01.10.2012

94

Appendix: Switch-on delay TON


FBD /CFC

IN
Q
ET

ST

IN

BOOL Start input

PT

TIME

BOOL Output

ET

TIME

Preset Time, delay time

Starts with edge, output is


available after delay and

Elapsed Time, current time value


TwinCAT Training: Programmer

01.10.2012

95

Appendix: Switch-off delay TOF


FBD /CFC

IN

PT

ST

IN

BOOL Start input

PT

TIME

BOOL Output

ET

TIME

Preset Time, extension

ET

Starts with falling edge on


IN, new edge extends signal

Elapsed Time, current time value


TwinCAT Training: Programmer

01.10.2012

96

Appendix: Pulse timer TP


FBD /CFC

IN
Q

ST

IN

BOOL Start input

PT

TIME

BOOL Output

ET

TIME

Preset Time, pulse time

ET

Starts with edge, restart is


not accepted

Elapsed Time, current time value


TwinCAT Training: Programmer

01.10.2012

97

Appendix: UP counter CTU


FBD /CFC
ST

CU

BOOL

Count up, count input

RESET BOOL

Counter reset

PV

UINT

Preset Value

BOOL

Counter value has reached PV

CV

WORD

Current counter value

Counts with edge on


CU, output is set when
the counter value has
reached the value of
PV.

TwinCAT Training: Programmer

01.10.2012

98

Appendix: DOWN counter CTD


FBD /CFC
ST

CD

BOOL

Count down, count input

LOAD sets counter,

LOAD

BOOL

Load value of PV to counter

PV

UINT

Preset Value

BOOL

Counter value has reached 0

Counts downwards with


edge on CU, output is set
when the counter value
has reached the value 0.

CV

UINT

Current counter value


TwinCAT Training: Programmer

01.10.2012

99

Appendix: UP/DOWN counter CTUD


FBD /CFC

LOAD
CD
CU
RESET
CV

ST

CV=PV

QD
QU

CU

BOOL

Count UP, count input +

CV

UINT

Current counter value

CD

BOOL

Count DOWN, count input -

Counts with edge on CD and CU,

RESET

BOOL

Reset

Negative count values are not possible

LOAD

BOOL

Load value of PV to counter

PV

UINT

Preset Value

QU

BOOL

Counter value has reached PV

QD

BOOL

Counter value has reached 0


TwinCAT Training: Programmer

01.10.2012

100

Appendix: String function CONCACT


FBD

ResultOnline

ST

STR1

STRING

First string

STR2

STRING

String that is appended


to the first string

TwinCAT Training: Programmer

01.10.2012

101

Appendix: String function FIND


FBD

ResultOnline

ST

STR1

STRING

String from which characters


are to be deleted

STR2

STRING

String to be found

TwinCAT Training: Programmer

01.10.2012

102

Detail : Overflows
Beware of overflows with numerical operations
0000h
INT 0

FFFFh
INT -1

8000h

7FFFh

INT -32768

INT 32767

PLC memory
INT value
TwinCAT Training: Programmer

01.10.2012

103

Data types: Example: EL3102


EL3102
2-channel analog input
terminals -10+10 V,
differential input, 16 bit

Input signal = Value


EL310x
10 V
5V
0V
-5 V
-10 V

Value
Decimal
32767
16383
0
-16383
-32768

Hexadecimal
0x7FFF
0x3FFF
0x0000
0xC001
0x8000

Status word from (EL3102-0000-0016) with older models only SW.0 - SW.7 1 byte
Bit

SW.15

SW.14

Name

TxPDO
Toggle

Bit
Name

SW.13

SW.12

SW.11

SW.10

SW.9

SW.8

TxPDO State Sync error

SW.7

SW.6

SW.5

SW.4

SW.3

SW.2

SW.1

SW.0

ERROR

Limit 2

Overrange

Underrange

Limit 1

With older
models

TwinCAT Training: Programmer

01.10.2012

104

Data types: Example: KL2531


KL2531

Velocity
Bit

15

14

Cont. VZ

13

12

11

10

Velocity value

Controlbyte (Ctrl)
Bit
Name

CB.7

CB.6

RegAccess Reset

CB.5

CB.4

CB.3

CB.2

CB.1

CB.0

AutoStop

AutoStart

Reduced
Current

Start

PLC-Stop

Enable

CW.13

CW.12
Reduced
Current
(drive)
CW.4
enLatch
FallEdge

CW.11

CW.10

CW.9

CW.8

Reduced
Current

SetPos

disMixed
Decay

GetEncoder
Position

CW.3
enLatch
RiseEdge

CW.2
enLatch
Input2

CW.1
enLatch
Input1

CW.0

Control word (ExtCtrl)


Bit
Name

Bit
Name

CW.15

CW.14

Set Position Clear


in ProcData Position

CW.7
CW.6
CW.5
GetPosition ToggleLatch GetLatch
Error
Data
Data

enLatchC

Position
Bit

15

14

13

12

11

10

Cont. Position value

Statusbyte (Status)
Bit
Name

SB.7

SB.6

RegAccess Error

SB.5

SB.4

SB.3

Warning

Idle

LoadAngle

SB.2

SB.1

SB.0
Ready

Status word (ExtStatus)


Bit
Name

SW.7

SW.6

SW.5

SW.4

SW.3

SW.2

SW.1

SW.0

Encoder
Disabled

LatchData
Toggled

LatchData
InByte2,3

LatchValid

Target
Reached

SetPos
Ready

Input E2

Input E1

Bit
Name

SW.15

SW.10
OpenLoad
Br A

SW.9
Under
Voltage

SW.8
Over
Temperature

SW.14
NoControl
Config Error
Power

SW.13
SW.12
SW.11
OverCurrent OverCurrent OpenLoad
Br B
Br A
Br B

Data types: Example: KL2531


KL2531

Summary
Description

Typ

Velocity 16-bit with sign

INT

Ctrl 8-bit bitstring

BYTE

ExtCtrl 16-bit bitstring

WORD

Position 16-bit, no sign

UINT

Status 8-bit bitstring

BYTE

ExtStatus 16-bit bitstring

WORD

TwinCAT Training: Programmer

01.10.2012

106

Data types: Example for reading the DT system time


The system time can be read with the
FB FB_LocalSystemTime
(TCUtilities.Lib)

TwinCAT Training: Programmer

01.10.2012

107

Data types: Example for DT


IEC standard operations can be applied to
D# and DT#

TwinCAT Training: Programmer

01.10.2012

108

Example: String function FIND

Pos 1

Pos
10

Pos
11

10

TwinCAT Training: Programmer

01.10.2012

109

Example: string functions LEN, REPLACE


Example: a string sVal is to be filled up to 5 characters. Output is right-aligned.
(Display CX or similar)

Pos 1

Pos 5
sVal

sResult

.1

-5

-5

12345

12345

TwinCAT Training: Programmer

01.10.2012

110

Example: String conversion with Union


A string is placed in the same address in the memory with an ARRAY OF BYTE
(Union)

A
B
C
D
E
$R
$N
TwinCAT Training: Programmer

01.10.2012

111

Detail - Replace %MB by UNION


Place target variable in same addresses in order to perform an ASCII - CHAR
transformation

Possible
Better, since user
does not have to
manage addresses

TwinCAT Training: Programmer

01.10.2012

112

System
Query the set PLC cycle time
Creation of a variable of the type PlcTaskSystemInfo;

Query the system variable _TaskInfo []

Task no.

Component .CycleTime returns the set cycle time. Scaling:


10,000 is 1 ms

TwinCAT Training: Programmer

01.10.2012

113

New Automation Technology

Connectivity

01.10.2012

ADS (General)
Definition

ADS = Automation Device Specification


- Modular ADS devices
e.g. PLC (each runtime system), NC, etc.
- Data exchange with message router

NEU

ADS General
Definition: ADS = Automation Device Specification
modular ADS devices
e.g. PLC (each runtime system), NC, etc.
message exchange by ADS via the message router

Beckhoff Training: TwinCAT ADS

01.10.2012

ADS: General device concept


ADS server
unambiguously
identifiable by:
AdsAmsServerPort

Router
unambiguously
identifiable by:
AdsAmsServerNetID

Beckhoff Training: TwinCAT ADS

01.10.2012

Identification of ADS devices


Each (TwinCAT) PC in the network is clearly identifiable via a TCP/IP address,
e.g. 172.1.2.16
The NetID is the identifier of the message router on a TwinCAT system (PC, CX, BX, BC),
e.g. 172.1.2.16.1.1
The port number is the identifier of a TwinCAT device.
(PLC runtime 1, 2, 3, 4, NC, IO, cam controller)

Beckhoff Training: TwinCAT ADS

01.10.2012

Identification of ADS devices


The port number is the identifier of a TwinCAT device.
(PLC runtime 1, 2, 3, 4, NC, IO, cam controller)
Port

PLC runtime 1 (TC3)

851

PLC runtime 2 (TC3)

852

PLC runtime 3 (TC3)

853

PLC runtime 1 (TC2)

801

PLC runtime 2 (TC2)

811

PLC runtime 3 (TC2)

821

PLC runtime 4 (TC2)

831

NC

500
(501)

IP Address
172.16.17.108

Message Router 172.16.17.108.1.1

IO server

TwinCAT device

PORT 851 PORT 852 PORT 500


NC
PLC 2
PLC 1
I

IO Mapper
Beckhoff Training: TwinCAT ADS

01.10.2012

TwinCAT message router


Example:
an ADS client sends an ADS message to an ADS server.
the TwinCAT message router (transport layer 4) carries out:
the receipt of the clients request
forwarding the message to another router if appropriate
provision of the messages to the ADS server

Beckhoff Training: TwinCAT ADS

01.10.2012

TwinCAT message router


Existing message router:
on each TwinCAT PC
on each CX1000, CX1020 Embedded PC
on each BX Bus Terminal Controller
on each BC XXXX Bus Terminal Controller
Possible communication paths:
Network (TCP/IP)
A PLC runtime system sends data to another PLC on another
TwinCAT PC, Embedded PC, etc. in the network.
Fieldbus (Lightbus / PROFIBUS)
A PLC runtime system sends data to another PLC
on a Bus Terminal Controller in the fieldbus.

Beckhoff Training: TwinCAT ADS

01.10.2012

Client-server relationship
1.) Confirmed services
2.) Unconfirmed services
ADS Client

ADS Server

Request
(Anforderung)

Indication
(Aufforderung)

Confirmation
(Besttigung)

Response
(Antwort)

Beckhoff Training: TwinCAT ADS

01.10.2012

Client-server between two PLC devices


Example: PLC (runtime 1) requests data from PLC (runtime 2)
ADS Client

PLC I

ADS server PLC II

Uses ADS FB

merely keeps the


data available

Request

Indication

(FB call)

Confirmation

Response

(Busy on the FB)

Beckhoff Training: TwinCAT ADS

01.10.2012

10

Access methods, identification of the target data


By address

For PLC variable located in

%M

Memory range

%I

Input range

%Q

Output range

By name

PLC variable

Global

Example: .Tempsetpoint

Access with .Variablename


.TON1.ET GVL1.Input1 (global instance of an FB)

Local: VAR , VAR_INPUT, VAR_OUTPUT with instance path

Example: MAIN.TON1.ET

Beckhoff Training: TwinCAT ADS

01.10.2012

11

Access methods, sequence


Synchronous:

Client sends a query to the server

Client waits until the result is available

Synchronous with the program line

Asynchronous:

Client sends a query to the server

Client continues to operate directly


Result of the server by callback

Notification:

Client registers itself at the server

Server serves the client autonomously by callback


(until the client logs off from the server again)

Beckhoff Training: TwinCAT ADS

01.10.2012

12

Description of access with index group and index offset


Services are described by the parameters INDXGRP and IDXOFFS
In the case of the PLC function blocks ADSWRITE, ADSREAD, etc. these are
VAR_INPUT parameters
The same input parameters are used for the ADSDLL method calls

Beckhoff Training: TwinCAT ADS

01.10.2012

13

Description of access with index group and index offset


Detail for access to PLC data (selection)
PLC SOURCE /
target variable

IDXGRP

IDXOFFS

%MB

0x4020

MB address

Example
IDXGRP 0x4020
IDXOFFS 100

%MX

%IB

0x4021

0xF020

MB address * 8 +
bit address

IDXGRP 0x4021

IB address

IDXGRP 0xF020

IDXOFFS 81

IDXOFFS 0
%IX

%QB

0xF021

0xF030

IB address * 8 +
bit address

IDXGRP 0xF021

QB address

IDXGRP 0xF030

IDXOFFS 41

ISXOFF 100
%QX

0XF031

QB address * 8 +
bit address

IDXGRP 0xF011
IDXOFFS 167

Beckhoff Training: TwinCAT ADS

01.10.2012

14

Description of access with index group and index offset


Access by name takes place via a variable handle
See PLC example and VS example for details

Action

IDXGRP

IDXOFFS

Example

Create
Handle

0xF003

READ/ WRITE COMMAND

Read / Write
by
handle

0xF005

Handle

Read or Write : Data

Delete
Handle

0xF006

Write Data: Handle

WRITE: VarName

Read: Handle

Beckhoff Training: TwinCAT ADS

01.10.2012

15

PLC examples

Examples with 2 PLC runtimes

Beckhoff Training: TwinCAT ADS

01.10.2012

16

Access by address
Example: PLC 1 sends to PLC2 2; access by address

PLC 1

PLC 2 PORT 811

Beckhoff Training: TwinCAT ADS

01.10.2012

17

Access by address
Variable access
PLC 1
PORT PLC2
NETID local

INDEXGROUP 0x4020 ->%MB


INDEXOFFSET 100 address %MB100
Beckhoff Training: TwinCAT ADS

01.10.2012

18

Access by address
Notes

Beckhoff Training: TwinCAT ADS

01.10.2012

19

Access by name / handle PLC-PLC


Example: PLC 1 sends to PLC2 access by name handle
Request handle on variable name
Write by handle
Delete handle

PLC 1

PLC 2 PORT 811

Beckhoff Training: TwinCAT ADS

01.10.2012

20

Access by name / handle PLC-PLC


Request handle IDXGRP 16#F003
PLC 1

NetiD local
PORT PLC2
Create Handle

Beckhoff Training: TwinCAT ADS

01.10.2012

21

Access by name / handle PLC-PLC


Variable access by handle 16#F005
PLC 1
PORT PLC2
NETID local

INDEXGROUP 0xF005 ->Access by handle


INDEXOFFSET Handle
Beckhoff Training: TwinCAT ADS

01.10.2012

22

Access by name / handle PLC-PLC


Delete handle 16#F006
PLC 1
PORT PLC2
NETID local

INDEXGROUP 0xF006 ->Delete handle


INDEXOFFSET Handle
Beckhoff Training: TwinCAT ADS

01.10.2012

23

Access by name / handle PLC-PLC


Notes

Beckhoff Training: TwinCAT ADS

01.10.2012

24

Example: access by IDXGRP IDXOFFS


Example: read and write PLC variable located at %MB and %MX
Access with IDXGRP and IDXOFFSET
(TCINFOSYS)
%MB in PLC:

INDEXGROUP

0x4020

INDEXOFFSET the %MB address of the PlcC variable


%MX in the PLC:

INDEXGROUP

0x4021

INDEXOFFSET byte address (%MB) * 8 + bit address

INDEXGROUP 0x4021
INDEXOFFSET 10*8 +1 = 81
INDEXGROUP 0x4020
INDEXOFFSET 12

Beckhoff Training: TwinCAT ADS

01.10.2012

25

Example: access by IDXGRP IDXOFFS

PLC

C# Application

VAR_GLOBAL

BIT0 AT%MX10.0 :BOOL;

BIT1 AT%MX10.1 :BOOL;

BIT2 AT%MX10.2 :BOOL;

BIT3 AT%MX10.3 :BOOL;

iVar0 AT%MB12 :INT;

diVar0 AT%MB14 :DINT;

END_VAR

Beckhoff Training: TwinCAT ADS

01.10.2012

26

Example: access by IDXGRP IDXOFFS


Integration of Add AdsDll
1

Beckhoff Training: TwinCAT ADS

01.10.2012

27

Example: access by IDXGRP IDXOFFS

TcAdsClient tcClient = new TcAdsClient();


Instance TcClient
TcClient.Connect(851);
Link TcClient to PLC1
(PORT 851)
%MX ACCES
lblM10_0.Text = TcClient.ReadAny
(0x4021,
10 * 8 + 0,
typeof(bool)).ToString();

IDXGRP for %MX ACCESS


IDXOFFS MB ADDRESS *8
+ BIT ADDRESS
Type of variable

Result

Beckhoff Training: TwinCAT ADS

01.10.2012

28

Example: access by IDXGRP IDXOFFS

%MB ACCES
lblMW12.Text = TcClient.ReadAny
(0x4020,
12,
typeof(short)).ToString();

IDXGRP for %MB ACCESS


IDXOFFS MB ADDRESS of
the PLC variable (AT%MB12)
Type of variable

Result

Beckhoff Training: TwinCAT ADS

01.10.2012

29

Example: access by IDXGRP IDXOFFS

TcClient.Dispose();
Enables the resources

Details: Create PLC program, create Visual C# 2008 according to the


course notes

Beckhoff Training: TwinCAT ADS

01.10.2012

30

Example: access by IDXGRP IDXOFFS


Notes

Beckhoff Training: TwinCAT ADS

01.10.2012

31

Example: access by name

Basic procedure:
Insert TcClient
Insert Namespace
Instance object variable for TcClient
Create handle variables
Request handle on PLC variable(s)
Write & read by handle
Delete handle(s)
Release resources (dispose)

Beckhoff Training: TwinCAT ADS

01.10.2012

32

Example: access by name


Write the variables to the PLC and read back

PLC

C# Application

VAR_GLOBAL

BIT0 :BOOL;

BIT1 :BOOL;

BIT2 :BOOL;

BIT3 :BOOL;

iVar0 :INT;

diVar0 :DINT;
END_VAR

Beckhoff Training: TwinCAT ADS

01.10.2012

33

Example: access by name


TcAdsClient tcClient = new TcAdsClient();
Instance TcClient
private int hBit0;
Handle on the PLC variable

hBit0 = TcClient.CreateVariableHandle(".BIT0");
Request handle
Name of the PLC variable. Do
not forget the dot with global
variables
(. BIT0)

Beckhoff Training: TwinCAT ADS

01.10.2012

34

Example: access by name


chkBit0.Checked = (bool)TcClient.ReadAny(hBit0, typeof(bool));
Return type is object

Type of variable
Handle on the variable

Result sets check box

TcClient.WriteAny(hiVar0, (short)tbariVar0.Value);
Value to the PLC
PLC INT is in C# Short
Handle
Beckhoff Training: TwinCAT ADS

01.10.2012

35

Example: access by name


TcClient.DeleteVariableHandle(hBit0);
Delete handle

TcClient.Dispose();

Release resources

Details: Open the templates (PLC/C#) distributed in the course and follow
the instructions
Beckhoff Training: TwinCAT ADS

01.10.2012

36

Example: access by name


Notes

Beckhoff Training: TwinCAT ADS

01.10.2012

37

Example: access by notification


Methods:
TcClient.AddDeviceNotificationEx(.);
AdsNotificationEx += new AdsNotificationExEventHandler()
TcClient.DeleteDeviceNotification();

General procedure:
Register notification on each variable (handle)
Create event handler
Evaluate received data in the Notification Event
Delete notifications
Release resources

Beckhoff Training: TwinCAT ADS

01.10.2012

38

Example: access by notification


Example

PLC

VAR_GLOBAL
AxisName:STRING(19);
Ready:
Error:
actVelocity:
actPosition: LREAL;
setVelocity:
setPosition: LREAL;
Lagdistance: LREAL;
END_VAR

C# Application

BOOL;
BOOL;
LREAL;
LREAL;

Beckhoff Training: TwinCAT ADS

01.10.2012

39

Example: access by notification

TcAdsClient tcClient = new TcAdsClient();

Instance TcClient
TcClient.AdsNotificationEx += new
AdsNotificationExEventHandler(TcClient_AdsNotificationEx);
Event
Name of the event function

Beckhoff Training: TwinCAT ADS

01.10.2012

40

Example: access by notification


void TcClient_AdsNotificationEx(object sender, AdsNotificationExEventArgs e)
{
if (e.NotificationHandle == hnReady )
{
e contains:
}
Datavalue
}
Notification handle
userobject
Is run through when the PLC
timestamp
has sent data
TcClient.DeleteDeviceNotification(hnReady );
delete notifications
ends reading
Details: Open the templates (PLC/C#) distributed in the course and follow
the instructions
Beckhoff Training: TwinCAT ADS

01.10.2012

41

Example: access by notification


TcClient.Connect(851)
Open port on PLC
hnReady = TcClient.AddDeviceNotificationEx
(
notification handle
".Ready",
AdsTransMode.OnChange,
100, 0,
lblReady,
typeof(bool)
);

PLC variable name

Update method
Filter time
User object or zero
Data type of the read
variable

For each variable


Beckhoff Training: TwinCAT ADS

01.10.2012

42

Example: access by notification


Notes

Beckhoff Training: TwinCAT ADS

01.10.2012

43

Writing / reading a 1-dimensional array


Methods:
TcClient.CreateVariableHandle(.);
TcClient.ReadAny()
TcClient.WriteAny();
TcClient.DeleteVariableHandle();
Procedure:
Connect to device PLC
Create variable handle
Read / write variable by handle
Delete variable handle

01.10.2012

44

Writing / reading a 1-dimensional array


Example:

PLC
VAR_GLOBAL
VisuPositions: ARRAY [0..19]
OF LREAL;

C# Application

double[] PlcArray;

END_VAR

01.10.2012

45

Writing / reading a 1-dimensional array


PlcArray = (double[])TcClient.ReadAny
(
handle
hPlcArray,
typeof(double[]),
Variable Type
new int[] { 20 }
Array length, number of
);
elements
C# target variable
TcClient.DeleteVariableHandle(hPlcArray);
Delete handle
Details: Open the templates (PLC/C#) distributed in the course and follow
the instructions
01.10.2012

46

Writing / reading a 1-dimensional array


Notes

01.10.2012

47

Reading a 1-dimensional array with notifications


Methods:
notificationHandle =TcClient.AddDeviceNotificationEx()
TcClient.DeleteDeviceNotification(notificationHandle);
TcClient.AdsNotificationEx += new AdsNotificationExEventHandler();
Procedure:
Connect to device
Add notification handler
Add device notification, device sens automaticly
Data im callback auswerten
Delete device notification

01.10.2012

48

Reading a 1-dimensional array with notifications


Reading a PLC array with notifications
PLC
VAR_GLOBAL
VisuPositions: ARRAY [0..19]
OF LREAL;

C# Application

double[] PlcArray;

END_VAR

01.10.2012

49

Reading a 1-dimensional array with notifications

TcAdsClient tcClient = new TcAdsClient();


Instance of the
TcAdsClient
TcClient.AdsNotificationEx += new
AdsNotificationExEventHandler(TcClient_AdsNotificationEx);
Event
Name of the event

01.10.2012

50

Reading a 1-dimensional array with notifications


TcClient.Connect(851)
Connect to plc
hnPlcArray=TcClient.AddDeviceNotificationEx(
PLC variable
Create notification handle ".VisuPositions",
AdsTransMode.OnChange,
Actualisation by
100,0,
Time for checking for
change of array
dataGridView1,
changes
User object
typeof(double[] ),
Data type
new int[] {20});
Arguments, number
of array elements

01.10.2012

51

Reading a 1-dimensional array with notifications


void TcClient_AdsNotificationEx(object sender, AdsNotificationExEventArgs e)
{
if (e.NotificationHandle == hnPlcArray)
{
e contains:
}
}
Datavalue
Notification handle
Is run through when data is
userobject
received
timestamp
TcClient.DeleteDeviceNotification(hnPlcArray);
Delete notifications
Details: Open the templates (PLC/C#) distributed in the course and follow
the instructions
01.10.2012

52

Reading a 1-dimensional array with notifications


Notes

01.10.2012

53

Read structure synchronously from the NC with IDXGRP


IDXOFFS
Method:
tcClientObject.Read(Indexgroup, Indexoffset, AdsStream);
AdsStream : Buffer for read data. Namespace: TwinCAT.Ads.Adstream
Class for evaluating the data stream:
BinaryReader. Namespace: System.IO
Or AdsBinaryReader Namespace TwinCAT.Ads simplified handling for strings
and PLC data and time types
Procedure:
Create Adsstream
Create BinaryReader or AdsBinaryReader
Read Methode aufrufen (Read, ReadAny)
Evaluate data stream and copy into target structure

01.10.2012

54

Read structure synchronously from the NC with IDXGRP


IDXOFFS
Example
NC
NC ADS Documentation :
IDXGRP 0x4000 + AxisID
IDXOFFSET 0
Details : TCMC.LIB

C# Application

ListView

01.10.2012

55

Read structure synchronously from the NC with IDXGRP


IDXOFFS
TcAdsClient tcClientNc = new TcAdsClient();
Instance
AdsStream AdsStrNcParaset= new AdsStream(512) ;
Ads stream for receive data
Length in bytes
tcClientNc.Read(Indexgroup + AxisId, Indexoffset, AdsStrNcParaset);
Read command
IDXGRP /IDXOFFS -> TcInfosys
Target stream

01.10.2012

56

Read structure synchronously from the NC with IDXGRP


IDXOFFS
Getting the index group and index offset from the Beckhoff information system
TcInfosystem

01.10.2012

57

Read structure synchronously from the NC with IDXGRP


IDXOFFS
Beckhoff Information System

Function to
read/write

Indexgroup +
Axid

Indexoffset

Acces Read
only

@ Result for AXIS1 : IDXGRP 0x4001 IDXOFFSET 0


01.10.2012

58

Read structure synchronously from the NC with IDXGRP


IDXOFFS
BinaryReader BinRead = new BinaryReader(AdsStrNcParaset,Encoding.ASCII );
Class for decoding the
receive stream
Constructor contains receive stream
Required if strings are contained

BinRead.ReadInt32()
Example for 32-bit INT

01.10.2012

59

Read structure synchronously from the NC with IDXGRP


IDXOFFS
Or: AdsBinaryReader:
AdsBinaryReader AdsBinRead = new AdsBinaryReader(AdsStrNcParaset);
Ads Class to evaluate stream
Constructor with AdsStrem
AdsBinRead.ReadInt32()
Example for 32-bit INT

Details: Open the templates (PLC/C#) distributed in the course and follow
the instructions
01.10.2012

60

Read structure synchronously from the NC with IDXGRP


IDXOFFS
Notes

01.10.2012

61

Reading structures with notifications


Methods:
TcClient.DeleteDeviceNotification(notificationHandle);
notificationHandle =TcClient.AddDeviceNotification()
TcClient.AdsNotificationEx += new AdsNotificationExEventHandler();
Procedure:
Connect to device
Add notification handler with datastream
Add device notification,
Evaluation of the data in callback
Delete device notification
Note:
StructLayout and MarshalAs can alternatively be used with the standard
framework. The method AddDeviceNotificationEx can be used there.

01.10.2012

62

Reading structures with notifications


Example
PLC
TYPE strAxisstate :
STRUCT

C# Application
private struct Axisstruct
{

AxisName:STRING(19);

public string AxisName;

Ready: BOOL;

public bool Ready;

Error: BOOL;
actVelocity: LREAL;

public bool Error;

actPosition: LREAL;

public double actVelocity;

setVelocity: LREAL;

public double actPosition;

setPosition: LREAL;

public double setVelocity;

Lagdistance:LREAL;

public double setPosition;

END_STRUCT

public double Lagdistance;

END_TYPE
}
VAR_GLOBAL
Axistate1 :strAxisstate ;

private Axisstruct Axistruct1;

END_VAR

01.10.2012

63

Reading structures with notifications


TcAdsClient TcClient = new TcAdsClient();
Instance for ads client
TcClient.AdsNotification += new AdsNotificationEventHandler
(TcClient_AdsNotification);
Add event

AdsStream StreamAxisstruct1 = new AdsStream(62);


Stream to receive data

01.10.2012

64

Reading structures with notifications


Check event
void TcClient_AdsNotification(object sender, AdsNotificationEventArgs e)
{ // check stream

AdsBinaryReader to
evaluate Stream

e.DataStream.Position = 0;
AdsBinaryReader AdsBinReader = new AdsBinaryReader(e.DataStream);
Axistruct1.AxisName = AdsBinReader.ReadPlcString(20);
Axistruct1.Ready = AdsBinReader.ReadBoolean();
Read Data from stream.
Position increments
automaticly
01.10.2012

65

Reading structures with notifications

TcClient.DeleteDeviceNotification(hnAxisstruct1);
Delete Notification only one handle per struct

TcClient.Dispose();
Release resources

Details: Open the templates (PLC/C#) distributed in the course and follow
the instructions
01.10.2012

66

Reading structures with notifications


Notes

01.10.2012

67

You might also like