0% found this document useful (0 votes)
340 views458 pages

De MC Smo PRG en 01 v4 3 1 CNRSZR

The document provides an overview of the SIMOTION programming course offered by Siemens AG, detailing its structure, content, and training objectives. It covers various aspects of motion control, including programming fundamentals, system architecture, and technology packages. The course is designed for professionals in the automation and drive technology sectors, focusing on integrating motion control with automation functions.

Uploaded by

wilfredvincent10
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)
340 views458 pages

De MC Smo PRG en 01 v4 3 1 CNRSZR

The document provides an overview of the SIMOTION programming course offered by Siemens AG, detailing its structure, content, and training objectives. It covers various aspects of motion control, including programming fundamentals, system architecture, and technology packages. The course is designed for professionals in the automation and drive technology sectors, focusing on integrating motion control with automation functions.

Uploaded by

wilfredvincent10
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/ 458

Kursunterlagen für ERDINC KELOGLU, erdinc.keloglu@siemens.

com

Siemens AG

DEUTSCHLAND
Industry Sector

90475 NÜRNBERG
Gleiwitzer Str. 555
er
di
nc
. ke
lo
gl
u
@
Siemens Certified Service Technician Level 1
(inkl. SPS-Techniker entspr. VDMA/ZVEI)

ca
(MC-SMO-PRG)
ne
r.s
SIMOTION Programming
SITRAIN:

ez
er
@
gm
ai
Training for Industry

l.c
siemens.com/sitrain

om
1 SIMOTION - System Overview

Fundamentals of programming
2
with Structured Text

Functions and function blocks


3
in SIMOTION

om
SITRAIN
Training for Industry 4 Programming motions of axes

l.c
5 Libraries in SIMOTION
SIMOTION
Programming Course

ai
6 The execution system in SIMOTION
MC-SMO-PRG course
gm 7 Gearing in SIMOTION
@
8 Creating cams
er

9 Camming in SIMOTION
ez

10 Exercises
r.s

Name:

11 Solutions
Course from: to:
ne

Course leader:
Appendix 1: Communication
12
Course location: with SIMOTION
ca

This document was created for training purposes. SIEMENS Appendix 2: Supplementary technology
does not guarantee the content. 13
The reproduction, transmission, or use of this document or its objects/Fixed gear
content is not permitted without express written authority.
Offenders will be liable for damages.

Copyright © Siemens AG 2013. All rights, including rights


created by patent grant or registration of a utility model or 14 Appendix 3: OPC for SIMOTION
design, are reserved.

SITRAIN course material on the Internet:www.siemens.de/sitrain

Course folder version: V4.3


SIMOTION – An Overview

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.1
@
Contents Page

Mechatronics and Motion Control – Transformation in Machine Construction .................................. 2


Tasks of a Motion Control System .................................................................................................... 3
er

Motion Control – Possibilities in the Automation Area ...................................................................... 4


What is SIMOTION? ........................................................................................................................ 5
SIMOTION Components .................................................................................................................. 6
System Architecture of the Runtime System ..................................................................................... 7
ez

Technology Packages in SIMOTION ................................................................................................ 8


SIMOTION SCOUT Engineering Tools ............................................................................................. 9
Programming Languages in SIMOTION ........................................................................................... 10
MCC – Programming Motion Sequences .......................................................................................... 11
r.s

LAD/FBD – Programming Languages for PLC Tasks ....................................................................... 12


ST – High-Level Language for Programming Complex Algorithms ................................................... 13
DCC – Graphic Tool to Generate Charts .......................................................................................... 14
Sequential and cyclic programming .................................................................................................. 15
User tasks in SIMOTION .................................................................................................................. 16
ne

The Various Hardware Platforms (1) ................................................................................................ 17


The Various Hardware Platforms (2) ................................................................................................ 18
Integration in TIA .............................................................................................................................. 19
SIMOTION Documentation ............................................................................................................... 20
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 1 SIMOTION – An Overview
Mechatronics and Motion Control – Transformation in Machine
Construction
Traditional machine construction Mechatronic solution
„ Central drive technology „ Distributed drive technology
„ All motion is derived from „ Motion is coordinated by higher-
mechanical transmission level control
components „ Software simulation of

om
„ Machine functions are mechanical components
"mechanically" defined „ Flexible machine functions

Electronics
Coupling Mechanical system

l.c
Gearing

Cam
controller

ai
Line shafts
Cam

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.2
Software

SITRAIN Training for


Automation and drive technology
@
Previous In previous machines, mechanical components such as cams gearboxes,
machine Concepts couplings, line shafts, etc., were mainly used.
This meant it was often costly and time-consuming to make mechanical
changes. It was difficult to create flexible solutions. Now the obstacles imposed
er

by mechanical components are being lifted by the use of intelligent automation


and drive technology.

Intelligent Intelligent software solutions are increasingly replacing mechanical components


ez

concepts with central drive technology. Machine functions are implemented by means of
distributed drive technology. Individual movements are coordinated and
synchronized by the higher-level control.
Functions which were previous sly implemented with hardware are now
integrated into the software. Changing machine requirements such as format
r.s

changes can be responded to almost at @the touch of a button.

Today "intelligent components" play a key role in modern machine and


Advent of production plant construction. These "mechatronic components" comprise
mechatronics mechanical components, sensors, actuators, electronic components and
ne

software.

Today, meochatronic solutions are indispensable in many sectors. The economic


success is not in optimizing the sub systems, but in a complete and holistic
system approach. With mechatronics a machine or production plant is regarded
not only in mechanical terms but as a complete system that integrates
ca

mechanical components, electronics, control engineering and software


technology.

SIMATIC and As technology leader, Siemens offers manufacturers of machines and production
SIMOTION plants a system platform providing automation without system interruptions. The
associated wide-ranging services portfolio extends from application consultancy
by competent specialists – with well-founded sector experience – up to
commissioning and maintenance by our service specialists.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 2 SIMOTION – An Overview
Tasks of a Motion Control System

Tasks of a motion control system


HMI „ Controlling axis motion
- Positioning
- Coupling axes (synchronous operations, ...)
MC control „ Cyclically calculating setpoint positions
(interpolation)
„ Performing closed-loop position control, output

om
of the speed setpoint via PROFIBUS or
PROFINET
Other tasks
„ Processing peripheral (I/O) signals
„ Closed loop control tasks (e.g. closed loop
temperature control, etc.)

l.c
„ Data processing

Tasks of a drive
„ Converting the speed setpoint into the actual
I/O speed

ai
„ Closed-loop speed and current control
„ of a drive comprises
- Rectifier/inverter
- Motor

SIMOTION
Siemens AG 2013. All rights reserved.
Drives
gm
Date:
File:
„
- Encoder system
can also be operated independent of an MC
control system

10.01.2013
MC-SMO-PRG_01.3
SITRAIN Training for
Automation and drive technology
@
MC control For SIEMENS control systems, the total motion functionality is split up into the
actual Motion Control system and the drive system.
The MC control has the task of processing the specified (motion) program.
Within the motion program, both positioning commands can be issued to
er

individual axes as well as commands to synchronize and coordinate several


axes (synchronous operation commands).
The setpoint positions (interpolation) resulting from the motion commands are
fed into the closed-position control and there, compared with the actual positions
ez

supplied from the drive system (closed-loop position control). From the resulting
following error, by multiplying with the Kv factor, a new speed setpoint (axis
velocity) is calculated and transferred to the drive.
The speed setpoint can be transferred to the drive system either digitally via
r.s

PROFIBUS or PROFINET – or as analog signal (+/- 10 V).


In addition to the actual motion control functionality, typical PLC functionality can
also be integrated into the MC system. Just the same as for a SIMATIC PLC,
digital or analog peripheral (I/O) signals can be read-in, processed and the
results output again to the peripherals.
ne

Drive system The task of the drive system is to convert the received speed information into an
actual motor speed. A speed and current controller are integrated in the drive
system for this very purpose.
The motor moves the axis which is traversed to the required target position with
ca

the setpoint speed specified by the motion control system.


The drive system consists of an converter, motor and encoder. When coupled to
a SIEMENS motion control system, the drive system operates exclusively in
what is known as the speed mode. Motion control functionality (basic positioner,
etc.) possibly integrated in the drive system, in this particular case, cannot be
used.
Drive systems can also be operated without a higher-level motion control
system. The speed can be entered, for instance via an analog potentiometer.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 3 SIMOTION – An Overview
Motion Control – Possibilities in the Automation Area

SIMATIC SIMOTION SINUMERIK

om
SIMATIC - automates SIMOTION - the motion SINUMERIK – brings
everything for you and that control system machine tools up to speed.
worldwide.
Specifically for machine Specifically for turning,
Powerful control that can be solutions where there are milling, drilling –
universally used – high demands on the numerical control at its

l.c
functionality can be T-CPU motion control best.
extended by motion control

Our portfolio today:

ai
ƒ SINAMICS
ƒ MICROMASTER
ƒ SIMODRIVE

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Drive technology

Date:
File:
10.01.2013
MC-SMO-PRG_01.4
ƒ MASTERDRIVES

SITRAIN Training for


Automation and drive technology
@
Overview The demands placed on a control system largely depend on the application.
Therefore, SIEMENS offers different systems, which have been designed for
different application fields:
er

SIMATIC SIMATIC is the tried and proven basis automation system for solutions in all
sectors of industrial automation.
It consists of standard hardware and software components and offers a wide
range of possibilities for customized expansions. For SIMATIC S7, motion
ez

control functionality can be integrated using function modules, for example.


FM modules have a special functionality, which are generally controlled from the
SIMATIC user program via function block calls. Complex motion control
solutions can be implemented within a SIMATIC system in this fashion.
r.s

SINUMERIK SINUMERIK control systems are specially designed for machine tools, handling
systems and special-purpose machines.
SINUMERIK offers the optimum solution for every task in the machine tool
sector, using CNC control and drives.
ne

SIMOTION In addition to SIMATIC and SINUMERIK, there is also SIMOTION, the motion
control system for applications with complex motion control which integrates
motion control and simple control functionality in one unit.
ca

SIMOTION combines the complex handling of motion functions in a scalable


motion control system. It comprises the SCOUT engineering system, motion
control technology packages and a common runtime system for various
SIMOTION hardware platforms.

Technology CPU The technology CPUs 315/317T -2DP and 317TF -2DP (fail-safe control) are
located between the SIMATIC and SIMOTION pillars.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 4 SIMOTION – An Overview
What is SIMOTION?

Motion control
„ Positioning
„ Synchronous
operation

+ SIMOTION

om
The fusion of:
Technology functions „ Motion control
„ Temperature controller „ Technology functions
„ Pressure „ Logic

l.c
controller
Integrated
+ system solutions for
machine construction

ai
Logic functionality
„ AND, OR
„ Multipliers

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.5
SITRAIN Training for
Automation and drive technology
@
SIMOTION SIMOTION offers an optimized system platform for automation and drive
solutions with the focus on motion control applications and technological tasks.
This is achieved through the new universal motion control system.
SIMOTION is an integrated motion control system which has been conceived
er

primarily for the automation of production machines. Uniformity and integration


is achieved in engineering, programming, communication, data management,
the human-machine interface (HMI) - thus encompassing all system
components, and of course all the different hardware platforms.
ez

Fusion of SIMOTION's innovative approach consists of removing the traditional division


PLC and motion between pure automation functions (typically PLCs) and motion functions
control (motion control). This merging of functionality is implemented in both the
hardware and software.
r.s

With respect to the hardware, this new approach means that the controller must
be capable of processing motion functions. On the other hand, a drive system
must be able to perform automation tasks.
On the software side, the fusion of automation functions and motion functions
ne

makes for simpler engineering. This starts with the configuration and continues
through parameter assignment and programming.
The integration with SIMATIC brings additional advantages as both systems are
often operated in one installation. The two systems can be configured and
programmed on a standard engineering interface.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 5 SIMOTION – An Overview
SIMOTION Components

One engineering system


ƒ for configuring, programming
and setting parameters
ƒ Graphic or textual

om
programming

Different

l.c
Runtime system hardware platforms:
ƒ Synchronous operation ƒ Controller in the S7 design
ƒ Positioning ƒ Industrial PC
ƒ ... ƒ Drive

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.6
SITRAIN Training for
Automation and drive technology
@
Overview SIMOTION offers an optimized system platform for automation solutions for
machines where motion control applications and technology tasks are in the
forefront.
The motion control system consists of the engineering system SCOUT, the
er

motion control technology packages and a common runtime system for the
various SIMOTION platforms.

SCOUT engineering The SCOUT engineering system is used fomr configuring, programming
ez

system and setting parameters; it is the same system for all hardware platforms.

Configuring, programming and setting parameters is either performed by


means of graphics or text.
r.s

Technology Technology packages contain the software functions that are required for
packages automation in a wide range of different sectors. They expand the basic
functionality of the SIMOTION devices to suit individual requirements.
Technology packages can be added according to the machine requirements
(e.g. synchronous operation, cam).
ne

SIMOTION offers flexible solutions - for all requirements - by running on a


Hardware range of different platforms. With SIMOTION you can freely select between
platforms three different platforms:
ca

• SIMOTION C - Controller-based
• SIMOTION P - PC-based
• SIMOTION D - Drive-based

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 6 SIMOTION – An Overview
System Architecture of the Runtime System

SIMOTION Tailored
SIMOTION
user Function SIMOTION
program libraries
application

om
Motion
control Additional DCC User program
technology technology blocks

l.c
Basis function- packages
ality acc. to packages
IEC 61131-3 + Function libraries

SIMOTION kernel

ai
(operating system, I/O handling, communication…) + Technology packages

+ Basis functionality

SIMOTION
Drives

Siemens AG 2013. All rights reserved.


I/Os
(sensors, actuators)
gm
Additional automation

Date:
File:
components

10.01.2013
MC-SMO-PRG_01.7
SITRAIN Training for
Automation and drive technology
@
System architecture The most outstanding feature of the new automation approach is its system
architecture. This forms the basis for ongoing system development. The system
architecture of SIMOTION especially supports concepts – such as
decentralization, different target platforms and distributed intelligence.
er

The software is modular and can be flexibly adapted to the widest range of
requirements.

Basis functionality The basis functionality of the device (SIMOTION kernel) includes functions for
ez

open-loop and closed-loop control as well as logic and arithmetic. Program


execution can be cyclical, time- or interrupt-triggered.
As a result, the SIMOTION kernel contains the functions needed for virtually all
applications and corresponds in essence to a PLC with the IEC 1131-3
r.s

command set plus system functions for controlling various components, such as
inputs and outputs.

Technology The SIMOTION kernel can be expanded by loading technology packages. Using
packages additional language commands, the technology packages can be accessed in
ne

the same way as the SIMOTION kernel from the user program.

Function The libraries contain standard functions for frequently performed tasks.
libraries In addition to the standard functions supplied, users can also create their own
blocks and store them in a library.
ca

From Version 4.0, the following libraries have also been integrated as function
blocks in the system (TP "Cam"), and can now be directly inserted into the user
program from the command library:
• Standard functions, for instance PID controllers, driver blocks for special
I/O modules
• Blocks in conformance with PLCopen to control axes (single and
multi-axis blocks)

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 7 SIMOTION – An Overview
Technology Packages in SIMOTION
Expanded Temperature
Speed-con- Positioning Synchronous Path inter- technology control
trolled axis axis axis polation

om
„ Adder „ Temperature
„ Actual value „ Position- „ Gearing „ 2D/3D linear object control
processing controlled interpolation
„ Camming „ Controller „ Controller
„ Speed traversing „ Circular
„ Synchroni- object optimization
setpoint „ Referen- interpolation
zation/de- „ Formula

l.c
„ Output cam cing synchroni- „ Polynomial object
functions „ Leading zation interpolation
„ Fixed gear
„ Measuring axis „ Various
function „ Sensor
input kinematics

ai
License TP "Cam" License
not required required
License License
TP "Path" not required required

SIMOTION
Siemens AG 2013. All rights reserved.
TP "Cam_ext" (extended)
gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.8
License
not required "TControl"

SITRAIN Training for


Automation and drive technology
@
Technology Technology packages can be loaded in the runtime system to expand the basic
packages functionality of the SIMOTION kernel. In addition to the object types, technology
packages provide a wide range of powerful motion control commands, which are
required to flexibly solve applications.
er

TP "CAM" The "Cam" technology package provides all object types and system commands
to control speed, positioning and synchronous axes.
In addition to the functionality for the individual axes, TP "Cam" contains the
ez

"Measuring input", "Output cam" and "Cam track" functions (from V3.2 and
higher) as well as the function blocks in conformance with PLCOpen.

TP "PATH" The "PATH" technology package provides path functionality. The following are
supported: 2D/3D linear, circular and polynomial interpolation. In addition,
r.s

various kinematics such as 2D/3D gantry, roll, Delta-2D, Delta-3D-Picker, as


well as SCARA and articulated arm kinematics

TP "CAM_EXT" Supplementary technology functions are available with Version 3.2 and higher.
• Adder: With adder objects up to four input vectors can be added to one
ne

output vector.
• Formula: With formula objects, you can apply mathematical operations to
scalar (LREAL, DINT) and motion vectors.
• Controller: Using the controller object, according to a PID algorithm, scaler
ca

variables can be processed and logically combined.


• Sensor: The sensor technology object can be used to detect and process
scalar measured values, i.e. correspondingly monitored and smoothed.
• Fixed gear: For "fixed" synchronous relationships between axes with an
adjustable gear factor, however, without specific synchronizing/
desynchronizing strategy.

TP "TControl" The basis of the temperature controller is a DPID controller which has special
functions (threshold monitoring, adaptation of controller parameters, etc.) for
easy adaptation to applications (plastics machines).
SITRAIN Training for MC-SMO-PRG
Automation and Drive Technology Page 8 SIMOTION – An Overview
SIMOTION SCOUT Engineering Tools

System ST Structured Text


configuration SIMOTION SCOUT
MCC
Project navigator Motion Control Chart

om
LAD/FBD

Axis configuration

DCC

l.c
CamEdit

Drive Test and diagnostics


CamTool

ai
commissioning

SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm 10.01.2013
MC-SMO-PRG_01.9
SITRAIN Training for
Automation and drive technology
@
Engineering system The SCOUT Project navigator is the common framework for all tools of the.
SCOUT engineering system. This workbench is also the navigation center for the
individual engineering steps. It is used to create and manage SIMOTION
projects and provides a uniform and integrated view of all data and programs.
er

The essential new feature is the graphic programming of the motion sequence
using Motion Control Chart (MCC). From SCOUT V4.1, there is also the optional
DCC programming language (Drive Control Chart) to create continuous, closed-
loop control related circuit diagrams to control drives.
ez

The technological tree structure of the project includes


• all devices (open-loop control, drives etc.),
• all technological objects (axes, output cams, cams etc.) and
• user programs in hierarchic views that can be filtered.
r.s

The navigation in the tree structure opens the parameter assignment or


programming tool assigned to the selected object.
The SIMOTION SCOUT engineering system is a powerful tool that acts as the
PC development environment to optimally support the required engineering
ne

steps in a user-friendly way.


The SCOUT engineering tool is integrated as optional package to STEP 7 in the
SIMATIC environment. When developing SCOUT, special attention was given to
optimum usability and a comprehensive, function-oriented view of the
automation task.
ca

Note The SCOUT engineering tool is available in two versions:


• as a standalone version, without any connection to STEP 7
• as optional package to STEP 7

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 9 SIMOTION – An Overview
Programming Languages in SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.10
SITRAIN Training for
Automation and drive technology
@
Overview SIEMENS offers a range of task-oriented programming languages for
SIMOTION that allow the user to focus on the actual task at hand. SIMOTION's
modular design makes it possible to create modular blocks in different
languages according to the individual task requirements.
er

MCC MCC is a graphic language for creating operational sequences. In particular, this
language offers entry-level users support for quick and transparent creation of
sequential program sequences in MotionTasks.
ez

Any additional ST code can be integrated in the MMC program via the "ST
Zoom" command.

LAD/FBD These programming languages are unparalleled for programming binary signal
r.s

gating. In addition to the wide range of options in the area of binary signal gating
(edge evaluation, flip-flops, etc.), it integrates many other function such as IEC-
compliant counter and timer blocks.
Almost all system functions can be directly called and tested in a network.
ne

ST Structured Text is a text-based, high-level language similar to PASCAL.


ST contains all typical elements of a high-level language such as operators,
expressions, control statements, etc. ST supports in particular programming of
mathematical algorithms and data administration tasks.
Due to the many control structures it offers, ST is also suitable for programming
ca

process sequences.

DCC The Drive Control Chart (DCC) option is a modular, scalable programming
language based on the STEP 7 package CFC (Continuous Function Chart), to
develop continuous open-loop or closed-loop control solutions for controlling
drives.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 10 SIMOTION – An Overview
MCC – Programming Motion Sequences
Properties of motion control charts
• Graphic language to describe motion
sequences in the form of a sequence chain
• Complex sequences in automation technolo-
gy are broken down into individual steps

om
• MCC contains graphic commands for:
• Axis movements
• Processing I/O signals
• Control structures for branches and
repeat operations

l.c
• Comparable with S7 Graph from STEP 7
Advantages of MCC
• Motion sequences can be simply and

ai
transparently generated
• Even entry-level programmers can attain
results quickly

when it comes to testing and therefore fast commissioning

SIMOTION
Siemens AG 2013. All rights reserved.
gm
• In addition to the fast generation, MCC also provides support

Date:
File:
10.01.2013
MC-SMO-PRG_01.11
SITRAIN Training for
Automation and drive technology
@
Properties MCC is a new graphic programming language, designed to significantly simplify
of MCC the automation of production machines.
Many production machines are very complex. They require a control system
(SIMOTION) that is capable of handling motion control and technologies with a
er

wide variety of motion functions, as well as PLC functions, arithmetic functions,


and data management tasks.
MCC is the neutral description tool used to represent a sequence diagram. This
sequence diagram is referred to as MCC chart in this document. It provides you
ez

with all of the descriptive symbols you will need to define your automation task
quickly and efficiently.
In addition, MCC offers many ways to structure large automation tasks.
Using MCC, programs, function blocks and functions can be generated in
r.s

compliance with IEC61131-3.

Advantages of MCC As a graphic programming language, MCC helps you to formulate process and
motion sequences easily by creating a sequence of graphic MCC commands.
The characteristics of every MCC command can be parameterized individually.
ne

Control structures such as IF commands make for easy implementation of


alternative branches.
Furthermore, each MCC command has its own graphic design, making the
functionality of each action within an MCC chart immediately evident.
ca

Consequently, the system greatly facilitates the programming of automation


tasks and additionally enhances readability.
Further, online functions enable you to locate errors quickly or simply help you
to keep track of the current states.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 11 SIMOTION – An Overview
LAD/FBD – Programming Languages for PLC Tasks
Popular language from the PLC area
• LAD uses program elements from circuit
diagrams
• FBD uses elements from Boolean algebra
• Compatible to IEC 61131-3 LAD/FBD

om
• Motion control functionality can be best integrated
using the function block from the PLCOpen
library
• Identical to SIMATIC LAD/FBD

l.c
Advantages:
• Binary logic operations can be simply formulated,
for instance, interlocking conditions

ai
• Easy to understand and program
• Simple testing and commissioning of programs

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.12
SITRAIN Training for
Automation and drive technology
@
LAD LAD stands for ladder diagram. LAD is a graphic programming language. The
syntax for the instructions is similar to a circuit diagram. LAD enables simple
tracking of the signal flow between conductor rails via inputs, outputs and
operations.
er

LAD statements consist of elements and boxes, which are graphically


connected to networks (compatible to IEC 61131-3).
The LAD programming language provides all elements that are required to
generate PLC tasks. LAD features an extensive command set. This includes the
ez

various basic operations with a comprehensive range of operands and how to


address them. The concept of functions and function blocks allows complex
tasks to be clearly structured.
r.s

FBD FBD stands for function block diagram. FBD is a graphics-based programming
language that uses the same type of boxes used in boolean algebra to represent
logic (compatible to IEC 61131-3). In addition, complex functions (e.g. mathe-
matical functions) can be represented directly in conjunction with the logic
boxes.
ne

Just like LAD, FBD provides all of the elements that are required for creating
PLC tasks.

Advantages and The programming languages are admirably suited to implement open-loop
limits control tasks using binary operands; for instance, interlocking conditions.
ca

Programming closed-loop control tasks with analog variables, for instance the
speed of a drive or the temperature of a heating boiler etc. is a tedious
procedure in LAD/FBD networks.
DCC is an expansion to process analog variables. Using the DCC editor, analog
variables can be processed and interconnected in a similar way to binary
variables in LAD/FBD.
However, having said this, LAD/FBD is especially useful as many service
personnel feel very comfortable with LAD/FBD programming.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 12 SIMOTION – An Overview
ST – High-Level Language for Programming Complex Algorithms
High-level language similar to Pascal
for formulating complex tasks
• Compatible with IEC 61131-3 ST
(ST = Structured Text)
• Contains all the typical elements of a

om
high-level language, such as operators,
expressions, control instructions, etc.
• Motion control functionality is integrated
by means of system functions and
function blocks

l.c
• Identical to SIMATIC S7 SCL
Advantages:
• Formulation and creation of blocks with

ai
complex algorithms:
• Closed-loop control tasks
• Data processing tasks

SIMOTION


Process optimization
Mathematical/statistical evaluation

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.13
SITRAIN Training for
Automation and drive technology
@
Properties ST is a high-level programming language oriented to PASCAL. The language
of ST is based on the IEC 61131-3 standard, which standardizes programming
languages for programmable logic controls (PLCs).
In addition to open-loop and closed-loop control tasks, modern automation
er

systems must be capable of handling an increasing number of data processing


tasks and complex mathematical algorithms (process optimization). ST was
developed specifically to address tasks such as these.
In addition to the standardized, IEC 61131-3-compliant programming language,
ez

SIMOTION ST also includes commands for SIMOTION devices, motion control


and technology.
Technology objects make an interface available to the user program via which,
for example, axes can be positioned or output cams parameterized. These
r.s

technology commands are the commands provided by technology objects which


can be called easily from an ST user program.

Advantages of ST Programming controls using a high-level language such as ST opens up a wide


range of options, especially for the following tasks, such as e.g.:
ne

• simple generation of complex open-loop and closed-loop control algorithms,


such as e.g. algorithms for process optimization
• transparent handling of data management tasks, for example the acquisition
and processing of process data (statistical pre-compression of data etc.)
ca

• simple communication using standard protocols(TCP/IP, UDP) to


other systems, for instance master computer coupling
When compared to other high-level languages, for instance C, ST is easy to
learn and understand. Especially entry-level personnel, who have no experience
with the concepts and techniques of high-level languages, can achieve usable
results with ST.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 13 SIMOTION – An Overview
DCC – Graphic Tool to Generate Charts
DCC (Drive Control Chart)
Graphic tool to generate
motion control programs
• Blocks are placed on a sheet and
interconnected

om
• Interconnections are possible:
- to I/Os of other blocks
- between I/Os of the I/O list
- also to I/Os of blocks in
other charts
• Sources and targets are managed in

l.c
the sheet bar
• Can be used in SIMOTION and
SINAMICS

ai
Advantages
• Well-established programming tool for
motion control tasks!
• Fast generation, testing and
commissioning
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.14
SITRAIN Training for
Automation and drive technology
@
Overview, DCC DCC (Drive Control Chart) offers a modular, scalable technology option, which
has chiefly been developed for drive-related, continuous open-loop and closed-
loop control tasks. The DCC technology option for SIMOTION controllers and
SINAMICS drives can be configured graphically using the Drive Control Chart
er

editor (DCC editor), which is based on SIMATIC S7 CFC.

As a consequence, extensive closed-loop control related structures can be


programmed in SIMOTION. These can then be combined with other program
sections to form an overall program. The time slices: T1 .. T5 of the blocks can
ez

be freely selected and combined in SIMOTION. The run environment in


SIMOTION ensures consistent data transfer between blocks with different
sampling times

In SINAMICS, using the DCC-Editor, drive-related tasks can be directly


r.s

implemented in the converter. SINAMICS BICO technology is used to access


drive parameters.
Procedure
When a new chart is created, the block types are first taken from the device-
specific block library and inserted in the DCC editor's block manager.
ne

Using the DCC Editor, charts are subsequently created, in which blocks are
inserted from the library, parameterized and interconnected. The charts are then
compiled and an intermediate code generated; this is then loaded into the
SIMOTION and/or the drive unit using SCOUT /STARTER.
ca

Advantage kDCC can be used from very simple up to extremely complex applications.
Communication between the blocks can be configured in a user-friendly fashion
using a straightforward interconnection system. It is not necessary to manually
handle and manage the machine resources.
Comprehensive test tools with simple display, diagnostics and trace functions
ensure fast testing and in turn fast commissioning of the user program.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 14 SIMOTION – An Overview
Sequential and cyclic programming

Sequential processing: Cyclic processing:

om
l.c
ai
• Can only be used in "MotionTasks" • Only suitable in cyclic tasks:
and event-controlled tasks • Alternative to creation in MCC

SIMOTION
• Program creation in MCC

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
- Programming in LAD/FBD
- With blocks from "PLCopen"

MC-SMO-PRG_01.15
SITRAIN Training for
Automation and drive technology
@
Sequential With sequential programming, the entire program is separated into individual
programming steps with associated function calls. When one command can switch to the next
is defined in the dialogs for the individual commands.
If the next command is only enabled when the job has been completed, then this
er

is referred to as sequential programming or synchronous function calls. Program


execution - i.e. execution of the function calls - is synchronous with the process.
In this case, the commands in the MCC chart mirror the individual phases of the
process sequence.
ez

This type of program generation corresponds to programming sequencers in


PLCs. This type of programming offers significant benefits over conventional
cyclic programming, in particular for process sequences where the entire
process can be divided into individual phases (sub-movements).
r.s

Usually, a "synchronous" program is easier (i.e. primarily quicker) to create and


easier to debug. The process sequence can be converted into the
corresponding controller program directly.
In SIMOTION, programming sequential program flows is linked to tasks that are
not executed cyclically. SIMOTION supports this programming concept by
ne

providing what are known as MotionTasks.

Cyclic Cyclic programming corresponds to conventional program generation in PLCs.


programming In this case, calls to technology objects are executed asynchronously. The call
itself is usually implemented in the form of a function block.
ca

After the function call is issued, the program advances to the next command
without waiting for the job to be terminated. During the subsequent cycles of the
program section, the user program can track the job processing status via the
associated output parameters of the function block, so that the next job can be
started upon successful termination of the current one.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 15 SIMOTION – An Overview
User tasks in SIMOTION

Stop Run Startup task

RUN
BackgroundTask BackgroundTask

om
MotionTasks MotionTask1 MotionTask2 MotionTask32

SynchronousTasks Servo-syncTask IPO-syncTask IPO-syncTask2

T4 DccAux Task T5 DccAux Task

l.c
TimerInterruptTasks TimerIntTask1 TimerIntTask2 TimerIntTask5

ai
InterruptTasks UserIntTask1 UserIntTask2 SystemIntTasks

SIMOTION
Siemens AG 2013. All rights reserved.
Run Stop

Date:
File:
gm ShutdownTask

10.01.2013
MC-SMO-PRG_01.16
SITRAIN Training for
Automation and drive technology
@
StartupTask/ The StartupTask is executed once at the transition from STOP or STOP U
ShutdownTask operating mode to RUN operating mode. It serves the purpose of initialization.
The ShutdownTask is called at the transition from RUN to STOP or STOP U.
er

BackgroundTask This task is called cyclically. When the programs in this task have been
processed, the task is automatically restarted. This task implements the
conventional interlock functions of a PLC.
ez

MotionTasks MotionTasks are tasks that are started by the user program and are processed
only once. These tasks are assigned to programs; execution is then sequential.
One such program is, for example, motion control of an axis. The axis moves to
a target position and waits for an Enable signal before traversing to the next
target position.
r.s

. . . Synchronous- The tasks are started synchronously with the specified system cycle clock
tasks (position control cycle clock, IPO cycle clock, IPO_2 cycle clock) before the
technology package. In these tasks, you can implement time-critical functions
that correlate closely with the timing of the motion control of the axes.
ne

The T4 DCCAuxTask and the T5 DCCAuxTask were integrated in V4.1.1 of


DCC so that time slices T4 and T5 could be implemented. Time slices T1
through T3 are implemented with the position control task, IPO task, and
IPOSynchronousTask2.
ca

TimerInterruptTasks The TimerInterrupt Tasks are started and processed at fixed intervals and can
be used to implement control or monitoring tasks that need a fixed time
reference.

UserInterruptTasks These are event-triggered and processed only once. They can be used to
respond to user-defined events.

FaultTasks These are triggered by system events such as faults and alarms and
(Systeminter.Tasks) processed only once. Different tasks are available for the various error events.
SITRAIN Training for MC-SMO-PRG
Automation and Drive Technology Page 16 SIMOTION – An Overview
The Various Hardware Platforms (1)
SIMOTION C230-2 / C240 / C240 PN
• SIMATIC S7-300 mechanical design
• Drive link analog (4 channels onboard, not C240 PN)
or via PROFIBUS-DP or 3 x PROFINET
(only C240 PN)
• Interfaces 2 x PROFIBUS-DP,

om
1 x Ethernet (100 MBit/s)

SIMOTION P350-3 / P320-3


• Design: P350-3: PC-Box with Windows XP PRO
P320-3: Embedded PC with Windows

l.c
Embedded Standard 2009
• Processor: Intel Pentium 2 GHz /
Intel Core2 Solo 1.2 GHz,

ai
• Memory: 2 GB RAM, 40 GB HD /
2 GB RAM, 4 GB CF card
• Drive link: PROFIBUS-DP or PROFINET /

• Interfaces

SIMOTION
Siemens AG 2013. All rights reserved.
3 x PROFINET

gm
1 x COM, 4 USB, 2 x Ethernet /
1 x Ethernet, 4 x USB

Date:
File:
10.01.2013
MC-SMO-PRG_01.17
SITRAIN Training for
Automation and drive technology
@
What is The C2xx is a motion control module for controlling servo drives via
SIMOTION C? PROFIBUS DP (PROFINET for C240 PN) and four onboard drive interfaces
(only C230-2 and C240).
The SIMOTION C is a powerful module for the independent single-axis
er

positioning or for axis group motions. It supports operation of both rotary and
linear axes.
The engineering system is used for the configuration, parameterization,
commissioning, programming and diagnostics of the SIMOTION C.
ez

What is SIMOTION P is a PC-based motion control system. Control, motion control and
SIMOTION P? HMI functions run concurrently on this PC.
For the P350-3, the drive coupling and the connection of distributed I/Os can be
r.s

made using either an IsoPROFIBUS board with two PROFIBUS interfaces


(clock-synchronous) or an MCI-PN board (4 x PROFINET).
The P320-3 combines PC technology with the advantages of a maintenance-
free embedded PC solution without rotating parts. It can be operated "headless"
(without display or monitor) or with a monitor using a DVI interface. The drive
ne

connection is made using three integrated PROFINET interfaces.


Unlike the SIMOTION C system, the controller-based solution that contains
parts of the SIMATIC S7 system, the SIMOTION P has the advantage of a PC
solution with standard PC applications running parallel to the motion control
program, large data storage, and rapid high-volume data processing.
ca

The P350/P320 has recently been optimized, in particular in the hydraulic


applications area. Together with the ET200 HS PN (High-Speed PROFINET) I/O
system, cycle times as fast as 250 µs, and consequently response times below
1 ms, can be implemented.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 17 SIMOTION – An Overview
The Various Hardware Platforms (2)
SIMOTION D425/425-2/435/435-2/445/445-2/455-2
• Comprises two systems:
• Processor for motion control MC-
• Processor for drive control Steuerung
• Design SINAMICS drive system

om
• Drive link Three PROFIBUS master systems:
one internal, two external
• Interfaces: 2 x PROFIBUS DP Antriebs-
2 x Ethernet (100 MBit/s) Steuerung
3 x PROFINET (only Dx45-2 PN/DP)

l.c
SIMOTION D410/410-2
• Comprises two systems:
• Processor for motion control

ai
• Processor for drive control D4x5/-2
• Design SINAMICS drive system
• Drive link Two PROFIBUS master systems:

• Interfaces :

SIMOTION
one internal, one external
1 x PROFIBUS-DP
or 1 x PROFINET

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.18
D410/-2

SITRAIN Training for


Automation and drive technology
@
What is SIMOTION D combines the SIMOTION functionality and the drive functionality
SIMOTION D? of a drive system on a single drive hardware system. This makes the complete
system very compact with a fast response.
SIMOTION D is always used when a compact machine concept and high
er

performance for motion control tasks are required in combination with high-
speed I/Os. SIMOTION D is offered in the performance variants: D425/-2 (low-
end performance range), D435/-2 (medium performance range), D445/-2 (high-
end performance range) and D455-2 (top performance range).
ez

As of V4.1, the D410 single-axis system is available for the modular expansion
of SIMOTION D systems. As of V4.3 the innovated System D410-2 with a multi-
axes option is available.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 18 SIMOTION – An Overview
Integration in TIA

Shared use of HMI

om
Shared communication:
PROFIBUS, PROFINET, Ethernet

T-CPU

l.c
C230-2/C240
P350-3/P320
D4xx

ai
Shared use of
distributed I/Os and

SIMOTION
drives via PROFIBUS
and PROFINET

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.19
SITRAIN Training for
Automation and drive technology
@
Totally Integrated TIA with SIMATIC contains all technologies, such as PLC, PC-based control,
Automation automation computer, distributed I/O, HMI systems, communication networks
and process control systems which are required in an automation environment.
TIA allows you to implement the solution that is technically required and makes
er

economic sense from a complete and integrated modular system. SIMOTION is


completely integrated in the TIA concept.

PROFIBUS DP Standard PROFIBUS DP with DP/V1 functionality


ez

• For connecting distributed I/Os


• For connecting a higher-level automation system
• For connecting HMI devices
r.s

• For connection to the SCOUT engineering system


All standard DP slaves (e.g. distributed I/Os, drives) can be connected to
PROFIBUS.

Industrial Ethernet Fast Industrial Ethernet that can be used for the following purposes:
ne

• Connecting HMI devices


• Connecting to the SCOUT engineering system
• Communication with TCP/IP and UDP (User Datagram Protocol)
ca

PROFINET PROFINET is the innovative and open Industrial Ethernet standard (IEC 61158)
for industrial automation. With PROFINET, devices can be linked up from the
field level through to the management/supervisory level.
With PROFINET, drives can be controlled isochronously via a network and
communication that is not critical from a time perspective (e.g. TCP/IP) can be
established between automation components.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 19 SIMOTION – An Overview
SIMOTION Documentation

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_01.20
SITRAIN Training for
Automation and drive technology
@
SIMOTION The SIMOTION printed documentation consists of individual documentation
documentation packages included in more than 50 SIMOTION documents and other documents
(e.g. SINAMICS).
The documentation packages are organized according to their functionality and
er

content. The documentation is contained in the various languages.


The following SIMOTION documentation packages are available:
• 1_Engineering_system_handling: consists of four manuals that describe
ez

the handling of the SIMOTION SCOUT engineering system and of the CamTool .
• 2_Description_of_system_and function describes the technical
operational sequences for the SIMOTION system and explains the technology
objects.
• 3_Programming: describes the three programming languages
r.s

MCC, LAD/FBD and ST@.


• 3_Programming_reference_lists: contains all reference lists required for
the programming as well as the description of the connection of drives and other
I/Os to a SIMOTION system.
ne

• 3_Service_angd_Diagnosis: describes the TO alarms, project


comparison, upgrading devices and the Task Trace functionality.
• 3_SIMOlTION_IT: describes the functionality of the Web Browser
interface for SIMOTION.
• 4_Additional_documentation: contains the descriptions of all product
ca

information as well as the connection of additional hardware components to


SIMOTION, e.g. ADI4, TM15 and TM17.
• 5_SIMOTION C: describes the C230-2 / C240 / C240 PN hardware
platform.
• 5_SIMOTION D: describes the D4xx hardware platform and the
SINAMICS S120 platform.
• 5_SIMOTION P: describes the P350-3 and P320-3 hardware platforms.

SITRAIN Training for MC-SMO-PRG


Automation and Drive Technology Page 20 SIMOTION – An Overview
Fundamentals of programming with Structured Text

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Integration of ST in SCOUT .............................................................................................................. 3
Generating an ST source file ............................................................................................................ 4
er

Specifying the ST source file compiler settings ................................................................................. 5


Settings for working with the ST editor ............................................................................................. 6
Names (identifiers) and syntax coloring in the ST editor ................................................................... 7
Structure of an ST source file ........................................................................................................... 8
ez

Components of the interface section ................................................................................................. 9


Components of the implementation section ...................................................................................... 10
Declarations in the interface and implementation parts .................................................................... 11
Declaration part of a program ........................................................................................................... 12
Validity of variables .......................................................................................................................... 13
r.s

Initializing variables .......................................................................................................................... 14


Overview of SIMOTION data types ................................................................................................... 15
Elementary data types for SIMOTION .............................................................................................. 16
The derived data type: ARRAY ......................................................................................................... 17
ne

Character strings (STRING) in ST .................................................................................................... 18


The derived data type: STRUCT ....................................................................................................... 19
The data type: Enumerator ............................................................................................................... 20
Technology object data types ........................................................................................................... 21
Statement part of a program ............................................................................................................. 22
ca

Types of statement in ST .................................................................................................................. 23


Expressions, operators, and operands in ST .................................................................................... 24
Assignments in ST ........................................................................................................................... 25
Access to I/Os and process images ................................................................................................. 26

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 Fundamentals of Structured Text
Fundamentals of programming with Structured Text

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.2
SITRAIN Training for
Automation and Drives
@
Contents Page
Access to individual bits with the "Permit language extensions" compiler option .............................. 27
Control statements: IF and CASE ..................................................................................................... 28
er

Control statements: FOR, WHILE, and REPEAT .............................................................................. 29


Control statements: EXIT and RETURN ........................................................................................... 30
Control statements: GOTO and WAITFORCONDITION ................................................................... 31
ez

Comments in ST .............................................................................................................................. 32
Controlling compilation with the preprocessor ................................................................................... 33
Example of how to use the preprocessor .......................................................................................... 34
Testing ST programs ........................................................................................................................ 35
r.s

Operating modes for program testing ................................................................................................ 36


The "Program status" test function ................................................................................................... 37
Monitoring variables with the symbol browser ................................................................................... 38
Monitoring variables in watch table ................................................................................................... 39
ne

New functions in the ST editor (as of V4.2) ....................................................................................... 40


Setting breakpoints in ST ................................................................................................................. 41
Specifying the "debug task group" .................................................................................................... 42
Setting breakpoints in an ST source file ............................................................................................ 43
ca

Specifying the call path ..................................................................................................................... 44


Activating breakpoints in the ST source file ...................................................................................... 45
Monitoring variables at a breakpoint ................................................................................................. 46
Use "break points" and "Program status" simultaneously .................................................................. 47
Recording variables with the trace tool ............................................................................................. 48
Diagnostics with the TO trace ........................................................................................................... 49

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Fundamentals of Structured Text
Integration of ST in SCOUT

Compiling Program status

om
Editor

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Symbol browser

Date:
File:
10.01.2013
MC-SMO-PROG_02.3
SITRAIN Training for
Automation and Drives
@
ST programming The ST programming environment essentially consists of the editor, the
environment compiler, and the integrated test functions:
• ST editor
er

Programs are created with a user-friendly text editor. You can use this editor
to create programs consisting of functions (FC), function blocks (FB), and
user-defined data types (UDT).
• ST compiler
ez

The ST compiler converts edited programs into downloadable code. After


compilation, it displays every syntax error, indicating´the program line and
the cause of the error.
When a program has been compiled without errors, it can be downloaded to
the target system and tested.
r.s

• ST test functions
ST programs are tested with the "Program status" function. It is particularly
useful for locating logical programming errors in running programs.
The symbol browser can also be used to observe and change the content of
ne

variables in the user program.


Each of the components of the ST programming environment is easy and
convenient to use and is integrated directly into the SIMOTION SCOUT
Workbench.
ca

External editor An external ST editor can also be integrated into the SIMOTION SCOUT
Workbench.
1. To do this, open the "Settings" dialog by selecting Options -> Settings
from the menu and go to the "External ST editor" tab.
2. Check the "Use external ST editor" box and enter the path and the required
program.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Fundamentals of Structured Text
Generating an ST source file

Enter name
(max. 128 characters)

om
l.c
ai
Double-click

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.4
SITRAIN Training for
Automation and Drives
@
Inserting an ST
source file ST source files are assigned to the SIMOTION device on which they are to run.
1. Open the appropriate SIMOTION device in the project navigator.
er

2. Select the "PROGRAMS" folder.


3. Double-click the "Insert ST source file" entry or select the menu command
Insert -> Program -> ST source file.
The "Insert ST source file" dialog opens.
ez

4. Enter a name of your choosing for the ST source file on the "General" tab.
Names for program source files must satisfy the rules for identifiers:
They are made up of letters (A … Z, a … z), numbers (0 … 9), or single
underscores (_) in any order, whereby the first character must be a letter
r.s

or underscore.
Names are not case-sensitive. They start with a letter or an underscore and
can contain up to 128 characters.

5. If applicable, select the "Compiler" tab so that you can make the local
ne

compiler settings for this ST source file.


6. Confirm with "OK". The new ST source file created is displayed in the
selected folder and opens in the ST editor.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Fundamentals of Structured Text
Specifying the ST source file compiler settings

Permit program
status

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.5
SITRAIN Training for
Automation and Drives
@
Compiler The following settings can be made on the "Compiler" tab:
• Use global settings: The selected global settings are applied.
The global settings can be selected under the menu command:
Options -> Settings -> Compiler.
er

Once the "global setting" has been deselected, the relevant option can
be selected locally, i.e. specifically for the source file.
• Selective linking: Unused code is removed from the executable program.
ez

• Use preprocessor: The preprocessor prepares an ST source file for


compilation. For example, character strings can be defined as replacement
texts for identifiers, or sections of the source program can be hidden/shown
for compilation.
• Enable program status: Check this option if you want to perform a test using
r.s

the block status later on. In this case, additional program code is generated
to enable variables (including local variables)
to be monitored.
• Permit language extensions: Language elements are permitted that do not
comply with IEC 61131-3.
ne

• Only create program instance data once: The local variables of a program
are only stored once in the user memory of the unit. The setting is required
when a further program is to be called within a program.
• Issue warnings: In addition to error messages, the compiler can issue
ca

warnings. You can set the scope of the warning messages to be issued.
• Permit forward declarations: When calling a block, the compiler must not
yet have compiled that block; it must only know the signature (name,
parameters, etc.).
• Permit OPC-XML: Symbol information about the unit variables of the
interface section is loaded to the target system.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Fundamentals of Structured Text
Settings for working with the ST editor

Options -> Settings

om
l.c
ai

SIMOTION
Command library

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.6
SITRAIN Training for
Automation and Drives
@
Command library The navigation window for working with the ST editor can be switched over to
display the command library instead of the project structure.
The command library contains all functions and operators (e.g. mathematical
operators, technology, PLCopen, etc.) that can be used within the ST
er

language. The individual commands are combined in groups (e.g. arithmetic


group) on the Command library tab.
The individual operators and functions can be dragged from the library window
to the ST editor workspace using a drag and drop operation.
ez

The following settings can be made on the "ST editor" tab in the "Settings"
ST editor settings dialog:
• Display line numbers: If active, the line numbers are displayed.
• Replace tabs with blanks: Tab entries are replaced with the
r.s

corresponding number of blanks.


• Tab width: Number of characters skipped by a tab.
• Status format: Format in which the values of program variables are
displayed when the "Program status" test function is selected.
• Tooltip display for function parameters: When active, the parameters
ne

are displayed as tooltips for the functions.


• Automatic indent/outdent: When text is input, blocks that belong
together are indented automatically by the set tab width.
• Folding active: The column with the folding information is displayed
ca

on the left-hand side next to the edit area.


• Display indent level: The indents and outdents for blocks are optically
highlighted by vertical auxiliary lines.
• Display pairs of brackets: The associated bracket of the pair that
belongs to the bracket where the cursor is located is found and optically
highlighted.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Fundamentals of Structured Text
Names (identifiers) and syntax coloring in the ST editor

Own name (identifier)


consisting of:
„ Letters (a...z, A..Z) user defined name
„ Digits (0...9) (black)
„ Underscore (_)

om
Restrictions Keywords
„ No umlauts (blue)
„ Not case-sensitive
„ Must not start with a digit
„ Should not start with an Constants:
underscore (reserved for (pink)

l.c
SIEMENS)
„ Must not be the same as
"keywords"

Keywords

ai
„ Have a fixed meaning
„ Are displayed in blue
Comments:

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.7
(green)

SITRAIN Training for


Automation and Drives
@
ST character set ST uses the following letters and digits from the ASCII character set:
• The lower and upper case letters from A to Z (no umlauts)
• The Arabic digits from 0 to 9
er

Letters and digits are the most commonly used characters.

Identifier (name) A user-defined name (identifier) for a data type, a variable, or a block can
consist of letters (no umlauts), digits, and the underscore character. The
ez

underscore is a special character.


The use of other special characters (ie+, - ,*, etc.) in own names (identifiers)
is not permitted. Special characters has a specific meaning in ST (e.g. + for
addition, etc.).
Identifiers are not case-sensitive.
r.s

Reserved identifiers ( keywords) are names with a fixed meaning


Reserved (e.g. IF, ELSE, PROGRAM, etc.) within the SIMOTION programming system. ^A
identifiers list of all identifiers with a predefined meaning can be found in the SIMOTION
Basic Functions Function Manual.
ne

Reserved identifiers must not be used as own names. Therefore, these


identifiers are displayed in blue in the ST editor (see below).
The ST editor supports syntax coloring. What this means is that the various
language elements of an ST source file are displayed in different colors:
ca

Syntax coloring

• Blue: Keywords
• Green: Comments
• Black: The names of technology objects, variables, and blocks, as well
as user code
• Pink: Constants

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Fundamentals of Structured Text
Structure of an ST source file
UNIT example

INTERFACE
Connection to
other units
END_INTERFACE and to the
execution system

om
IMPLEMENTATION

FUNCTION adder : LREAL

END_FUNCTION

l.c
FUNCTION_BLOCK homing

END_FUNCTION_BLOCK
...

ai
PROGRAM Truing

END_PROGRAM

SIMOTION
END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.8
SITRAIN Training for
Automation and Drives
@
ST source file An ST source file is a logical unit that you can create in your project. It is also
referred to as a unit.
In principle, a unit consists of flowing text split into logical components by
keywords such as UNIT, INTERFACE, etc. The logical parts of an ST source file
er

are also called sections. Specific keywords are used to mark the start and end of
each logical section of an ST source file.

UNIT name The name of the unit can be specified but does not have to be; if it is, it must
ez

appear at the start of the ST source file. If the name is used, it must match the
name of the ST source file entered under the settings in the corresponding
dialog.
r.s

INTERFACE Obligatory part of a unit. The interface section contains statements for importing
and exporting data (data types, variables, function blocks, functions, and
programs). Technology packages, libraries, and the INTERFACE component of
other units can also be loaded.
ne

IMPLEMENTATION Obligatory component of a unit. As well as the declaration of private data types
and variables, it contains the executable sections or POUs (program
organization units).

POUs are the executable source file sections, e.g.: functions, expressions,
ca

Note function blocks, and programs.

The POU called must always be in a unit upstream of the calling block.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Fundamentals of Structured Text
Components of the interface section

UNIT example
INTERFACE
// Specification of imports Import of:
USEPACKAGE CAM; • Technology packages
USELIB Lib_1, Lib_2; • Libraries

om
USES control, diagnostics; • Units

// Public variables and data types


TYPE Declaration and export of
Color : (red, yellow, blue);
END_TYPE • Variables

l.c
VAR_GLOBAL • Data types
set, actual: LREAL;
END_VAR

Export of:

ai
// Specification of public blocks
PROGRAM display; • Programs (necessary for
task assignment)
FUNCTION adder;
• Function blocks
END_INTERFACE

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.9
• Functions

SITRAIN Training for


Automation and Drives
@
Interface section The interface section always follows the specification of the UNIT component.
There must only be one interface section per ST source file. The interface
section contains statements for the export (data types, variables, function
blocks, functions, programs) and import of technology packages, libraries, and
er

other units.

Technology The USEPACKAGE tp-name keyword is used to specify the technology


packages package to be used within the ST source file. The technology package then
ez

makes the system functions and variables required for compiling the ST source
file available.

Libraries The USELIB library_name-list keyword enables libraries or components of


libraries to be used in the unit.
r.s

Units The USES unit_name-list keyword is used to reference other units so that their
exported components such as variables, data types, etc. can be imported
(importing unit).
ne

The USES keyword can also be used in the implementation section.

Export Data and code blocks can be exported here. The following are permitted at
variable and type declarations:
• TYPE for the full declaration of user-defined data types
ca

• VAR_GLOBAL, VAR_GLOBAL_RETAIN, VAR_GLOBAL CONSTANT for


the declaration of global variables
FCs, FBs, and programs used in other units can also be specified. A program
assigned to a task in the execution system must also be exported.

Note Follow the sequence specified above when making specifications in the
interface section. Otherwise, error-free compilation of the ST source file will not
be possible.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Fundamentals of Structured Text
Components of the implementation section
UNIT example
IMPLEMENTATION
// Private, unit-global variables and
// data types
TYPE Declaration of unit-global
Mode: (active, inactive); • Data types

om
END_TYPE
• Variables
VAR_GLOBAL
State: Mode := active;
END_VAR

// Implementation of public and


// private blocks

l.c
PROGRAM display
Declaration part
. . .
END_PROGRAM

ai
FUNCTION adder : LREAL
Statement part
. . .
END_FUNCTION

SIMOTION
. . .
END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.10
SITRAIN Training for
Automation and Drives
@
Implementation The implementation section contains declarations and the executable sections,
section making it the primary component of the ST source file. The implementation
section follows the interface section. There must be one implementation section
per ST source file.
er

Declaration The following variable and type declarations are permitted within the declaration
section section:
• TYPE for the declaration of user-defined data types
ez

• VAR_GLOBAL, VAR_GLOBAL RETAIN, VAR_GLOBAL CONSTANT for


the declaration of global variables
Unlike the declarations in the INTERFACE section, these types and variables
are not exported to other units.
r.s

Functions (FC) FCs are parameterizable POUs that can be called from programs and function
blocks. FCs do not have a "memory", i.e. they are not able to "remember"
information from one call to another.
FC variables are only ever temporary; they are initialized on every call.
ne

Expression Expressions are a special type of function declaration with a BOOL data type
return value. The WAITFORCONDITION function is used so that a MotionTask
can wait specifically for a programmable event or condition. The command
ca

suspends the task that called it until the condition (expression) is true.

Function block FBs are parameterizable POUs which can be called from programs and other
(FB) FBs. Unlike FCs, FBs have a "memory", i.e. they are able to "remember"
information in static variables from one call to another.

Programs Programs are called by the operating system on the target device based on their
task configuration. More FBs and FCs can be be called within a program.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Fundamentals of Structured Text
Declarations in the interface and implementation parts

VAR_GLOBAL CONSTANT Type declarations (UDT):


PI: REAL := 3.14159;
NUM: INT:= 100; • Elementary data type
END_VAR • Derived data types
TYPE - Simple data type
Speed: REAL; - Structures

om
Motor: STRUCT
Setpoint_speed : Speed; - Fields
Actual_speed : Speed; - Enumerators
Enable: BOOL;
Fault: BOOL; • TO/system data types
END_STRUCT;
Meas_values: ARRAY[1..NUM] OF REAL;
State: (active, passive);

l.c
XYZ_Achse: posAxis; Global variables:
END_TYPE
• VAR_GLOBAL
VAR_GLOBAL
• VAR_GLOBAL CONSTANT
FullBottles: INT := 123;

ai
EmptyBottles: INT; • VAR_GLOBAL RETAIN
END_VAR

VAR_GLOBAL RETAIN

SIMOTION
OperatingRuntime: UINT;
END_VAR

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.11
SITRAIN Training for
Automation and Drives
@
User-defined User-defined data types or UDTs can be created with the TYPE/END_TYPE
data types construct in the following declaration sections:
• Interface part
• Implementation part
er

• POU
The data types created can be used again in the same or subsequent
declaration section. Moreover, UDTs can be nested at will. Predefined UDTs
ez

can be used as data type specifications, for example.


The declared UDTs can then be used for subsequent variable declarations.

Variables A variable defines a memory space with variable content. A variable consists of
r.s

an identifier that can be selected at will (e.g. myVar1), the specification of a data
type (e.g. INT), and any applicable modifiers (e.g. CONSTANT, RETAIN), which
define access or how the content responds in the event of a POWER OFF.
The following types of variable can be declared within an interface and
implementation section:
ne

• Global variables (VAR_GLOBAL) are variables which support read and write
access from the user program. When
the controller shuts down, the content of the variables is lost. Global
variables can be initialized during declaration.
• Global "read-only" variables (VAR_GLOBAL CONSTANT) only support
ca

read access from the user program. "Read-only"


variables must be initialized during declaration.
• Retain variables support read and write access; their content is not
lost in the event of a POWER OFF. When the controller shuts down, the
content is saved in an internal Flash for reloading in the original location the
next time the controller starts up.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 Fundamentals of Structured Text
Declaration part of a program
PROGRAM MyProgram
• PROGRAM name
TYPE
State : (OPEN, CLOSED);
END_TYPE • Type declarations for internal
VAR data types
NumMeasValues: INT;

om
NumTests: INT := 5; • Variable declarations:
Guard: State;
END_VAR • VAR (static variables)
VAR_TEMP • VAR_TEMP (temporary variables)
IntermResult: REAL; • VAR CONSTANT (constants)
END_VAR

l.c
VAR CONSTANT • Static and temporary variables
Pi: REAL := 3.14;
END_VAR can be initialized; constants
must be initialized.
;

ai
IntermResult:= NumTests * Pi;

SIMOTION
END_PROGRAM

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.12
SITRAIN Training for
Automation and Drives
@
TYPE ... END_TYPE User-defined data types or UDTs can be declared in the declaration section of a
PROGRAM with the TYPE/END_TYPE construct.

Unlike declaration within the IMPLEMENTATION or INTERFACE part, the data


er

types defined here can only be used for subsequent variable declarations
VAR within the PROGRAM.

The VAR keyword is used to declare variables of any data type in a program.
ez

Local variables (VAR) of a program are simatic when used in cyclic tasks. In
sequential tasks, they are temporary; i.e. they are reinitialized every time the
task (e.g. MotionTask_1) starts.
In these variables, a program that is running in a cyclic task can remember
information from cycle to cycle (memory).
r.s

VAR_TEMP
The keyword VAR_TEMP is@ used to declare temporary variables in a
program. Temporary program variables are local user variables which are
reinitialized every time the program is called.
Temporary variables are used to save intermediate results which are produced
ne

at the start of program execution, for example, and processed further later in
the same program cycle.
VAR CONSTANT Constants are data with a fixed value. This value cannot change at program
runtime. Constants are declared in the same way as variables.
ca

The value assigned to a constant is calculated from the initialization expression


at the time of compilation.

Initialization All local variables of a program can be initialized during declaration. Constants
must be initialized during declaration. If an initialization value is not declared for
a variable, it is pre-assigned the value "0".

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 Fundamentals of Structured Text
Validity of variables
SIMOTION device
UNIT left UNIT right
Global device
variables

INTERFACE INTERFACE Validity


VAR_GLOBAL VAR_GLOBAL

om
END_INTERFACE END_INTERFACE
Unit variable
(interface part)
IMPLEMENTATION IMPLEMENTATION
Validity
VAR_GLOBAL VAR_GLOBAL

PROGRAM test1 PROGRAM test1


VAR VAR Unit variable

l.c
(implemen-
tation part)
END_PROGRAM END_PROGRAM
Validity

ai
PROGRAM test_n PROGRAM test_n
Local variable
Validity

SIMOTION
END_PROGRAM
END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


gm
Date:
File:
END_PROGRAM
END_IMPLEMENTATION

10.01.2013
MC-SMO-PROG_02.13
SITRAIN Training for
Automation and Drives
@
Global device Global device user variables are created with the symbol browser:
variables For this purpose, the "Global device variables" entry must be selected in the
project window underneath the required SIMOTION device. The required
variables can then be created in the symbol browser window with identifier, data
er

type, initial value, and settings for POWER OFF.


These variables can be accessed from all parts of the user program. Global
device variables can be monitored and controlled in the symbol browser. They
can also be accessed from OCM devices.
ez

Global unit Global unit variables can be declared in the interface or implementation part
variables of the unit.
In the case of declaration in the interface part, the variables become exportable
r.s

variables which can also be used in POUs of other units. These variables (with
the exception of CONSTANT) can be monitored and controlled in the symbol
browser. They can also be accessed from OCM devices.
In the case of declaration in the implementation part, the global variables can
only be used in the POU of the unit concerned (they are the private property of
ne

the unit, as it were). Although these variables can be monitored in the symbol
browser, they cannot be accessed from OCM devices.
Variables can also be saved as data sets on an MMC or CF card and reloaded.
Values of retain unit variables (VAR_GLOBAL RETAIN) are not saved. The
system supports the following functions for saving and reloading values:
ca

• _saveUnitDataSet()/exportUnitDataSet() //Save data of a UNIT


• _loadUnitDataSet()/_importUnitDataSet() //Reload data
• _deleteUnitDataSet() // Delete data set

Local variables Local variables can only be used in the associated POU in which they were
declared. These variables can neither be monitored in the symbol browser nor
accessed from OCM devices. Local variables are the private property of the
corresponding POU, as it were.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 Fundamentals of Structured Text
Initializing variables
INTERFACE
VAR_GLOBAL RETAIN Initialization on
RuntimeMeters : UDINT;
END_VAR "OVERALL RESET" or "Download"
VAR_GLOBAL
InitialPosition: LREAL; Initialization on
END_VAR "Power On" and "OVERALL RESET"
. . .
(also on STOP -> RUN as of V4.2)
END_INTERFACE

om
IMPLEMENTATION
VAR_GLOBAL RETAIN Initialization on
MyCounter: INT;
END_VAR "OVERALL RESET" or "Download"
Initialization on
VAR_GLOBAL
"Power On" and "OVERALL RESET"

l.c
MyValue: LREAL;
END_VAR (also on STOP -> RUN as of V4.2)
PROGRAM MyProgram
VAR // static Initialization on start of task,
Counter: INT; e.g. transition: STOP -> RUN
END_VAR

ai
VAR_TEMP // temporary
Initialization on program
IntermediateValue : REAL; call or function block call
END_VAR

SIMOTION
. . .
END_PROGRAM
END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.14
SITRAIN Training for
Automation and Drives
@
Initialization of The type of the variables (VAR_GLOBAL RETAIN, etc.) determines when their
variables contents are reset to their initialization values. The initialization value of a variable
can be specified during declaration; if it is not, the initialization value is equal to 0.
er

These variables retain their values even after the controller shuts down.
VAR_GLOBAL In other words, after a controller restart, the original value is retained. The
RETAIN initialization values are restored when an OVERALL RESET (switch position:
MRES) is performed and, dependent upon the settings made under Options ->
ez

Download -> "Initialization of all retentive variables", also when a project is


downloaded.

These variables usually retain their contents when the controller is set to STOP
r.s

VAR_GLOBAL
operating mode due to an error, for example, and then reset to RUN. They
"lose" their contents when the controller is shut down and when an overall reset is
performed. When the controller is powered up or an overall reset is performed, the
contents of the variables are set to the initialization values. This also happens when
a project is downloaded (dependent upon the settings made under Options ->
ne

Download -> "Initialization of all non-retentive variables").


As of V4o.2, initialization on transition from STOP to RUN can also be activated
on the "Settings" tab in the properties dialog of the SIMOTION device.

In programs, these variables are static in nature, i.e. they are only reset to the
ca

VAR initialization values if the task in which the program is running is restarted. In FBs,
these variables are part of the instance data area, i.e. initialization depends upon
the variable type (VAR_GLOBAL RETAIN, etc.) under which the associated FB
instance was declared.

These variables are temporary in nature, i.e. their contents are reset to the
VAR_TEMP initialization values every time the program or the FB/FC (in the case of FC this
corresponds to the type: VAR) is called.
r

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 Fundamentals of Structured Text
Overview of SIMOTION data types

• Bit data types (BOOL, BYTE, WORD, DWORD)


Elementary
data types • Numerical data types (SINT, USINT, INT, REAL, etc.)
• Time types (TIME, DATE, TIME_OF_DAY, DATE_AND_TIME)

om
• Field (ARRAY)

l.c
• Character string (STRING)
Compound
• Structure (STRUCT)
(derived)
data types • Enumerators (ENUM)

ai
• TO (Technology Objects)

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.15
SITRAIN Training for
Automation and Drives
@
Overview Solutions for automation tasks provided by computer systems are based on
algorithms which process the process data captured by sensors and output new
manipulated variable values to the actuators. Programs are ultimately
formulations of algorithms based on certain representations of data or data
er

structures.
Elementary The elementary data types are the smallest elements of any programming
data types
system. The selection of elementary data types in a programming system says
ez

much about the intended area of application.


In SIMOTION, the elementary data types are predefined according to
IEC 61131-3. The data types has been selected to allow timestamp
management and high-precise on motion control in addition to the conventional
r.s

tasks of a PLC, which include digital and analog signal processing.


With elementary data type@s, the corresponding memory area occupied by a
variable is uniquely defined.
Compound
The fundamental idea behind data structuring is the separation of
ne

data types
elementary and higher structures. Elementary structures are the tiny elements
which are used to build compound data types.

In SIMOTION, the compound data types declared by the user are supplemented
by dedicated data types provided by the corresponding technology packages
ca

and by the system for handling the supported objects (driveAxis, posAxis, etc.).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 Fundamentals of Structured Text
Elementary data types for SIMOTION

Keyword Width (in bits) Value range


BOOL 1 or 8 *) 1 or 0 (TRUE/FALSE)
BYTE 8 16#0 to 16#FF
WORD 16 16#0 to 16#FFFF

om
DWORD 32 16#0 to 16#FFFFFFFF
SINT 8 -128 to 127
USINT 8 0 to 255
INT 16 -32768 to 32767
UINT 16 0 to 65635
DINT 32 -2147483648 to 2147483647
0 to 4294967295

l.c
UDINT 32
REAL 32 -3.040282E38 to 3.040282E38
LREAL 64 -2.225073E308 to 2.225073E308
TIME 32 TIME#49d_17h_2m_47S_295mS
DATE 32 DATE#2200-12-31

ai
TIME_OF_DAY 32 TIME_OF_DAY#23:59:59.999
DATE_AND_TIME 64 DT#2200-12-31-23:59:59.999

SIMOTION
Siemens AG 2013. All rights reserved.
gm
* BOOL type operands only occupy 1 bit if they are defined as inputs or outputs in the I/O list;
if they are defined as variables in the memory, they occupy 1 byte (8 bits).

Date:
File:
10.01.2013
MC-SMO-PROG_02.16
SITRAIN Training for
Automation and Drives
@
BOOL, BYTE, BOOL data type variables consist of one bit; BYTE, WORD, DWORD data type
WORD, DWORD variables are sequences of 8, 16, and 32 bits respectively. The individual bits
are not processed in these data types.
er

SINT, INT, DINT... Variables of these data types represent integers for performing corresponding
arithmetic operations (counter instructions).

SIMOTION supports both signed integers such as SINT, INT, and DINT and
the corresponding unsigned data types: USINT, UINT, and UDINT.
ez

REAL, LREAL These are numeric data types with decimal places. In addition to counting
operations, they can be used for extended mathematical operations and
functions (such as the trigonometric functions sin, cos, etc.).
r.s

TIME, DATE, etc. These data types are used to manage time stamps in the user program of a
SIMOTION device.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 Fundamentals of Structured Text
The derived data type: ARRAY
Measuring point: ARRAY[1..10]
ARRAY: Meas_point[1]: Real
• Grouping of Meas_point[2]: Real
components of the Meas_point[3]: Real
.
same data type . .
.
• Declaration and access: Meas_point[10]: Real

om
TYPE
a : ARRAY[1..6] OF REAL; // 1-dim. array (6 columns)
matrix : ARRAY[1..4] OF a; // 2-dim. array (4 rows with 6 columns)
END_TYPE

l.c
VAR
a_1 : a; // Variable of 1-dim. array data type
b_1 : a := [1,2,3,3(4)]; // Variable with initialization
m_1, m_2 : matrix; // 2-dim. array
END_VAR

ai
m_1[4][6] := 9.0; // Write to row 4, column 6
m_1 := m_2; // Assignment of a complete array

SIMOTION
m_1[4] := a_1;
IF m_1 = m_2 THEN ...

Siemens AG 2013. All rights reserved.


gm
Date:
File:
//
//
Assignment of a part ARRAY
Comparison operation (=, <>)

10.01.2013
MC-SMO-PROG_02.17
SITRAIN Training for
Automation and Drives
@
ARRAYs The ARRAY data type is a field from a fixed number of components of the same
data type. An array can be multidimensional (number of indices).
The index specification describes the limits of the array:
• The array limits specify the minimum and maximum value for the index.
er

They can be defined by SINT, USINT, INT, UINT, or DINT data type
constants or initialization expressions.
• The array limits must be separated by two periods.
ez

• The entire index specification is enclosed in square brackets.


• The index itself can be an integer of data type SINT, USINT,
INT, UINT, DINT, or UDINT.
r.s

Types of ARRAY There are several different types of ARRAY:


• The one-dimensional ARRAY type is a list of data elements arranged in
ascending order.
• The two-dimensional ARRAY type is a table of data consisting of lines and
columns. The first dimension refers to the line number, the second to the
ne

column number.
• The higher-dimensional ARRAY type is an expansion of the two-dimensional
ARRAY type that includes additional dimensions.
ca

Note If array limits are violated during runtime, a processing error occurs in the
program.

Access Arrays can be accessed by component or in their entirety, e.g.:


• ArrayName [index_1] ... [index_n] := . . .
• ArrayName := . . .
As of V4.0, the "Comparator at equal to" = and "Comparator at not equal to" <>
operations are supported for ARRAY operands of the same type.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 Fundamentals of Structured Text
Character strings (STRING) in ST
STRING: Data type with a maximum length of 254 characters
• Variable declaration
AxisName1 : STRING[120]; // Maximum length 120 characters
AxisName2 : STRING; // Maximum length 80 characters

• Example assignments:

om
AxisName1 := 'Transporter';
• Comparison operations:
IF AxisName1 = AxisName2 THEN.. (<, >, <=, =<, =>, >=, = , <>)
• String functions (Command library "Character strings"):
CONCAT (attaches two strings together) LEN (returns the length)

l.c
DELETE (deletes sub character string) LEFT (returns the left character string)
FIND (returns the pos. of a character string) MID (returns character string from string)
REPLACE (first character string in string) RIGHT (returns right character string)
• Assignments to BYTE type variables

ai
byteVar := string20[5];
string20[10] := byteVar;

SIMOTION
• Conversions from and to DINT/UDINT/REAL/LREAL
myString := REAL_TO_STRING(myReal);
myLReal := STRING_TO_LREAL(myString);

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.18
SITRAIN Training for
Automation and Drives
@
STRING As of V4.0, the STRING data type is available in SIMOTION. It enables the user
program to manage names and texts on the SIMOTION runtime system and
send/receive them to/from a connected operator control and monitoring system.
The STRING data type is used to record character strings. A character string is
er

a sequence of 0 or more characters with an apostrophe at the start and at the


end. Each character is encoded with 1 byte (8 bits) in the string (ASCII string).
A character can be entered as follows:
ez

• As printable characters (ASCII code $20 to $7E, $80 to $FF), except the
dollar sign (ASCII code $24) and apostrophe (ASCII code $27), as these
have a special function within the string
• Using the two-digit hexadecimal ASCII code of the corresponding character
preceded by a dollar sign ($).
r.s

In ST language, string variables can be declared with a max. length of 254


characters. The number is specified in square brackets when the variable is
declared (e.g. STRING[124]). If no characters are specified (e.g. just STRING),
the default length is 80 characters.
As of V4.1, individual elements (components) of a string variable can be
ne

accessed.

Operations String variables are used to assign constant character strings (e.g. 'Fueller_rot')
or other string variables. Comparison functions are also available
ca

(lexicographical comparison). When comparing two string variables of different


lengths, the shorter variable is expanded to the length of the longer one by
inserting $00.
V4.1 and higher supports the explicit data type conversion of STRINGS from
and to DINT, UDINT, REAL, and LREAL using the corresponding standard
functions.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 Fundamentals of Structured Text
The derived data type: STRUCT
Motor: STRUCT
STRUCT (structure): Setpoint speed: REAL
• Grouping of Actual speed: REAL
components of Enable: BOOL
different data types
Fault: BOOL
• Declaration and access: END_STRUCT

om
TYPE // UDT definition
Motor : STRUCT
Setpoint_speed : REAL := 10.0;
Actual_speed : REAL;
Enable : BOOL;

l.c
Fault : BOOL;
END_STRUCT;
END_TYPE

VAR

ai
Motor_1 : Motor; // Variables of data type Motor
Motor_2 : Motor := (setpoint_speed:= 100.0, fault:= TRUE)
END_VAR

SIMOTION
Motor_1.setpoint_speed := 100.0; //
Motor_1 := Motor_2;
IF Motor_1 = Motor_2 THEN ...

Siemens AG 2013. All rights reserved.


//
//
gm
Date:
File:
10.01.2013
Write to structure
Assignment of entire structure
Comparison operation (=, <>)

MC-SMO-PROG_02.19
SITRAIN Training for
Automation and Drives
@
Structure The derived data type STRUCT, or structure, encompasses an area of a fixed
number of components in the TYPE/END_TYPE construct; the data types of
these components can vary:
The following are permitted as data types:
er

• Elementary data types


• Previously declared UDTs
• ARRAY data type specification
ez

• TO data types
• System data types
If you wish, you can define initialization values when declaring the data type
and/or when creating variables (as of V4.0).
r.s

Note The following data specifications cannot be used directly within a component
declaration:
• STRUCT data type specifications
• Enumerator data type specifications
ne

In this case, a UDT (user-defined data type) must be declared with the
required data type first. This UDT can then be used for component declaration.
kA component of the structure is addressed using the following syntax:
Access
ca

• StructureName.ComponentName
A period must be inserted as a separator between StructureName and
ComponentName. In the user program, the entire structure can of course be
accessed for assignments.
As of V4.0, the "Comparator at equal to" = and "Comparator at not equal to" <>
operations are supported for STRUCT variables of the same type.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 Fundamentals of Structured Text
The data type: Enumerator

Enumerator: 1 OPENING
1 1
• Limited number of
identifiers (names) 0 1 2
2 1
• Declaration and access: OPEN
3
CLOSED CLOSING

om
State graph for a guard

TYPE
GuardState :(CLOSED := -1, OPENING := 2, OPEN, CLOSING);
END_TYPE

l.c
VAR
myGuard : GuardState; // GuardState type variables
myDINT : DINT; // DINT type variables
END_VAR

ai
myGuard := CLOSED; // Access to myGuard
myGuard := GuardState#OPEN;
IF myGuard = OPEN THEN ... // Comparison operation(=, <>)

SIMOTION
myDINT := ENUM_TO_DINT(GuardState#OPEN);

Siemens AG 2013. All rights reserved.


gm
myDINT := ENUM_TO_DINT(myGuard); // Returns 3 in this case

Date:
File:
10.01.2013
MC-SMO-PROG_02.20
SITRAIN Training for
Automation and Drives
@
Enumerator For the enumerator data types, a limited number of identifiers or names are
assigned to the data type to be defined in the TYPE/END_TYPE construct.
Internally, DINT data type numbers are assigned to the individual values (e.g.
OPEN, CLOSED, etc.) which can accept an enumerator data type.
er

As of V4.0, the individual names can be initialized with DINT type values during
declaration. In the absence of initialization, the number 0 is assigned to the first
name, the number 1 to the second name, etc. Once a name is initialized with a
value, when the next name is initialized, it is assigned the same value
ez

incremented by one, and so on.


As of V4.0, the internal number assigned to a name can be assigned to a DINT
type variable using the ENUM_TO DINT function.

Variables and Once the Identifier data type has been declared, enumerator data type variables
r.s

operations can be declared. In the statement part, you can assign only elements from the
list of defined identifiers (enumerator elements) to these variables.
To integrate the data type into this assignment, you can prefix the enumerator
element with the identifier of the enumerator data type and the character "#".
ne

In addition to the ":=" assignment, the comparison operations "=", "<>", "<=",
">=", "<", and ">" are also supported at possible operations for an enumerator
data type.

Note Both the operating system and the technology packages often use predefined
ca

enumerators to identify properties such as task states (RUNNING, STOPPED,


etc.), axis states (ACCELERATING, STANDSTILL), etc.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 Fundamentals of Structured Text
Technology object data types
driveAxis: STRUCT
Technology object: camType internaltotrace: ARRAY
• Structure + functions sensormonitoring:structaxissensormonitoring
(provided by driveAxis
actordata: structaxissensordata
SIMOTION)
posAxis ...
• Declaration and access: ... END_STRUCT

om
VAR
myAxis : posAxis; // Variable for axis
myPos : LREAL; // Variable for position of axis
retVal : DINT; // Variable for return value of TO function
END_VAR

l.c
myAxis := Axis_1; // The name "Axis_1" was defined when the axis
// was configured

// Axis is enabled.
retVal := _enableAxis(axis := myAxis);

ai
// Axis is positioned.
retVal := _pos(axis := myAxis, position := 100);

SIMOTION
Siemens AG 2013. All rights reserved.
// Scan the position
gm
myPos := myAxis.positioningState.actualPosition;

Date:
File:
10.01.2013
MC-SMO-PROG_02.21
SITRAIN Training for
Automation and Drives
@
Technology objects TOs incorporate fixed structures and functions provided by the individual
(TO) technology packages. For variables of a TO to be declared, the corresponding
technology package must be loaded in the interface part.
SIMOTION provides the following TOs:
er

• Drive axis (data type: driveAxis)


• Position axis (data type: posAxis)
• Following axis (data type: followingAxis)m
• Following object (data type: followingObjectType)
ez

• Cam (data type: camType)


• Measuring input (data types: measuringInputType)
• Output cam (data type: outputCamType)
• External encoder (data type: externalEncoderType)
r.s

• Temperature controller (data type: temperatureControllerType)


• General data type u(ANYOBJECT)

The data types for technology objects are dependent on the technology package
downloaded. The elements of technology objects can be accessed in the same way
ne

Properties as with structures.

Inheritance can also be used between TOs. Inheritance for axes means that all of
the data types, system variables, and functions of the driveAxis TO are fully included
in the posAxis TO. In turn, posAxis is fully included in the followingAxis TO.
ca

If a function or a function block expects an input parameter of the driveAxis data


type, inheritance allows you to also specify a posAxis or a followingAxis when
making the call.
The same applies if the input parameter expects a posAxis. Here too, a followingAxis
can be specified when making the call.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 Fundamentals of Structured Text
Statement part of a program
PROGRAM MyProgram

VAR
minHeight: REAL:= 2.2;
Height : REAL;
Length : REAL;
Write access Width : REAL;
Read access

om
END_VAR

VAR_TEMP
Area: REAL;
Volume: REAL;
END_VAR
;

l.c
Area: = Length * Width;
Volume: = Area * Height;
;
IF volume < 5.0 THEN
Control structure
Length:= 2.5; // Comment

ai
Width:= 2.0;
END_IF;

END_PROGRAM

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.22
SITRAIN Training for
Automation and Drives
@
Statement part The actions to be executed with the data introduced in the declaration part and
the global data are described in the statement part of a block. Normally, the
statements are executed in the order in which they are listed in the program text.
The assignment operator ".=" is used to assign new values to both local and
er

global variables. The old value of the variables is lost when you do this.
In the case of "read" access, the variable always appears on the right of the
assignment operator (":-") in the expression. In the case of write access, the
operand appears on the left of the assignment operator.
ez

Local and global variables can be accessed in both read and write mode. In
other words, the variable can appear both on the immediate right of the
assignment operator ":=" (read access) and on the immediate left of the
assignment operator (write access).
r.s

Constants (VAR CONSTANT) can only be accessed in read mode. In other


words, they are only permitted to appear on the immediate right of the
assignment operator.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 Fundamentals of Structured Text
Types of statement in ST

Value assignments:
• Example: A := B + C;
Expression

Control statements:

om
• IF statement: IF E1 THEN ... ELSIF ... ELSE ... END_IF

• WHILE statement: WHILE Index <= 50 DO ... END_WHILE

l.c
...

Subroutine execution and system functions:


• FC calls:

ai
MyRetVal := test(-2.4);

• System functions: retVal := _pos(axis := myAxis,

SIMOTION
Siemens AG 2013. All rights reserved.
gm
position := 100,
commandId := _getCommandId());

Date:
File:
10.01.2013
MC-SMO-PROG_02.23
SITRAIN Training for
Automation and Drives
@
Value assignments The ".=" assignment operator is used to assign new values to variables. The old
value of the variables is lost when you do this.

Control Control statements are used to modify the sequential order in which statements
er

statements are usually processed.


Conditional statements (IF and CASE statement) are used to make a selection
from various alternatives during program execution.
ez

Loop statements (FOR, WHILE, and REPEAT statement) are used to execute
statements repeatedly.
Jump statements (CONTINUE, EXIT, and GOTO statement) are used to
interrupt the sequential order in which commands are processed and jump to a
point at which the process should be resumed.
r.s

Calls to FC, FB In accordance with the principle of structured programming, other POUs can be
system functions called from within a POU. POUs that can be called are:
• Other functions and function blocks created in ST or in MCC by the user
ne

• Standard functions and standard function blocks provided by the system


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 Fundamentals of Structured Text
Expressions, operators, and operands in ST
Expressions:
• Arithmetic expressions (3 + number_1)*(rad ** 3.7)/3.1
• Relational expressions A >= 9
• Logic expressions (n > 5) AND (n < 20)

Operators

om
• Assignment operator: :=
• Arithmetic operators *, /, MOD, DIV, +, -, **
• Relational operators <, >, <=, >=, =, <>
• Logic operators NOT, AND, XOR, OR

l.c
• Bit sequence operators NOT, AND, XOR, OR

Operands
• Constants 30.0, 1234

ai
• Extended variables %IB5, Status, Motor.Current,
Func(A:=ON)

SIMOTION
• Expression in (...)

Siemens AG 2013. All rights reserved.


gm
((3 + Var_1) * (VAR_2 ** 3.7))

Date:
File:
10.01.2013
MC-SMO-PROG_02.24
SITRAIN Training for
Automation and Drives
@
Expressions Expressions consist of operands, operators, and round brackets. Within an
expression, the operators (e.g. +, -, *, /, etc.), i.e. the active components, are
linked with the passive elements such as constants, variables, and function
values to generate a new value.
er

An expression thus takes the place of the value representing it.


ST supports the generation of standard expressions, i.e. arithmetic, logical, and
relational expressions. Constants or elementary variables or variables from
arrays, structures or return values of functions can be used for generation
ez

purposes.
Expressions consist of operators and operands. Most operators in ST link two
Operators and operands (e.g. A + B) and a re, therefore, known as binary operators. The
operands others just work with a single operand and are, therefore, known as unary
r.s

operators.
The result of an expression can be:

• Assigned to a variable (e.g. A := B + C;)


• Used as a condition for a control statement
ne

(e.g. IF A<g B DO ...)


• Used as actual parameters for calling a function or a function
block (e.g. MyFunc (input := A + B))
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 Fundamentals of Structured Text
Assignments in ST
Assignment to variables
• Elementary data type: Counter := (5 + CountVar) * 2;
• Structures
- Entire structure Struct_1 := Struct_2;

om
- Components Struct_1.comp1 := Struct_2.comp1;

• Arrays
- Entire array Array_1 := Array_2;
- Components Array_1[Index_1] := Array_2[5];

l.c
Access to process image
- Absolute access Value := %IB5; %Q5.2 := TRUE;

ai
- Symbolic: VAR
MyInput AT %IB5 : SINT;
END_VAR

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Value := MyInput;

Date:
File:
10.01.2013
MC-SMO-PROG_02.25
SITRAIN Training for
Automation and Drives
@
Principle Value assignments replace the instantaneous value of a variable with a new
value specified via an expression. This expression can also contain function
(FC) identifiers which are called by the expression and for their part return
corresponding values.
er

The value of an expression assigned to a variable must be compatible with the


type of variable (assignment-compatible).

Value assignments A compound variable represents the entire type (the entire structure, the
ez

with compound entire array) or a component of the compound variable. Therefore, assignments
variables to a compound variable can be made in two ways. You can:
• Assign the content of another complete compound variable (structure, array)
to each compound variable (structure, field).
r.s

An entire array can then only be assigned to another array if both


the data types of the components and the array limits match exactly
• Assign a type-compatible variable, a type-compatible expression, or another
component to each component of the compound variable
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 25 Fundamentals of Structured Text
Access to I/Os and process images
"Absolute identifier" Process image Refresh Input
input PIB0
%I1.3
%IB63 %IB0
BackgroundTask PIB63
%IW0 %IB63 64 bytes PIB64

PIB66
"User-defined Process images PIB67

om
of the inputs
process images" IB0 PIB4095 (C240)
Symbolic only for: Refresh
depending on PIB4095 (P350)
• IPOSynchronousTask IB . . . Any PIB16383 (D4x5)
• TimerInterruptTask selected task
• BackgroundTask

l.c
"Absolute identifier" Process image Output
%Q1.3 output Refresh
PQB0
%QB63 %QB0
%QW0 BackgroundTask PQB63
%QB63 64 bytes PQB64

ai
"User-defined Process images
PQB66
process images" PQB67
of the outputs
Symbolic only for: QB0 Refresh PIB4095 (C240)

SIMOTION
• IPOSynchronousTask
• TimerInterruptTask
• BackgroundTask

Siemens AG 2013. All rights reserved.


QB . . .
gm
Date:
File:
Any

10.01.2013
depending on
selected task

MC-SMO-PROG_02.26
PIB4095 (P350)
PIB16383 (D4x5)

SITRAIN Training for


Automation and Drives
@
Direct With symbolic I/O variables, inputs and outputs can be accessed directly.
I/O access In direct access with I/O variables, the inputs and outputs are updated as
follows:
• For the onboard I/Os of the C2x0, the access cycle clock is 125 µs
er

• For central (SIMOTION D) or isochronous distributed I/Os, updates are


performed in the position control cycle clock, i.e. the inputs are read before
the position controller is called and the outputs are written after the position
controller is called. Non-isochronous I/Os are processed in the IPO cycle
ez

clock.
During the StartupTask, access to the I/O variables is restricted. Otherwise, in
the RUN operating state and in the ShutdownTask, I/O variables can be
accessed without restriction.
r.s

Access via Process images are areas of the RAM in the SIMOTION device in which a
process images subset of the I/O address area is mirrored.
The system automatically mirrors the first 64 bytes of the I/O address area to the
process images of the BackgroundTask. With user-defined process images, the
ne

size depends on the number and size of the I/O variables that have been set up.
The process images of the inputs are updated before the associated task is
called. After processing of the task, the process image output is sent to the I/Os.
The process image is, therefore, consistent for the entire cycle of the associated
task.
ca

Logical To improve the structuring options for input/output addresses in the


address space user program, the quantity structure has been increased:
• C2x0: 4 KB
• P350: 4 KB
• D4x5: 16 KB

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 26 Fundamentals of Structured Text
Access to individual bits with the "Permit language
extensions" compiler option
VAR
MyResult : BOOL;
MyAnyBit : BYTE; // or WORD, DWORD
BitNo : USINT := 5; // Bit number
END_VAR

om
MyResult := _getbit(in:= MyAnyBit, // Read out bit status
n:= BitNo); // Without language extension

MyResult := MyAnyBit.5; // Read out bit status


// With language extension

l.c
MyAnyBit := _setbit(in:= MyAnyBit, // Set bit
n:= BitNo, // Without language extension
value:= TRUE);

MyAnybit.5 := TRUE; // With language extension

ai
MyAnybit := _togglebit(in:= MyAnyBit, // Toggle bit
n:= BitNo); // Without language extension

SIMOTION
MyAnyBit.5 := MyAnyBit.5 XOR TRUE;

Siemens AG 2013. All rights reserved.


gm
Date:
File:
// With language extension

10.01.2013
MC-SMO-PROG_02.27
SITRAIN Training for
Automation and Drives
@
Access to As of SCOUT V4.1 the compiler option "Permit language extension" provides a
individual bits user-friendly means of accessing the individual bits of a BYTE, WORD, or
DWORD data type variable. It enables individual bits in a BYTE, WORD, or
DWORD to be accessed in the same way as in SIMATIC S7. This type of
er

access is very useful in particular if the corresponding BYTE, WORD, or


DWORD was declared in the I/O or in one of the process images.
Generally, the following is valid:
• With standard functions: The standard functions _getBit(), _setBit()
ez

and _toggleBit() support the IEC-compliant reading, writing, and inversion of


any bit in a bit string. You can specify the number of the bit via a variable.
• With direct bit access:
The number of the bit to be accessed can be entered after the name of
r.s

the variable, separated by a period. The variable must be a BYTE, WORD,


or DWORD type variable. In this case, the number of the bit can only be
specified via a constant.
In order to be able to use this option, the "Permit language extensions"
option must be activated in the compiler settings.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 27 Fundamentals of Structured Text
Control statements: IF and CASE

• IF MCC
IF
IF height
height << 55 THEN
THEN
;; //
// Statements
Statements
ELSIF
ELSIF height
height >> minHeight
minHeight THEN
THEN

om
;; // Statements
// Statements
ELSE
ELSE
;; //
// Statements
Statements
END_IF;
END_IF;

l.c
• CASE
CASE
CASE condition
condition OF
OF
1: ; // Statements

ai
1: ; // Statements
2,3:
2,3: ;; //
// Statements
Statements
44 .. 10: ; // Statements
.. 10: ; // Statements

SIMOTION
ELSE
ELSE ;;
END_CASE;
END_CASE;

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.28
SITRAIN Training for
Automation and Drives
@
Principle The problem of having to execute different statements dependent upon certain
conditions is often encountered in programs. This problem is solved with
conditional statements, which branch the execution sequence off into various
subroutines.
er

IF statement The IF statement is a conditional statement . It specifies one or more options


and selects one (or none) of its statements for execution.
The IF statement is processed according to the following rules:
ez

1. If the value of the first expression is TRUE, the statement part after
THEN is executed; otherwise, the expressions are evaluated in the ELSIF
branches.
2. If none of the Boolean expressions in the ELSIF branches is TRUE, the
r.s

sequence of statements after the ELSE is executed (or, if there is no ELSE


branch, no further statements are executed).
Any number of ELSIF statements may be programmed. The ELSIF branches
and/or the ELSE branch may be omitted. This is interpreted in the same way as
if the branches existed with no statements.
ne

CASE branch The CASE statement is used to select 1 of n program parts. The selection is
determined by a selector (an expression evaluated as an INT type variable).
A list of constants is available for selection, a program part being assigned to
each value or group of values.
ca

The CASE statement is processed according to the following rules:


1. The value of the selector is tested during execution of the CASE statement.
If its value is contained in the value list, the program part belonging to
the list is executed.
2. The ELSE branch is optional. It is executed if the value returned by the
selector is not contained in the value list. If the ELSE branch is missing and
no match is found, the program is resumed after END_CASE.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 28 Fundamentals of Structured Text
Control statements: FOR, WHILE, and REPEAT

• FOR
FOR
FOR loop
loop :=
:= 11 TO
TO height
height BY
BY 22 DO
DO
;; // Statements
// Statements
END_FOR;
END_FOR;

om
• WHILE
WHILE
WHILE condition
condition DO
DO
;; //
// Statements
Statements
END_WHILE;
END_WHILE;

l.c
• REPEAT
REPEAT
REPEAT

ai
;; //
// Statements
Statements
condition := n+1;
condition := n+1;
UNTIL
UNTIL condition
condition == 13

SIMOTION
END_REPEAT;
END_REPEAT;

Siemens AG 2013. All rights reserved.


13

gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.29
SITRAIN Training for
Automation and Drives
@
Overview ST and of course MCC provide the control structures FOR, WHILE, and
REPEAT for repeating statement sequences.
er

FOR Loop A FOR statement executes a series of statements in a loop, whereby


incremented values are assigned to a variable (control variable). The control
variable must be a SINT, INT, or DINT type variable.
When the loop is started, the control variable is set to the starting value and
ez

incremented (or reduced for a negative step width) by the specified value with
each loop cycle. The FOR_loop is exited, i.e. execution resumes with the
statement after END_FOR, when the control variable reaches the full-scale
value.
The FOR statement is used whenever a statement sequence is to be looped
r.s

through for a fixed, known number of cycles. If the number of cycles is not
known, use the WHILE or REPEAT statement.

WHILE statement The WHILE statement allows a sequence of statements to be executed


repeatedly under the control of an iteration condition. This execution condition is
ne

formed according to the rules of a logical expression.


The statement part after DO is repeated until the iteration condition has the
value TRUE.
ca

REPEAT statement REPEAT statements repeat statement sequences between REPEAT and UNTIL
until a particular condition is fulfilled and the action is aborted. This abort
condition is formed according to the rules of a logical expression.
The condition is evaluated after every completed execution of the statement
sequence. This means that the sequence is executed at least once, even if the
abort condition has been fulfilled from the start.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 29 Fundamentals of Structured Text
Control statements: EXIT and RETURN

WHILE
WHILE TRUE
TRUE DO
• EXIT DO
;; //
// Statements
Statements
IF
IF %I1.1
%I1.1 == TRUE
TRUE THEN
THEN

om
EXIT;
EXIT;
END_IF;
END_IF;
END_WHILE;
END_WHILE;

l.c
• RETURN FUNCTION
FUNCTION example:
example: VOID
VOID
//
// Statements
Statements
IF
IF %I1.1
%I1.1 == TRUE
TRUE THEN
THEN
RETURN;
RETURN;

ai
END_IF;
END_IF;
END_FUNCTION
END_FUNCTION

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.30
SITRAIN Training for
Automation and Drives
@
EXIT An EXIT statement is used to exit a loop (FOR, WHILE, or REPEAT loop) at any
point regardless of whether or not the abort condition has been fulfilled.
This statement has the effect of jumping directly out of the loop immediately
surrounding the EXIT statement. Program execution is resumed at the end of
er

the repeat loop (e.g. END_FOR, END_WHILE).

RETURN A return statement exits the POU (FB, FC, program) currently being processed
and returns to the calling POU or operating system when a program is exited.
ez

When a function or a function block is terminated, program execution continues


in the higher-level POU after the position where the function or function block
was called.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 30 Fundamentals of Structured Text
Control statements: GOTO and WAITFORCONDITION
• GOTO
LABEL
LABEL //There
//There is
is an
an option
option to
to
MyLabel;
MyLabel; //declare
//declare jump labels
jump labels in-
in-
END_LABEL
END_LABEL //the
//the declaration
declaration part
part
//...
//...

om
IF
IF %I0.0
%I0.0 THEN
THEN
GOTO
GOTO MyLabel;
MyLabel;
END_IF;
END_IF;
test
test :=
:= NumTest;
NumTest;
MyLabel:
MyLabel:
;; //
// Statements
Statements

l.c
• WAITFORCONDITION
//
// Call
Call with
with expression
expression

ai
WAITFORCONDITION
WAITFORCONDITION myExpression
myExpression WITH
WITH TRUE
TRUE DO
DO
//
// Execution
Execution with
with priority,
priority,
//
// at
at least
least one
one statement,
statement, e.g.:
e.g.:
%Q0.0 := TRUE;
%Q0.0 := TRUE;

SIMOTION
END_WAITFORCONDITION;
END_WAITFORCONDITION;
//
// ...
...

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.31
SITRAIN Training for
Automation and Drives
@
GOTO statement The GOTO statement forces a jump to the jump label specified in the command.
Jump statements are programmed with the GOTO command by specifying the
jump label the program is to jump to.
Jumps are only permitted within a POU.
er

WAITFORCONDITION The WAITFORCONDITION command is used to force the program to wait


statement for a specific event or condition in a MotionTask. The command suspends the
task until the condition (expression) is true.
ez

The expression identifier must be a construct declared with EXPRESSION. The


WITH expression sequence is optional. If it is included, the expression
determines whether expression is evaluated only on the rising edge from 0 to 1
(expression = TRUE) or at static 1 (expression = FALSE).
r.s

A negative edge can be scanned with NOT expression identifier. If no WITH


expression is specified, the expression is evaluated statically by default. The
statement part must contain at least one statement.

EXPRESSION An expression is a special type of function declaration with a BOOL data type
ne

return value. When the expression is declared, the data type of the return value
is not specified explicitly.
An expression can only be declared in the implementation section of a unit.
Optionally, local (temporary) variables can be declared. Other declarations (e.g.
input parameters, constants) are not permitted.
ca

The local variables of the expression, unit variables, global device variables, I/O
variables, and the process image can be accessed in the statement section.
In the statement section, a BOOL data type expression must be assigned to the
expression designation. Function calls or loops are not permitted.
The expression is called by the operating system in the IPO cycle clock. If the
return value is "true", the task switches back to the "RUNNING" state.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 31 Fundamentals of Structured Text
Comments in ST

• Line comment
// Can look like this
x := 3;

// A line comment can also

om
// extend over several lines in this
// format. => ASCII character set

• Block comment

l.c
(*
Block comments look like this. They are used
to comment out entire blocks.
####

ai
######
#
*)

SIMOTION
x := 3;

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.32
SITRAIN Training for
Automation and Drives
@
Overview When you write a program, it is important to include comments. They make
programs clearer and more transparent. In SIMOTION, comments can be
included in programs in several ways.
er

Comments In ST programs, you can insert line comments to describe program sections
in ST or command lines, for example.
If a comment extends over several lines, you can use block comments, which
are written in an ST unit specially created for them. You can use block
ez

comments, for example, to include explanations of the task assignments of a


program or to use TOs in the project.

Comments In MCC, you can enter short comments immediately next to a command.
r.s

in MCC Spanning three short lines, they refer, for example, to the addressed inputs,
outputs, axis names, or machine modules.
In addition, you can add a longer comment to each command. Comments in
MCC are indicated by a mark at the command and are included on program
printouts.
ne

MCC also offers a separate comment block that is inserted as a separate


command in the MCC chart and displays the comment text during editing.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 32 Fundamentals of Structured Text
Controlling compilation with the preprocessor
• The preprocessor replaces names in an ST source file, MCC
chart, and LAD/FBD program before the actual compilation takes
place.
• Flexible generation of user programs: assignment of axis
names, etc.

om
e.g. somewhere in an ST source file:
{
#define <identifier> <text>
. . .
}

l.c
// Here the name <identifier> is replaced by the name <text> in
// subsequent lines of the program before the actual compilation
// takes place.

ai
#undefine <identifier>
. . .
}

SIMOTION
// stops here.

Siemens AG 2013. All rights reserved.


gm
// Replacement of the name <identifier> with the name <text>

Date:
File:
10.01.2013
MC-SMO-PROG_02.33
SITRAIN Training for
Automation and Drives
@
Preprocessor The preprocessor prepares an ST source file for compilation. For example,
character strings can be defined as replacement texts for identifiers, or sections
of the source program can be hidden/shown for compilation. This provides a
means of including additional lines of code in a program for supplementary
er

debug information, for example.


The preprocessor can be activated with the following settings:
• Globally, for all projects (via Options -> Settings -> Compiler)
ez

• Locally for an ST source file (ST source file properties dialog)

Controlling the Statements sent to the preprocessor to start or end replacement rules
preprocessor are called pragmas. The preprocessor can be controlled with the following
pragmas.
r.s

• #define: The specified identifier is replaced by the specified text.


• #undef: The replacement rule for the identifier is cancelled.
• #ifdef: For variant formation (conditional compilation). If the specified
identifier is defined, the following program lines (until the next pragma that
ne

contains #else or #endif) are compiled by the compiler.


• #ifndef: For variant formation (conditional compilation). If the specified
identifier is not defined, the following program lines (until the next pragma
that contains #else or #endif) are compiled by the compiler.
• #else For variant formation (conditional compilation). Alternative branch to
ca

#ifdef or #ifndef. The following program lines (until the next pragma
containing #endif) are compiled by the compiler, if the preceding query with
#ifdef or #ifndef was not fulfilled.
• #endif Concludes variant formation with #ifdef or #ifndef.

Note The #define pragma can also be used to replace names in the interface part of
an ST source file, for example. This interface part can then be imported into any
other ST source file, MCC chart, or LAD/FBD program with the USES
statement.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 33 Fundamentals of Structured Text
Example of how to use the preprocessor
INTERFACE
FUNCTION_BLOCK fb1;
VAR_GLOBAL
g_var : INT;
END_VAR
{
#define my_define g_var
#define my_call f(my_define)
}

om
END_INTERFACE
IMPLEMENTATION
FUNCTION f : INT
VAR_INPUT
i : INT;
END_VAR
f := i;
END_FUNCTION
FUNCTION_BLOCK fb1

l.c
VAR_INPUT
i_var : INT;
END_VAR
VAR_OUTPUT
o_var : INT;
END_VAR
my_define := i_var; // After preprocessor: g_var := i_var

ai
{
#undef my_define
}
o_var := my_call +1; // After preprocessor: o_var := f(g_var) + 1;
my_define := i_var; // After preprocessor my_define not replaced.

SIMOTION
END_FUNCTION_BLOCK
END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


gm
// Error message from compiler

Date:
File:
10.01.2013
MC-SMO-PROG_02.34
SITRAIN Training for
Automation and Drives
@
Overview In the interface part of the ST source file shown, after the declaration of the
global variables g_var, the following pragmas:
• #define my_define g_var
• #define my_call f(my_define)
er

are used to start the replacement of the name my_define by g_varand


my_callby f(my_define),, i.e. f(g_var).
Thus the statement:
ez

my_define := i_var;
is replaced by the statement:
g_var := i_var;
and the statement:
o_var := my_call +1;
r.s

by the statement
o_var l:= f(g_var) +1;
After the pragma:g
#undefomy_define
ne

the name my_define is no longer replaced by g_var. As a result, the


statemeent
my_define:= i_var
generates an error message during compilation.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 34 Fundamentals of Structured Text
Testing ST programs

Options for testing ST programs

• Program status

• Symbol browser for monitoring and controlling

om
variables

• Monitor watch table

• Use breakpoints

l.c
• Trace tool

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.35
SITRAIN Training for
Automation and Drives
@
Overview Syntax errors are detected and displayed by the ST compiler during the
compilation procedure. Runtime errors during execution of the program are
indicated by system alarms or cause the system to switch to STOP mode; you
can find program logic errors using the ST test functions, e.g. using the symbol
er

browser and program status.


ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 35 Fundamentals of Structured Text
Operating modes for program testing

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.36
SITRAIN Training for
Automation and Drives
@
Overview Various SIMOTION device modes are available for program testing. How to
select the mode of a SIMOTION device:
1. Highlight the SIMOTION device in the project navigator.
2. Select Test mode from the context menu.
er

3. Select the required mode and confirm with OK.


If you have selected debug mode, you are proempted for further
inputs.
ez

Operating modes The following operating modes are available for selection:
• Process mode: Program execution on the SIMOTION device is optimized for
maximum performance. The following diagnostic functions are available:
- Monitor variables in the symbol browser
r.s

- Program status
- Trace tool with measurement functions for drives and function generator
Only 1 ST source file and 1 trace can be activated in this mode.
• Test mode: The same diagnostic functions are available as for process
ne

mode. Most of the restrictions do not apply.


However, only one ST source file can be monitored per task and 4 traces can be
triggered on each SIMOTION device.
ca

• Debug mode: This mode is available in SIMOTION Kernel as of V3.2.


In addition to the diagnostic functions supported in test mode, you can use the
following functions:
- Breakpoints
Notice No more than one SIMOTION device can be switched to debug mode.

You must observe the appropriate safety regulations. Use the debug mode only with
the life-sign monitoring function activated with a suitably short monitoring time!

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 36 Fundamentals of Structured Text
The "Program status" test function

Program status

Stop Force
monitoring update

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.37
SITRAIN Training for
Automation and Drives
@
Overview With the "Program status" function, you can select a range within the code of an
ST source file to monitor. You can also use this function to monitor local
variables (within a function, for example).
The "Program status" function shows the following variables:
er

• Simple data type variables (INT, REAL, etc.)


• Individual elements of a structure, provided an assignment is made
• Individual elements of an array, provided an assignment is made
ez

• Enumeration data type variables


To make the best use of available buffer capacity and to prevent runtime
falsification, complete fields and structures are not shown.
r.s

Using Program If you are using the "Program status" function, the "Permit program status"
status option must be checked to compile the ST source file in the Properties dialog of
the ST source file.
If you want to monitor more than one ST source file at the same time (up to 4 ST
source files can be monitored at the same time), the Test mode option must be
ne

selected on the "Debug ST" tab (menu: Options -> Settings).


1. Download the program to the target system in the STOP operating state
and then start the target system.
2. Click the "Program status" button to start test mode.
ca

The ST editor window is now divided vertically:


In the left-hand pane of the window, you can continue to edit the ST source
file. The contents of the variables are displayed in the right-hand pane of the
window.
3. In the left-hand pane, click to highlight the start of the monitoring range.
Values that have changed in the current cycle are displayed in red.
Values that have not changed are displayed in black. IF branches are
displayed with question marks and in green.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 37 Fundamentals of Structured Text
Monitoring variables with the symbol browser

om
l.c
Select
unit

ai
Status value
Global variables
of the unit

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.38
SITRAIN Training for
Automation and Drives
@
Overview The symbol browser shows the names, data types, and values of unit variables,
i.e. of global variables that have been declared in the interface or
implementation section of a unit. The contents of the variables can be monitored
and – if necessary – modified (Modify variables function).
er

However, the variable values of a unit can only be viewed or edited with the
symbol browser if the associated program has been downloaded to the target
system and a connection to the target system has been established.
ez

Using the For the following functions, a connection to the target system must be
symbol browser established and the associated program must have been downloaded to the
target system.
1. Select the required ST source file in the project navigator (e.g. ST_1).
r.s

2. Click the "Symbol browser" tab. The declared unit


variables are displayed.
3. To monitor the values of the variables, check the box in the Status value
column for each variable.
4. The following functions can now be selected:
ne

- Click the "Immed. status" button to see a snapshot of the values.


- Click the "Start status" button to periodically update the value of the
variables.
- Click the "Stop status" button to end the update of the variable values
ca

currently in progress.
- Enter a value in the "Control value" column, check the box in this column
and click the "Immediate control" button. The value entered is written to
the variable.

Note The symbol browser can also be used to monitor and control the I/O variables,
global device variables, and static variables of a program (select the execution
system and the task in the symbol browser).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 38 Fundamentals of Structured Text
Monitoring variables in watch table

om
Insert
watch table

l.c
Right mouse

ai
click
Unit/TO
variables

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.39
SITRAIN Training for
Automation and Drives
@
Overview With the symbol browser, you can only monitor variables belonging to one
object (device-, I/O-, and unit-specific) within a project, and with the "Program
status" test function, you can only monitor variables in a user-definable range
within the program.
er

Watch tables, on the other hand, let you monitor selected variables from any
source or object as a group. In offline mode, you can monitor and control the
data type of the variables; in online mode, you can monitor and control their
content.
ez

Watch table To monitor variables using the watch table:


1. In the project navigator, highlight the "Monitor" folder.
2. Select "Insert -> Watch table" to create a watch table; enter a name for the
r.s

table. A watch table with this name is then created in the "Monitor" folder.
3. In the project navigator, click the object (ADDRESS LIST, GLOBAL DEVICE
VARIABLES, unit) containing the variables you want to add to the watch
table. The corresponding table of variables then appears in the symbol
browser.
ne

4. In the table of variables, click the first entry to select the whole row. Right-
click to display the associated context menu and select "Move variable to
watch table".
In the next menu that is displayed, select the corresponding watch table
ca

("Watch table_1" in the example).


5. If you now select the required watch table in the project navigator, the
selected variable is displayed in the watch table.
6. Repeat steps 2 to 5 to add all required variables from the various objects
to the watch table.
7. You can use the symbol browser to monitor and modify the variables in the
watch table.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 39 Fundamentals of Structured Text
New functions in the ST editor (as of V4.2)
Context menu with commands for
„ Copying, pasting, deleting, etc.
„ Changing the view (Display pairs of brackets,
Folding active, Line numbers, etc.)
„ Go to: bookmark, start of block, etc.
„ Some of the commands can also be selected
via the toolbar

om
Support for split window
„ (e.g. so that declaration and code can be
displayed separately)

Sequence generator
„ Generation of simple number sequences

l.c
based on a specific pattern (<Ctrl> <Alt> F7)

Autocomplete
„ Select via <Ctrl> <Space>

ai
Select column Generate Select column Generate
by column sequence by column sequence


<Alt> mouse <Ctrl> <Shift> F7

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
<Alt> mouse

10.01.2013
MC-SMO-PROG_02.40
<Ctrl> <Shift> F7

SITRAIN Training for


Automation and Drives
@
Shortcut menu The ST editor context menu is shown if you right-click in an open ST source file.
Depending on the active application/editor or the mode (ONLINE/OFFLINE),
certain commands are not displayed or cannot be selected.
The context menu contains commands for:
er

• Copying/cutting/pasting/deleting
• Changing the view (show/hide line numbers, folding active, display
pairs of brackets, indent help, split wimndow, etc.)
• Bookmarks (insert/remove bookmaerk, go to bookmark, etc.)
ez

• Selected areas (indent/outdent, upperi /lower case letters, etc.)


• Go to start/end of block, go tos start of block, level 0, level 1, etc.
• Breakpoints (set, remove, activate, deactivate)
r.s

As of V4.2, the ST editor window can be split into two segments, creating two
Splitting the views of the same ST source file so that the declaration and the code can be viewed
editor window at the same time, for example, or different code positions can be compared more
easily.
The split can be activated/deactivated either with the ST source file -> Split
ne

window command or via the context menu. The split itself is not saved when the
source file is closed. ST source files are always opened in an entire window (i.e. one
that is split).
Wkhen the status function is activated, i.e. when the block is being monitored,
the editor window cannot be split.
ca

Sequence generator You can generate simple series of integer numbers (sequences) that follow a
specific pattern in the ST editor. This can be useful, for example, for the
initialization of an array. All the numbers selected in the ST editor are interpreted
as being possible elements. The initial elements from which the series is
calculated must represent integer values.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 40 Fundamentals of Structured Text
Setting breakpoints in ST

Can only be used in


• Programs
• Function blocks
• Functions (as of V4.3)

om
Procedure
1. Select debug mode
2. Specify the "debug task group"

l.c
3. Set breakpoints
4. Specify the call path
5. Activate breakpoints

ai
6. Use "Variable status" to monitor contents of local variables

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.41
SITRAIN Training for
Automation and Drives
@
Overview You can set breakpoints within a POU of a program source (e.g. ST source file,
MCC chart, LAD/FBD program). On reaching an activated breakpoint, the task
in which the POU with the breakpoint is called is stopped. If the breakpoint that
initiated the stopping of the tasks is located in a program or function block, the
er

values of the static variables for this POU are displayed in the "Variable status"
tab of the detail display.
Temporary variables (including in-out parameters for function blocks) are not
displayed. You can monitor static variables of other POUs or unit variables in
ez

the symbol browser.

Preconditions With the ST source file open, proceed as follows:


1. Select debug mode for the relevant SIMOTION device.
r.s

2. Specify the tasks of the "debug task group", i.e. the tasks that are to be
stopped when a breakpoint is reached.
3. Set your breakpoints in the ST source file at lines with statements.
4. Specify the call path.
ne

5. Activate the breakpoints.


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 41 Fundamentals of Structured Text
Specifying the "debug task group"

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.42
SITRAIN Training for
Automation and Drives
@
Overview During program execution, all tasks in the assigned "debug task group" are
stopped when an activated breakpoint is reached.

Procedure Once you have switched the corresponding SIMOTION device to debug mode,
er

you can proceed as follows:


1. Select the required SIMOTION device in the project navigator.
2. Select "Debug task group" from the context menu. The
ez

dialog for specifying the "debug task group" opens.


3. Select the tasks to be stopped on reaching the breakpoint:
− To stop specific individual tasks in the RUN state, assign these tasks
to the "Stopping tasks" list:
r.s

− To stop all tasks, activate the "All tasks" option.


In this case, you can specify whether or not the outputs are to be re-
enabled when the tasks are resumed.

Property Selected tasks All tasks


ne

Operating mode RUN STOP


Stopped tasks Only tasks in the "debug All tasks
task group"
Outputs Active Inactive
ca

Cycle monitoring Inactive Inactive


Axis technology Axes in position control No position control

Note The "debug task group" can only be changed if no breakpoints are active.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 42 Fundamentals of Structured Text
Setting breakpoints in an ST source file

1. Place the cursor


on a line with statements

2. Set

om
breakpoints

l.c
Inactive
breakpoint

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.43
SITRAIN Training for
Automation and Drives
@
Setting Breakpoints can only be set in an ST source file if the following conditions
breakpoints are met:
• The ST source file is open
• The required SIMOTION device has been switched to debug mode
er

• The "debug task group" has been specified


To set breakpoints, proceed as follows:
1. Place the cursor on a line in the ST source file that contains a statement.
ez

2. Click the "set/remove breakpoint" icon on the "breakpoint" toolbar


(keyboard shortcut: Ctrl+H). A breakpoint that has
been set can be removed by clicking the "set/remove breakpoint" icon.
An inactive breakpoint is displayed as an unfilled circle at the start of a line.
r.s

Note You can use other diagnostic functions such as "Status program" and the
"Breakpoints" function together in one ST source file. However, the line
highlighted in the ST source file for program testing must not contain a
breakpoint.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 43 Fundamentals of Structured Text
Specifying the call path

om
Edit
call path

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.44
SITRAIN Training for
Automation and Drives
@
Specifying the Once you have set the breakpoint in the ST source file, you can specify the
call path call path for the breakpoints. Proceed as follows:
1. Place the cursor on a line in the ST source file at which a breakpoint is set.
er

2. Click the "Edit call path" button on the "Breakpoints" toolbar. In the "Call
path/Breakpoint" window, the selected code position is displayed (with the
name of the ST source file, line number, name of the POU).
3. If the code position is called from several tasks:
ez

- Select the required task. The task must be in the debug task group.
4. Select the code position to be called (in the calling POU). The following
options are available for selection:
- The calling code positions within the selected task (with the name of the
r.s

program source, line number, name of the POU)


If the selected calling code position is in turn called by several code
positions, further lines are displayed in which you proceed similarly.
- All:
ne

All displayed code positions are selected. Moreover, all code positions
(up to the top level of the hierarchy) are selected from which the
displayed code positions are called.
5. If the breakpoint is only to be activated after the code position has been
reached several times, select the number of times.
ca

Note You can view the call path associated with the selected task with the "Display
call stack" function. Place the cursor on the line of the ST source file with the
breakpoint and click the "Display call stack" button.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 44 Fundamentals of Structured Text
Activating breakpoints in the ST source file

Continue

Activate
breakpoint
Debug

om
Activate/deactivate table
all breakpoints

Debug table

l.c
Active
breakpoints

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.45
SITRAIN Training for
Automation and Drives
@
Activating Breakpoints must be activated if they are to have an effect on program
breakpoints execution.
To activate/deactivate a single breakpoint, proceed as follows:
er

1. Place the cursor on a line of the ST source file at which a breakpoint is set.
2. Click the "Activate/deactivate breakpoints" button on the "Breakpoints"
toolbar (keyboard shortcut F4).
To deactivate a breakpoint click the "Activate/deactivate breakpoint" button
ez

again.
To activate/deactivate all breakpoints, proceed as follows:
1. Click the "Activate all breakpoints" button on the "Breakpoints" toolbar.
2. To deactivate all breakpoints, click the "Deactivate all breakpoints" button
r.s

again.
On reaching an activated breakpoint, the tasks that are assigned to the debug
task group are stopped.
ne

Continuing the Click the "Continue" button on the "Breakpoints" toolbar


program (keyboard shortcut: Ctrl+F8).

Note Breakpoints can also be activated and deactivated in the debug table. Select the
SIMOTION device in the project navigator and select the "Debug table" context
ca

menu.
In the window that opens, execute the action below, depending on which
breakpoints you wish to activate or deactivate:
• Single breakpoints: Check or clear the corresponding checkbox.
• All breakpoints: Click the corresponding button.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 45 Fundamentals of Structured Text
Monitoring variables at a breakpoint

Call- Stack
anzeigen

Execution has reached

om
breakpoint, this statement
has not yet been processed

l.c
Call- Stack

ai
Variable status

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.46
SITRAIN Training for
Automation and Drives
@
Monitoring The instantaneous content of the local variables can be monitored on the
variables "Variable status" tab in the detail window.

Program call For a program call, the following variables are displayed:
er

• Static variables (VAR)


No variables can be monitored for an FCm call.
FC call
In the case of an FB instance call, thee instance data can be
ez

monitored.
FB call
• Input parameters (VAR_INPUT)
• Output parameters (VAR_ OUTPUT)
• Static variables (VAR)
r.s

Temporary variables (VAR_TEMP) and in-out parameters (VAR_IN_OUT) are


not displayed.

The instantleous values of global "unit variables" must be monitored via the
ne

Note
"symbol browser window".
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 46 Fundamentals of Structured Text
Use "break points" and "Program status" simultaneously
Program staus

om
Program execution
stops at breakpoint

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.47
Status Variable

SITRAIN Training for


Automation and Drives
@
Note The functionality "Program status" and "break point" could be activated
simultaneously. This possibility could be used to test the processing of individual
instructions within a loop.
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 47 Fundamentals of Structured Text
Recording variables with the trace tool
Device trace System trace
(new as of V4.2)

om
l.c
ai
Signal selection for trace

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.48
SITRAIN Training for
Automation and Drives
@
Device trace With the "device trace", you can record and save signal charts of inputs and
outputs and the contents of variables in a SIMOTION or SINAMICS device. The
tool is used, for example, for implementing and documenting the optimization of
axes.
er

You can set the trace length, select the traced variables, define trigger
conditions, parameterize offsets, and switch between different graph types and
scales.
The device trace can be called via the menu command: Target system -> Trace.
ez

The only available description of the trace tool appears in the online help.

System trace As of V4.2, a system trace is also supported. It can be used to record up to
(new as of V4.2) 128 signals from multiple SIMOTION controllers networked via PROFINET IO
r.s

with IRT with chronological synchronism.


The same trigger criteria as for individual device traces are available, e.g.
overshooting of a specific threshold value of a variable. This is detected on the
relevant CPU and recording starts on all configured devices. Once recording is
complete, the data can be analyzed graphically in order to identify potential for
ne

optimization or locate malfunctions quickly.


In complex systems such as printing presses with multiple modular controllers
and synchronous operation across all devices in particular, this significantly
reduces commissioning times and also service requirements.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 48 Fundamentals of Structured Text
Diagnostics with the TO trace
Select TO trace (new as of V4.2)
device

om
Event selection for TO Recorded data
trace for TO trace

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_02.49
SITRAIN Training for
Automation and Drives
@
TO trace In SIMOTION, technology objects can be affected by changes to configuration
data and system variables, or by commands during runtime. The TO trace (a
new function as of V4.2) maps how a technology object is affected by these
changes and commands.
er

It can be used to record and display the last n actions affecting a technology
object in chronological order.
The TO trace is used for TO diagnostics and provides information in a snapshot.
It is TO-specific, i.e. it has to be confirmed individually for each technology
ez

object.

It records commands as well as configuration data and system variable access


with their command status and error status. Once the results recorded have
been read out, they are listed in a table. Each one is time-stamped.
r.s

Call
There are three ways of calling the TO trace. With the device selected, the TO
trace can be called either with the menu command Target system ->
Technology object trace or by selecting the corresponding command from the
device context menu. The third option is to use the corresponding button on the
ne

toolbar.
Parameterization All the technoology objects created in the project are displayed under the
"Technology objects" setting.
ca

To select a line, click any cell within it. The settings for a line are displayed
under the technology objects. The settings for a TO can be changed using the
button on the left.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 49 Fundamentals of Structured Text
Functions and function blocks in SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Blocks for structured programming .................................................................................................. 2
Properties of functions ...................................................................................................................... 3
er

Definition of a function in an ST source file ....................................................................................... 4


Declaration part of a function ............................................................................................................ 5
Statement part of a function .............................................................................................................. 6
ez

Calling user functions ....................................................................................................................... 7


Short form of function calls ............................................................................................................... 8
ARRAYs with dynamic lengths (new as of V4.2) ............................................................................... 9
Properties of function blocks ............................................................................................................ 10
r.s

Definition of a function block in an ST source file .............................................................................. 11


Declaration part of a function block ................................................................................................... 12
Parameters in function blocks ........................................................................................................... 13
Statement part of a function block .................................................................................................... 14
ne

Instantiation of function blocks .......................................................................................................... 15


IEC-compliant call of FB instances in ST .......................................................................................... 16
Call options with the compiler option "Permit language extension" .................................................... 17
Forward declarations in ST (new as of V4.2) .................................................................................... 18
ca

Command library in SIMOTION SCOUT ........................................................................................... 19


Standard functions in SIMOTION ...................................................................................................... 20
Standard function blocks in SIMOTION ............................................................................................ 21
Access to technology objects via TO data types ............................................................................... 22
Example TO access ......................................................................................................................... 23
Transformation and checking of TO data types ................................................................................. 24

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 Functions and function blocks
Blocks for structured programming
Cyclic task
Modularization of the
complete task: Motor 1 Controller
Motor 1 Controller
. . .
• Sub-tasks are solved in
separate blocks
• Parameterization makes Limit
Valves Copy
value

om
for flexibility of application Valves

• Example: Drilling cycle


with parameterizable depth BackgroundTask Motor_1
Name. Type Data type
Start VAR_INPUT BOOL
Stop VAR_INPUT BOOL
Reusability of blocks .

l.c
ON VAR_OUTPUT BOOL
.
(libraries): .
.
.
• Blocks can be called an Motor_1(
Start :=%I0.0,
unlimited number of times Stop :=%I0.1);

ai
ON := Start AND NOT _Stop;
• Restrictions: %Q4.0:=Motor_1.ON;
• No access to global
operands

SIMOTION
• Communication only via
parameter list

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.2
SITRAIN Training for
Automation and Drives
@
Modularization Abstraction is the basis for solving complex tasks by focusing on the essential
of tasks aspects of a task in each abstraction level and ignoring irrelevant details. Using
abstraction, you can divide complex tasks into smaller sub-tasks, each of which
can be solved individually.
er

SIMOTION supports this concept of modularization with its block model. Blocks
Structured are assigned to the sub-tasks that are isolated when the complete task is
programming divided into smaller components. These blocks contain the necessary algorithms
and data for solving the sub-task.
ez

SIMOTION blocks such as functions (eFC) and function blocks (FB) are
parameterizable - they allow you to implement the concepts of structured
programming. This means:
• Blocks for solving sub-tasks implement their own data management
r.s

using local variables


• Blocks communicate with the "outside world", i.e. with the sensors
and actuators of process control or with other blocks in the user program
solely via their block parameters. There must be no access to global
ne

operands in the statement part of blocks


Structured programming offers the following benefits:
Benefits
• Blocks for sub-tasks can be created and tested/debugged independently
ca

of one another
• Parameters can make the blocks flexible. For example, you can create a
drilling cycle where the coordinates and depth of the drill hole are passed as
parameters
• Blocks can be called any number of times at different locations with different
parameter sets, i.e. can be reused to suit your requirements
• "Reusable" blocks for special tasks can be provided in precompiled libraries

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Functions and function blocks
Properties of functions
Parmeterizable blocks:
• Any number of input parameters
• Any number of in-out FUNCTION Add: REAL
parameters OP_1 VAR_INPUT REAL
Program
• No memory, temporary OP_2 VAR_INOUT REAL

om
execution ...
variables only
• Only one output parameter Result := Add(
RET_VAL OP_1 := Value_1
OP_2 := Value_2,
• Avoid access to global ); ...
variables and absolute Add := OP_1 + OP_2;

l.c
operands
END_FUNCTION
• Return an identical result
with the same input
parameters

ai
Expand the command set of the
processor

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.3
SITRAIN Training for
Automation and Drives
@
General Functions represent parameterizable blocks without memory. In SIMOTION, functions
can have any number of input parameters, but they should only return one result in
the return value.
A calling block (a program, for example), can transfer input values to a function via
er

input parameters. The input values (actual values) are evaluated by the function and
the result is transferred to the calling block via the return value. If multiple items of
individual information are to be returned, then a corresponding data structure must be
declared as the return value.
ez

Similarly, a calling block can transfer information to the function called via in-out
parameters. Unlike input parameters, in-out parameters are also able to send back
results to the calling block.
r.s

Functions do not have a "memory". There is no autonomous, permanent data area


within an FC for long-term storage of results. Therefore, a function cannot "remember"
information from one call to another. Intermediate results (e.g. the initial results when
a function is being executed) can, however, be saved in temporary variables and
ne

used for processing in later sections of the function.


Application
In a classical sense, functions expand the processor's command set.
In cyclic tasks, functions are mainly used for implementing complex algorithms and
calculations . Results can be returned to the calling blocks via the return value (e.g.
ca

mathematical functions, etc.).


Within MotionTasks there is usually no need to retain information from one task call to
the next. In this case, therefore, differentiation between functions and function blocks
only plays a subordinate role -at least in terms of "memory".

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Functions and function blocks
Definition of a function in an ST source file
UNIT . . .
INTERFACE
• Type declarations for parameters
TYPE
MeasValType: ARRAY[1..10] OF LREAL; and return value must be made
SumMeanType : STRUCT externally:
Sum : LREAL; • INTERFACE part
Mean : LREAL; for functions which are also called

om
END_STRUCT; by blocks belonging to
END_TYPE
other units)
FUNCTION MyFC;
• IMPLEMENTATION part
END_INTERFACE (for functions that are only used
within the unit)
IMPLEMENTATION

l.c
FUNCTION MyFC: SumMeanType • Function name + data type of the
VAR_INPUT return value (or VOID)
MeasVal: MeasValType;
. . . • Type, parameter, and variable
END_VAR declarations

ai
VAR_INOUT
. . . • Statement part
END_VAR
; • Assignment of the return value

SIMOTION
MyFC := . . .;
END_FUNCTION
END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.4
SITRAIN Training for
Automation and Drives
@
General A function (FC) is defined in the implementation part of an ST source file. If you
want the function to be called also by blocks belonging to other ST units, you
need to list it in the interface section of the ST source file too.
If the function is only used within the defined unit, it only needs to be declared in
er

the implementation part. However, the FC must be defined before the blocks
(program, FB, FC) in which it is called.

Defining a function A function is defined via the keyword FUNCTION in the implementation part of
ez

an ST unit. FUNCTION must be followed by an identifier (the FC name) and


the data type of the return value. If you do not want the function to return a
return value, VOID must be specified as the data type. This is then followed by:
• The optional declaration part
r.s

• The statement part


• The keyword END_FUNCTION

Declarations for The operands of a function include input/in-out parameters (formal parameters)
input/in-out which are also visible from "outside". A block which calls a function must supply
ne

parameters and the input/in-out parameters with actual operands of the same data type the
return value function is called. Similar to the procedure with input/in-out parameters, the return
value of a function must be returned to the calling block upon completion of
function execution.
Blocks which call functions must, therefore, know about the syntax of the data
ca

types for the function's input parameters and return value. If custom data types
such as structures are used for the function's input parameters and/or return
value, their type (TYPE ... END_TYPE) must be declared outside the function.
If a function is to be called by blocks belonging to other ST units, the data type
for the input parameters and return value must be declared in the interface part of
the ST source file. If the functions are only used internally, declaration in the
implementation part is sufficient.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Functions and function blocks
Declaration part of a function
FUNCTION MyFC : SumMeanType • Function name + data type of the
return value
TYPE Value : (SUM, MEAN_VALUE);
END_TYPE • Type declarations for internal
data types
VAR_INPUT
Measurement: MeasVal;
NumMeasurements: INT := 10; • Parameter declarations:

om
END_VAR • VAR_INPUT (input parameters)
VAR_IN_OUT • VAR_INOUT (in-out parameters)
. . .
END_VAR • Variable declarations:
VAR • VAR (temporary variables)

l.c
IntermSum: REAL; • VAR CONSTANT (constants)
Index: INT := 0;
END_VAR
• Input parameters and variables can
VAR CONSTANT be initialized
Pi: REAL := 3.14;

ai
END_VAR • In-out parameters cannot be
initialized
MyFC := ...;
• Assignment of the return value

SIMOTION
END_FUNCTION

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.5
SITRAIN Training for
Automation and Drives
@
Declaration part The declaration part of a function is subdivided into various blocks, each of which is
identified by a separate pair of keywords.

User-defined Custom data types can be declared in a function. Unlike the declarations in the
er

data types interface or implementation part, the data types declared here can only be used
internally.

Input parameters (formal parameter) are some of the local operands of a function.
Input parameters The formal input parameters (name and data type) of a function are declared within
ez

the block VAR_INPUT ... END_VAR. The values of the actual operands can be
accessed within the function in the statement part under the names of the input
parameters .

The formal in-out parameters of a function (name and data type) are declared within
r.s

In-out the block VAR_IN_OUT ... END_VAR.


parameters
Local variables are variables which are declared within the block and can only be
Local variables used within the statement part of the block. All local variables (VAR ... END_VAR)
are temporary in functions, i.e. the value stored in the variable is not retained opon
ne

completion of the function. The next time the function is called, all variables are
reinitialized.

A local variable cannot be read or written by the calling block.


ca

Input parameters and local variables of a function can be initialized during


Initialization declaration. Input parameters with initialization values do not need values to be
passed when the function is called (optional parameters).
In-out parameters cannot be initialized with values. All in-out parameters need
values to be passed when calling with actual operands.
When a function is called, local variables are supplied with the initialization value. If
no initialization value is declared for a variable, it is assigned "0" by default.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Functions and function blocks
Statement part of a function
Function MeanValue: REAL

VAR_INPUT
Meas_val_1 : REAL;
Meas_val_2 : REAL;
Meas_val_3 : REAL;
END_VAR
Write

om
access VAR
IntermResult: REAL; Read access
END_VAR
;
;
;

l.c
IntermResult := Meas_val_1 + Meas_val_2;
Assignment of
the function IntermResult := IntermResult + Meas_val_3;
return value

ai
MeanValue := IntermResult / 3;

END_FUNCTION

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.6
SITRAIN Training for
Automation and Drives
@
Statement part The actual calculation is performed within the statement part. You can use the
same syntax to access the input/in-out parameters and local variables of a
function.
In the case of "read" access, the operand always appears to the right of the
er

assignment operator (":=") in the expression. In the case of write access, the
operand appears on the left of the assignment operator.
Local variables and in-out parameters of a function can be accessed in both
read and write mode. In other words, the variable/in-out parameter can appear
ez

both on the immediate right of the assignment operator ":=" (read access) and
on the immediate left of the assignment operator (write access).
Just like constants (VAR CONSTANT), the input parameters of a function can
only be accessed in read mode. In other words, they are only permitted to
r.s

appear on the immediate right of the assignment operator.

Return value The purpose of the function's return value is to return the result of its execution
to the calling block. The return value is assigned by assigning the required result
to the "function name".
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Functions and function blocks
Calling user functions

PROGRAM Main

VAR
myMeasVal: REAL := 5;
myRetVal: REAL; Function
END_VAR name

om
Return myMeasVal:= 25.3; Actual parameters
value of the FC call

myRetVal:= MeanValue(
Meas_val_1 := 3.5, Parameter list

l.c
Meas_val_2 := myMeasVal,
Meas_val_3 := 5.35 );

ai
.
. Formal input
.
parameters

SIMOTION
Siemens AG 2013. All rights reserved.
END_PROGRAM

gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.7
of the FC

SITRAIN Training for


Automation and Drives
@
Calling functions A function can be called in the calling block via its function name. An associated
actual operand must be specified for each input parameter which has not been
initialized. The parameters are generally specified by means of value
assignment. The different parameters of the function are separated by commas
er

(parameter list). The parameters can be listed in any sequence.


This value assignment assigns an operand (actual parameter) to the input/in-out
parameter which was declared in the declaration part of the called block (formal
parameter).
ez

The following also applies to function calls:


• When called, the function must be written on the right as an operand in an
expression (exception: return value of VOID data type)
• The function returns the return value when called – like an output parameter
r.s

– directly to the variable written on the left in the expression


If VOID is specified as the data type for the return value, assignment is neither
possible nor necessary; with other data types, the return value must always be
assigned to a variable.
ne

Parameter passing When functions are called, data exchange takes place between the calling block
and the called block. The parameters to be transferred must be specified in the
parameter list in the call.
The formal parameters are then replaced by actual parameters during function
ca

execution. This creates a mechanism for information exchange between the


calling block and the called function.
Formal input/in-out parameters adopt the current input values (data flow from
external to internal). Results are returned in the return value of the function or in
the in-out parameters (data flow from internal to external).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Functions and function blocks
Short form of function calls

PROGRAM Main

VAR
_MccRetDINT: DINT;
myByte: BYTE;
END_VAR

om
Function
name _starttask(MotionTask_1);

_MccRetDINT := _enableAxis(
Leading axis,
ALL, Actual parameters
ACTIVE,
of the FC call

l.c
Return INACTIVE,
WHEN_COMMAND_DONE, (parameter list)
value _getCommandId(),
INACTIVE);

myByte := ROL(myByte,1);

ai
SIMOTION
Siemens AG 2013. All rights reserved.
.
.
END_PROGRAM
gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.8
SITRAIN Training for
Automation and Drives
@
Short form of a As an exception, when some functions are called, it is necessary to use the
FC call short form of parameter transfer if this is explicitly requested by the
documentation. This is the case, for example, for all task control commands
(see Chapter 5). The short form of the system function call must also be used
er

for some system functions (see documentation on technology objects (TO)).


With the short form of parameter transfer, the formal parameters (parameter
identifiers) are omitted and only the actual parameters (parameter values) are
specified. In this case it is mandatory to specify the actual parameters in the
ez

correct sequence.
Generally it is possible to use the short form of parameter transfer with all
system functions. However, for reasons of transparency and flexibility, it is
advisable to always use the long form with value assignment as described on
the previous page.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Functions and function blocks
ARRAYs with dynamic lengths (new as of V4.2)
For in-out parameters in
FCs and FBs:
FUNCTION MeanValue : LREAL
• More flexibility when VAR_IN_OUT
transferring arrays MeasVal : ARRAY [..] OF LREAL;
END_VAR
• Declaration without

om
specification of limits for VAR
i : DINT;
index, e.g. IntermSum : LREAL;
END_VAR
ArrayName : ARRAY[…] OF TypeName
• Access to length and limits of FOR i := _firstIndexOf(in := MeasVal) TO
_lastIndexOf(in := MeasVal) DO
array via: IntermSum := IntermSum + MeasVal[i];

l.c
END_FOR;
_firstIndexOf(in := ArrayName) MeanValue := IntermSum/_lengthIndexOf(in:= MeasVal);
_lastIndexOf(in := ArrayName) END_FUNCTION
_lengthIndexOf(in := ArrayName)
Return value type is DINT

ai
• Access to occupied memory
via:

SIMOTION
_sizeOf(in := ArrayName)

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.9
SITRAIN Training for
Automation and Drives
@
Overview As of SIMOTION Kernel Version 4.2, you can use arrays with a dynamic length
in functions and function blocks. Declaration is only possible in the relevant
parameter block for in-out parameters (VAR_IN_OUT/END_VAR).
er

Evaluation When the function or an instance of the function block is called, arrays of any
length of the declared data type can be transferred. In this case, both the
reference (pointer) to the array specified in the actual parameter and the index
limits are included when the parameters are transferred.
ez

Within the function or function block, you can use the following functions to
access the index limits transferred additionally:
• _firstIndexOf (in := ArrayName)
Returns the lower index limit of the array transferred
r.s

• _lastIndexOf (in := ArrayName)


Returns the upper index limit of the array transferred
• _lengthIndexOf(in := ArrayName)
Returns the number of elements of the ARRAY. The following applies:
ne

_lengthIndexOf (x) := _lastIndexOf (x) -_firstIndexOf (x) + 1.


The size of the memory occupied by the ARRAY can be determined with the
following function:
• _sizeOf (in := ArrayName)
ca

This function is executed at runtime for dynamic arrays.


The following also applies:
_sizeOf (in := ArrayType) :=
_lengthIndexOf (in := ArrayType) * _sizeOf (in := type)

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Functions and function blocks
Properties of function blocks
Parmeterizable blocks: Drive
• Conforms to IEC 61131-3 VAR
• Any number of input, output, Motor_1: Motor; FUNCTION_BLOCK: Motor
and in-out parameters END_VAR
Start VAR_INPUT BOOL
• With memory, i.e. not just Stop VAR_INPUT BOOL

om
temporary but also Program M_on VAR_OUTPUT BOOL
Speed VAR_OUTPUT INT
static variables execution
...
• Call with separate data area ...
(instantiation) Motor_1(
• "Data encapsulation" Start :=%I0.0,
...
Stop :=%I0.1);

l.c
M_on := Start AND NOT Stop;
Application (in %Q8.0 := Motor_1.M_on; ...
%QW2 := Motor_1.Speed;
cyclic tasks):
END_FUNCTION_BLOCK
• Timer and counter functions

ai
• Actuating process units with
internal states

SIMOTION
• Furnaces, drives,
valves, etc.

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.10
SITRAIN Training for
Automation and Drives
@
Overview Function blocks (FB) are blocks belonging to the user program. They represent
code blocks with memory as defined in IEC 61131-3. In principle, they can be
called by other programs, function blocks, and functions.
Function blocks can have any number of input, output, and in-out parameters as
er

well as static and temporary variables.


Unlike functions, function blocks are instantiated, i.e. each function block is
assigned a separate data area where it can store, for example, process states
from one call to the next.
ez

"Memory" The programmer can declare static variables in the declaration part of a function
block, where the function block can store information which is retained from one
call to the next.
r.s

This possibility to store information from call to call is one of the features that
differentiates a function block from a function.

Application Using this "memory", a function block can implement timer or counter functions,
for example, or actuate process units such as machining stations, drives,
ne

furnaces, etc.
In cyclic runtime environments such as TimerInterruptTasks and
BackgroundTask, function blocks are particularly suitable for actuating process
units which have responses that depend on internal states, such as machining
step, speed, temperature, etc., in addition to external influences.
ca

When actuating such units, in general the internal states of the process unit are
mapped to the static variables of the function block.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Functions and function blocks
Definition of a function block in an ST source file
UNIT myUnit
INTERFACE
• Types for input, output, and in-out
USEPACKAGE CAM;
parameters must be declared
TYPE
PosSpeedType : STRUCT
outside the function block:
Position : LREAL; • INTERFACE part
Speed : LREAL; (for function blocks which are also

om
END_STRUCT; called by blocks stored in other
END_TYPE units)
FUNCTION_BLOCK Motor; • IMPLEMENTATION part
END_INTERFACE (for function blocks which are only
used within the unit)
IMPLEMENTATION

l.c
FUNCTION_BLOCK Motor • FB name
VAR_INPUT
Execute: BOOL; • Type, parameter and variable
MyPosSpeed: PosSpeedType; declarations
END_VAR

ai
;
;
;
• Statement part

SIMOTION
END_FUNCTION_BLOCK

END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.11
SITRAIN Training for
Automation and Drives
@
General A function block (FB) is defined in the implementation part of an ST source file. If
you want the FB to be called also by blocks belonging to other ST units, you need
to list it in the interface section of the ST source file too.
If the FB is only used within the defined unit, it only needs to be declared in the
er

implementation part. However, the FB must be defined before the blocks


(program, FB, or FC) in which it is instantiated and called.

Defining An FB is defined via the keyword FUNCTION_BLOCK in the implementation part


ez

function blocks of an ST unit. FUNCTION_BLOCeK must be followed by an identifier (the FB


name). This is then followed by:

• The optional declaration part


• The statement part
r.s

• The END_FUNCTION_BLOCK keyword

Data types for The operands of a function block include input, output, and in-out parameters
input, output, and (formal parameters) which are also visible from "outside". A block which calls
in-out parameters this function block must supply the input and in-out parameters with actual
ne

operands when the FB is called. It also has to clear the output parameters after
execution of the function block.

Blocksel which call functions must, therefore, know about the syntax of the data
types for the function's input, output, and in-out parameters. If custom data types
ca

such as structures are used for these parameters, their type (TYPE ...
END_TYPE) must be declared outside the function block.

If a function block is to be called by blocks belonging to other ST units, the data


type for the input, output, and in-out parameters must be declared in the
interface part of the ST source file. If the functions blocks are only used
internally, declaration in the implementation part is sufficient.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 Functions and function blocks
Declaration part of a function block
FUNCTION_BLOCK Motor • FB name
TYPE StateType: (UP,DOWN);
END_TYPE • Type declarations for data types
VAR_INPUT used internally
Start: BOOL;
Stop: BOOL;
Speed: INT;
• Parameter declarations:
• VAR_INPUT (input parameters)

om
END_VAR
VAR_OUTPUT • VAR_OUTPUT (output parameters)
Motor_ON: BOOL;
Setpoint: INT;
• VAR_IN_OUT (in-out parameters)
END_VAR
VAR_IN_OUT
• Variable declarations:
E_STOP: BOOL; • VAR (static variables)

l.c
END_VAR
• VAR_TEMP (temporary variables)
VAR
AxisPos: LREAL := 50.0; • VAR CONSTANT (constants)
END_VAR
VAR_TEMP
• Input parameters output parameters,

ai
IntermPos: LREAL;
END_VAR and all variables can be initialized
VAR CONSTANT
Pi: REAL := 3.14; • In-out parameters cannot be

SIMOTION
END_VAR
;
END_FUNCTION_BLOCK

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
initialized

MC-SMO-PRG_03.12
SITRAIN Training for
Automation and Drives
@
Declaration part The declaration part of a function block is subdivided into various blocks, each of
which is identified by a separate pair of keywords. Each block is given a
declaration list for data of the same kind, e.g. local type declarations, input,
output, and in-out parameters as well as static and temporary variables and
er

constants. Each type of block may only appear once; the blocks may appear in
any order.

User-defined Custom data types can be declared in functions - just like in any other POU.
ez

data types Unlike declarations in the interface or implementation part, the data types
declared here can only be used internally, i.e. only for declaring local variables
or constants.

Input, output, and Input parameters (formal parameters) are some of the local operands of a
r.s

in-out parameters function. The formal parameters (name and data type) of an FB are declared
within the block VAR_INPUT ... END_VAR. The values of the actual operands
can be accessed within the FB in the statement part under the names of the
parameters.
ne

Static variables Static variables are variables which are declared within the block and can only
be used within the statement part of the block.
The local variables (VAR ... END_VAR) are static in FBs, i.e. the value stored in
the variable is retained. The next time the FB is called, the stored values can be
ca

accessed again.

Temporary All local variables (VAR_TEMP ... END_VAR) are temporary in FBs, i.e. the
variables value stored in the variable is not retained after completion of the FB. The next
time the FB is called, all temporary variables are reinitialized.

Initialization Input and output parameters as well as all local variables of an FB can be
initialized during declaration. In-out parameters cannot be initialized.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 Functions and function blocks
Parameters in function blocks

Parameters are the channels Name Var.type Data type Initial value
for information transfer: Start VAR_INPUT BOOL FALSE
Stop VAR_INPUT BOOL TRUE
• Input parameter: Speed VAR_INPUT INT 50
Caller -> Block Motor_ON VAR_OUTPUT BOOL FALSE
• Output parameter: Setpoint VAR_OUTPUT INT 10

om
Block -> Caller E_STOP VAR_IN_OUT BOOL
... VAR ... ... ...
• In-out parameter:
... VAR_TEMP .. ... ...
Caller <-> Block

Parameters are the block's Motor_1

l.c
"envelope":: Motor
EN ENO
• Parameters are like "local"
Start Output
variables in the statement part Input Motor_ON
Stop para-

ai
• The call interface is language- parameters Setpoint meters
Speed
neutral
• Different languages In-out
E_STOP

SIMOTION
can be mixed

Siemens AG 2013. All rights reserved.


parameter

gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.13
SITRAIN Training for
Automation and Drives
@
Overview Parameters are channels for information transfer between the block calling and
the block called. The symbolic names, data types, and if applicable the initial
values of the parameters are defined in the declaration part.
er

Declaration type The type of the parameter indicates the direction of data transfer:
VAR_INPUT Input parameters (FB): For transferring information from the calling block to the
called block. Within the called block, only read access is permitted to input
parameters.
ez

VAR_OUTPUT Output parameters (FB, FC): For transferring information (results) from the
called block to the calling block.
VAR_IN_OUT In-out parameters (FB, FC): In-out parameters are for transferring information in
both directions. Both read and write access is possible to input/output
r.s

parameters.

Parameter transfer When the FBs are instantiated, a memory cell is provided in the instance data
area for each input parameter and output parameter of the function block. This
memory cell is used for storing the actual operand. In-out parameters are only
ne

provided with a memory cell to store the pointer to the actual operand.
When the FB instance is called (in LAD, FBD) the actual operands of the input
parameters are copied to the respective memory cells of the FB instance area.
Similarly, after the block is called (at least in LAD and FBD) the values of the
output parameters are copied to the actual operands created (transfer "by
ca

value"). If an input parameter or output parameter is still without a value when


the block is called, no copy process is carried out. The initialization values are
then used for processing within the FB.
With in-out parameters, a pointer is copied to the actual operand in the reserved
memory cell instead of the value of the actual operand (transfer "by reference").
To avoid working in the FB statement part with "uninitialized" pointers, when the
FB is called, the in-out parameters have to be supplied with variables as actual
operands.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 Functions and function blocks
Statement part of a function block
FUNCTION_BLOCK Motor
VAR_INPUT Restrictions with access to
Start: BOOL;
Stop: BOOL; parameters and variables
Speed: INT;
END_VAR
• Read-only access to input
VAR_OUTPUT
parameters
Motor_ON: BOOL := FALSE;

om
Setpoint: INT;
• Read and write access to
END_VAR output and in-out parameters
VAR_IN_OUT
E_STOP: BOOL;
• Read and write access for all local
END_VAR variables (VAR and VAR_TEMP)
VAR_TEMP • Read-only access to constants
MotorOnAux : BOOL;

l.c
END_VAR (VAR CONSTANT)
MotorOnAux := Start AND NOT Stop;
Motor_ON := Motor_ON OR MotorOnAux;
Motor_ON := Motor_ON AND NOT E_STOP;
IF Speed > 3000 AND Motor_ON THEN

ai
Motor_ON := FALSE;
E_STOP := TRUE;
Setpoint := 0;

SIMOTION
END_IF;
END_FUNCTION_BLOCK

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.14
SITRAIN Training for
Automation and Drives
@
Statement part The actual calculation is performed within the statement part. You can use the
same syntax to access parameters and local variables of a function block.
In the case of "read" access, the operand always appears to the right of the
assignment operator (":=") in the expression. In the case of write access, the
er

operand appears on the left of the assignment operator.

Access to Access to the input parameters of a function block is read-only, i.e. the
parameters parameter must always be written to the right of the assignment operator
ez

":=" (read access).


Access to output and in-out parameters of an FB can be both read and write.
These parameters can, therefore, be positioned to the left and to the right of the
assignment operator.
r.s

Access to variables (no constants) can be both read and write.

Memory A function block can retain information from call to call in both static variables
and output parameters because:
ne

• Both static variables and output parameters are stored in the instance
data area of an FB and, therefore, retain their contents from one call to the
next.
• Both static variables and output parameters can be accessed in the
statement part of an FB in read and write mode.
• It is not possible to change static variables or output parameters from
ca

"outside" (e.g. from the calling block).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 Functions and function blocks
Instantiation of function blocks
FUNCTION_BLOCK Motor Instance area for Motor_1
VAR_INPUT Start
Start BOOL
BOOL FALSE
FALSE
Start: BOOL; Stop
Stop BOOL
BOOL FALSE
FALSE
END_VAR Speed
Speed INT
INT 00
. . . Motor_ON
Motor_ON BOOL
BOOL FALSE;
FALSE;
Setpoint
Setpoint INT
INT 00
END_FUNCTION_BLOCK E_STOP "Pointer"0h
0h
E_STOP "Pointer"
... Drive_1

om
...
PROGRAM MyProgram
VAR Instance area for Motor_2
E_STOP: BOOL; Start
Start BOOL
BOOL FALSE
FALSE
Motor_1: Motor; Stop
Stop BOOL
BOOL FALSE
FALSE
Motor_2: Motor; Speed
Speed INT
INT 00
Motor_3: Motor; Motor_ON
Motor_ON BOOL
BOOL FALSE;
FALSE;

l.c
END_VAR Setpoint
Setpoint INT
INT 00
E_STOP
E_STOP "Pointer"0h
"Pointer" 0h
Motor_1( Drive_2
...
...
Start:= %I0.0,
Stop:= %I0.1,
Speed:= 200, Instance area for Motor_3

ai
E_STOP:= E_STOP); Start BOOL FALSE
Start BOOL FALSE
; Stop
Stop BOOL
BOOL FALSE
FALSE
: Speed
Speed INT
INT 00
Motor_ON
Motor_ON BOOL
BOOL FALSE;
FALSE;
%Q4.0:= Motor_1.Motor_ON;

SIMOTION
END_PROGRAM

Siemens AG 2013. All rights reserved.


gm
Date:
File:
Setpoint
Setpoint
E_STOP
E_STOP
...
...

10.01.2013
MC-SMO-PRG_03.15
INT
INT
"Pointer"
00
"Pointer"0h
0h
Drive_3

SITRAIN Training for


Automation and Drives
@
What is an The concept of instantiation of FBs is fundamental and constitutes the main
Instance? difference between FBs and FCs. Creating variables in a high-level language
such as "C" or "ST" and assigning variable names and data types to them is
called "instantiation" or "instance creation".
er

Function blocks are "instantiated" just like variables. An FB only becomes an


executable unit (FB instance) once it has been assigned its own data area
where the values of the block parameters and the static variables are stored.
Actuating a physical process unit such as a drive or furnace is then performed
ez

by means of an FB instance, i.e. an FB with assigned data area. The data


relevant for this process unit is then stored in this data area.

Instantiation Creating an FB instance, i.e. assigning a dedicated memory area to an FB, can
r.s

be performed in the declaration part of the calling block or in another global


variable list.
The instance concept of function blocks offers the following benefits:
• You do not need to save and manage local data at all when FBs are called.
• The instance concept allows multiple use of a function block. For example, if
ne

you want to actuate several process units of the same type (e.g. drives,
valves, etc.), you can use multiple instances of an FB.
The status data of the individual process units is mapped to the static
variables/output parameters of the FB.
ca

• The instantiation concept of FBs allows you to use a hierarchical structure.


This means that you can design object-oriented programs which are an
exact reflection of the technological structure of the machines and systems
used in the plant.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 Functions and function blocks
IEC-compliant call of FB instances in ST

PROGRAM MyProgram

VAR
E_STOP: BOOL;
FB instance name
Motor_1: Motor;

om
Motor_2: Motor;
Motor_3: Motor;
END_VAR
Assigning the input and
Motor_1( in-out parameters in
Start:= %I0.0, the parameter list
Stop:= %I0.1,
Speed:= 200,
E_STOP:= E_STOP); Copying the output

l.c
%Q4.0:= Motor_1.Motor_ON;
parameters to the
; actual parameters
Motor_2(
Start:= %I1.0,

ai
Stop:= %I1.1,
Speed:= -400, <InstanceName.OutputParameter>
E_STOP:= E_STOP);
%Q4.1:= Motor_2.Motor_ON;

SIMOTION
END_FUNCTION_BLOCK

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.16
SITRAIN Training for
Automation and Drives
@
Calling FB instances An FB instance can be called within the calling block via its instance name
in ST (variable name). The instance name and parameter list are specified when the
instance is called.
er

Input and in-out In ST, an actual parameter can be specified for each input parameter and must
parameters be specified for each in-output parameter when an instance is called.
If no actual operand is specified for an input parameter, the value of the last FB
instance call/the initialization value is used for FB execution.
ez

For all in-out parameters, ST - and of course all other compilers (LAD, CSF,
MCC) - forces the formal parameter to be supplied with a variable. Due to the
parameter transfer mechanism for in-out parameters, the assigned variable
must be directly readable and writable.
r.s

Output The FB instance returns the results of the call in output parameters. Output
parameters parameters cannot be specified in the parameter list in an FB instance call. After
the call, output parameters can be only be "cleared" (i.e. assigned to one of the
calling block's variables, for example) via explicit access to the private data area
ne

of the FB instance.
The output parameter of the FB instance is accessed by specifying the instance
name and - separated by a period - the name of the formal output parameter,
e.g.:
• %Q4.0:= Motor_1.Motor_ON
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 Functions and function blocks
Call options with the compiler option
"Permit language extension"

PROGRAM MyProgram

VAR
E_STOP: BOOL;
Motor_1: Motor;

om
Motor_2: Motor;
Motor_3: Motor;
END_VAR
Motor_1(
Start := %I0.0, FB instance call with specification
Stop := %I0.1,
Speed := 200, of output parameters

l.c
E_STOP := E_STOP,
Motor_ON => %Q4.0);

Motor_2.Start := %I1.0;

ai
Motor_2.Speed := 400;
Motor_2( E_STOP := E_STOP);
%Q4.1:= Motor_2.Motor_ON; Read and write access to input
parameters outside of the

SIMOTION
END_FUNCTION_BLOCK

Siemens AG 2013. All rights reserved.


gm
Date:
File:
parameter list

10.01.2013
MC-SMO-PRG_03.17
SITRAIN Training for
Automation and Drives
@
Extended call Activating the compiler option "Permit language extensions" makes the following
and access additional call and access options available to the ST programmer:
options
• Clearing of output parameters in the parameter list
er

In this case, the formal output parameters of an FB can be assigned


directly to the actual parameters (variables) in the parameter list using the
output assignment "=>".
ez

The actual operation to copy the values of the output parameters from the
instance data area of the FB is performed immediately after termination of
FB execution.
• Read and write access to input parameters
In addition to the assignment of an actual operand to the input parameter
r.s

when an FB is called, this compiler option also supports read and write
access to the FB's input parameters in the associated instance data area
outside of the FB.
The input parameters are accessed in the same way as the output
parameters - by specifying the instance name and the parameter name.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 Functions and function blocks
Forward declarations in ST (new as of V4.2)
Use of FCs, FBs, or programs INTERFACE
(POU = program organization TYPE
units) prior to implementation: FUNCTION_BLOCK OperateMode; //Forward decl.
END_TYPE
Standard: VAR_GLOBAL
myOpMode : OperateMode; // Only with fwd decl.
END_VAR
• The sequence of the POUs is

om
PROGRAM MyCyclicProg;
important; called POUs must
be compiled before the call END_INTERFACE

Forward declaration: IMPLEMENTATION


• Specification of the POU in the FUNCTION_BLOCK OperateMode

l.c
TYPE/END_TYPE section of the VAR_INPUT
. . .
interface or implementation part END_VAR
• The POU can be used now; the . . .
END_FUNCTION
implementation will follow later

ai
PROGRAM MyCylicProg
• This is being achieved with a . . .
two-phase compiler myOpMode(. . .);
. . .

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
END_PROGRAM

END_IMPLEMENTATION

10.01.2013
MC-SMO-PRG_03.18
SITRAIN Training for
Automation and Drives
@
Overview When creating the source file, you should always pay attention to the order of
the source file modules. A module that is to be called must always precede the
calling module so that the former is recognized by the latter. For example,
variables must be declared before they are used, functions must be defined
er

before they are called, and function blocks must be defined prior to instance
declaration.

Forward declaration If the "Permit forward declarations" compiler option is activated, the program
ez

organization units (POUs) can be used for the following purposes in a source
file, before the corresponding POUs have been fully defined:
• Instance declaration of a function block
• Call of a function
r.s

• Call of a program within a program, as long as the program to be called has


only been created once with the compiler option "Only create program
instance data once"
If this compiler option has been activated, the following statements are
interpreted as prototypes within the TYPE/END_TYPE section in the interface
ne

part or implementation part of an ST source file:


• FUNCTION_BLOCK FB_name
• FUNCTION FC_name
• PROGRAM prog_name
ca

Example Then, in an ST source file, once the prototype of an FB has been declared, an
instance of the FB can be declared; the FB is not implemented until
subsequently in the implementation part of the ST source file.

Note With MCC or LAD/FBD language, using (i.e. declaring) FB instances or calling
FCs and programs without explicit forward declaration is always possible.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 Functions and function blocks
Command library in SIMOTION SCOUT

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
Command library
gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.19
SITRAIN Training for
Automation and Drives
@
Overview ST provides a range of standard functions and function blocks for solving
common tasks. These standard functions and function blocks can be moved to
an ST source file using a drag and drop operation in the project navigator (select
command library).
er

Alarms & messages These functions send configured messages (e.g. error messages) to the display
devices that are logged on or check their status. Both messages that do not
require acknowledgment and messages that require acknowledgment can be
ez

sent. The state of a message and its acknowledgment state can also be
checked.

Drives This function is used to read and write drive parameters as well as to read out
the latest fault buffer entry in the drive.
r.s

Bit string Bit string functions are used to manipulate sequences of bits by means of
functions shifting (SHL, SHR) or rotation (ROL, ROR). There are also functions to read or
write individuals bits within a BYTE, WORD, or DWORD variable.
ne

Communication This group contains functions for data exchange between devices using the
Ethernet protocols UDP and TCP/IP, as well as functions for data transfer on
PROFIBUS.
ca

Data type When you link two operands in an operation or perform a value assignment,
conversion you must take data type compatibility into account. SIMOTION provides the
functions necessary for the explicit conversion of data types.

Logic This group contains functions for logic or bit-by-bit operations between
corresponding operands.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 Functions and function blocks
Standard functions in SIMOTION

Standard function Example


Alarms + messages _alarmsqId(..),_alarmsId(..)
_alarmscId(..), ...
Mathematical functions SIN(..), TAN(..), SQRT(..),

om
EXP(..), LOG(..), ..
Bit string standard functions SHL( ), ROR( ), ...
_getBit(..), _setBit(..)
Conversion INT_TO_DINT(..),
USINT_TO_BYTE (..), ...

l.c
Functions for task _restarttaskId(...),
handling _getStateOfTaskId(...), ...

ai
Communication _xsend(..),_xreceive (..),
_udpSend(..),_udpReceive(..),
...
TO-specific functions _enableaxis)..),_move(..),

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
_pos(..),...

10.01.2013
MC-SMO-PRG_03.20
SITRAIN Training for
Automation and Drives
@
Mathematical These are the functions for more complex mathematical operations. They go
functions beyond the scope of the commands supported by the ST language. Simple
mathematical functions can be performed using the operators +, -, *, /, **.
er

I/O These are primarily function blocks for accessing I/O modules such as CP or
FM modules.

PLCopen These are all of the function blocks conforming to PLCopen. These blocks have
ez

been designed for moving axes from a cyclic user program that is executed in
the BackgroundTask, for example.

Task handling Task control commands are used to manipulate the execution system (to start or
r.s

stop individual tasks, for example). In addition, the current state of tasks
(RUNNING, STOPPED, etc.) and information about task runtimes can be
obtained.

TO-specific TO functions are commands that execute specific actions at a technology object,
ne

functions such as axes, output cams, measuring inputs, etc. Before technology functions
can be called in a user program, the corresponding technology package must be
integrated into the associated ST source file with the USEPACKAGE statement.

Other system This group contains various functions such as querying the states of DP slaves
ca

functions or functions for saving UNIT variables on a CF or MMC card.

Character strings These functions are used to edit STRING type variables.

LAD/FBD These groups contain special operations for use in LAD/FBD programs.
elements

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 Functions and function blocks
Standard function blocks in SIMOTION

Standard function block Example


Bistable flip-flops SR(...), RS(...)

Edge evaluation R_TRIG(...), F_TRIG(...)

om
Counters CTU(...), CTD(...), CTUD(...)

Timers TP(...), TON(...), TOF(...),

l.c
RTC(...)
PLCopen _MC_Power(), _MC_Home(),
_MC_MoveAbsolute(),
_MC_MoveRelative(),

ai
_MC_MoveAdditive(),
_MC_MoveSuperImposed(),
_MC_Stop(), . . .

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.21
SITRAIN Training for
Automation and Drives
@
Overview Unlike system functions, system function blocks must be instantiated. First, a
variable of the function block type must be declared. This instance can then be
called.
er

Bistable SIMOTION features integrated function blocks for implementing bistable


elements flip-flops. In ST, the SR system function blocks can be used to implement a flip-flop
with dominant set. RS implements a flip-flop with dominant reset.
ez

Edge The R_TRIG system function block detects a rising edge, F_TRIG detects a falling
evaluation edge.

Counters ST provides a range of system s function blocks for counters. In total, three types
r.s

conforming to IEC 61131-3 are available:


• CTU: Implements an @up-counter, i.e., if the CU input is at 1, the internal
counter status is incremented by 1.
• CTD: Implements a down-counter.
• CTUD: Implements an up-down counter.
ne

• RTC: RTC is used to set and read out the controller's real-time clock.
ST also provides a range of IEC-compliant timers:
Timers • eTP: Time pulse
• TON: Switch-on delay
ca

• TOF: Switch-off delay

PLCopen This library contains the single-axis and multi-axis blocks conforming to
PLCopen. It also features an integrated block for implementing JOG mode for
axes.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 Functions and function blocks
Access to technology objects via TO data types

• In FBs and FCs via input parameters


• Overview: TO data types
Technology object Keyword

om
Drive axis driveAxis
Position axis posAxis
Following axis followingAxis
Following object followingObjectType
Cam camType

l.c
External encoders encoderType
Measuring input measuringInputType
Output Cam outputCamType

ai
Temperature Controller temperatureControllerType
AnyObject anyObject

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.22
SITRAIN Training for
Automation and Drives
@
General Within library blocks such as FCs or FBs, the technology objects of a project can
only be accessed via input parameters of the "Technology object" type.
In this case, the requisite input parameters must be declared in the declaration
part of the FC or FB.
er

Properties The data types of technology objects are determined by the technology package
loaded. The elements (e.g. system variables) of technology objects can be
accessed via TO data type input parameters.
ez

Inheritance can also be used between data types. Inheritance for axes means
that all of the data types, system variables, and functions of the "driveAxis" TO
are fully included in the "posAxis" TO. In turn, "posAxis" is fully included in the
"followingAxis" TO.
r.s

If a function or a function block expects an input parameter of the "driveAxis"


data type, inheritance allows you to also create a "posAxis" or a "followingAxis"
when calling.
The same applies if the input parameter expects a "posAxis". Here too, a
"followingAxis" can be specified when making the call.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 Functions and function blocks
Example TO access

• FB for positioning axes


FUNCTION_BLOCK Axis_FB
VAR_INPUT
myAxis : posAxis; // Declaration of input parameters for axis
myPos : LREAL := 0; // Position of axis

om
END_VAR
VAR_OUTPUT
myActPos : LREAL; // Variable for actual position of axis
END_VAR
VAR
retVal : DINT; // Variable for return value of TO function

l.c
END_VAR
retVal := _enableAxis(axis := myAxis); // Axis is enabled.

retVal := _pos(axis := myAxis, // Axis is positioned.

ai
position := myPos);

myActPos := myAxis.positioningState.actualPosition;
// Scanning position using system var access

SIMOTION
END_FUNCTION_BLOCK

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_03.23
SITRAIN Training for
Automation and Drives
@
Example The above diagram shows an application example of an input parameter of the
technology object data type.
In the function block "axis_fb", an axis is enabled using the TO function
_enableaxis(). Then the axis is moved to a specified position using the _pos()
er

system function.
After positioning, the current position of the axis is stored by means of structure
access.
ez

Note The above FB, however, is not programmed in a "watertight" manner. Since the
input parameters do not necessarily have to be assigned when the FB is called, the
input parameter "myAxis" will not necessarily point to a valid Axis TO.
Therefore, in an FB which is@ provided for general use, e.g. via a library, it is
r.s

always advisable to check whether the input parameters which are to be used to
access technology objects really do point to valid TOs.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 Functions and function blocks
Transformation and checking of TO data types
Implicit type cast (without conversion function)
• To a variable of a TO data type lower down the hierarchy:
VAR
drv_axis1 : driveAxis;
pos_axis1 : posAxis;
any_obj1 : anyObject;
END_VAR

om
drv_axis1 := pos_axis1;
any_obj1 := drv_axis1;

Explicit type cast (with conversion function)


• To a variable of a TO data type higher up the hierarchy:
VAR

l.c
drv_axis1 : driveAxis;
pos_axis1 : posAxis;
any_obj1 : ANYOBJECT;
END_VAR
pos_axis1 := ANYOBJECT_TO_OBJECT(drv_axis1);

ai
pos_axis1 := ANYOBJECT_TO_OBJECT(any_obj1);

Testing a TO reference

SIMOTION
Siemens AG 2013. All rights reserved.
gm
• With input parameters in FC, FB; after an explicit type transformation:
IF pos_axis1 <> TO#NIL THEN . . . // cast was successful

Date:
File:
10.01.2013
MC-SMO-PRG_03.24
SITRAIN Training for
Automation and Drives
@
Transformation of The TO data types driveAxis, posAxis, and followingAxis have a hierarchically
TO data types structured functionality.
A position axis (posAxis data type) contains the functionality of a drive axis
(driveAxis data type). A following axis (followingAxis data type) contains the
er

functionality of a position axis (posAxis data type) and, therefore, also of a drive
axis (driveAxis data type).
SIMOTION only supports type conversion within these hierarchical data types
as well as with the general TO data type ANYOBJECT. Other type conversions
ez

are not possible (e.g. from measuring input to output cam).


It is possible to assign variables (with TO data type) or TO instances to the
Implicit type following variables without specifying a conversion function:
conversion
• To a variable of a TO data type lower down the hierarchy:
r.s

- followingAxis t o posAxis or driveAxis


- posAxis to driveAxis
• To a variable of the general ANYOBJECT TO data type
ne

It is possible to assign variables (with TO data type) to variables with a TO


Explicit type data type higher up the hierarchy using the following type conversion function:
conversion
anyObject_to_Object
For conversion to be successful, the source variable (with the TO data type
ca

lower down the hierarchy) must point to a TO instance that is at least as high up
the hierarchy as the TO data type of the target variable.
Otherwise, the target variable of the value

• TO#NIL
is assigned. This value can be evaluated in an IF statement, for example, with
the comparison operator "=".

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 Functions and function blocks
Programming motions of axes

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.1
SITRAIN Training for
Automation and Drives
@
Contents Page
SIMOTION - Axes - Drives ............................................................................................................... 2
Technology objects (TO) in SIMOTION ........................................................................................... 3
Creating and configuring an axis ....................................................................................................... 4
er

Changing configuration data with SCOUT/the user program ............................................................ 5


Collecting and activating changed configuration data ....................................................................... 6
Using RESTART to activate configuration data ................................................................................ 7
Programming traversing ................................................................................................................... 8
ez

General structure of an axis command ............................................................................................. 9


Motion buffers of an axis .................................................................................................................. 10
Transition behavior of motion commands ......................................................................................... 11
Blending motions of axes ................................................................................................................. 12
r.s

Superimposed motions of axes ......................................................................................................... 13


Resetting the superimposed coordinate system ................................................................................ 14
Delay program execution ................................................................................................................. 15
Command tracking via the CommandId ............................................................................................ 16
Evaluating the command status with the CommandId ...................................................................... 17
ne

Buffering and deleting the CommandId in the TO ............................................................................. 18


Evaluating the motion status with the CommandId ........................................................................... 19
Evaluating the motion status with system variables .......................................................................... 20
Stop of an axis ................................................................................................................................. 21
ca

Emergency stop of an axis ............................................................................................................... 22


Resuming a stopped motion ............................................................................................................. 23
Setting and shifting the coordinate system ........................................................................................ 24
Reset axis TO .................................................................................................................................. 25
Acknowledging errors on the axis TO ............................................................................................... 26
Reading out errors on the axis TO .................................................................................................... 27
Enable axis command ...................................................................................................................... 28
Disable axis command ..................................................................................................................... 29

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 Programming motions of axes
SIMOTION - Axes - Drives

Technology objects SIMOTION


ƒ Linear/rotary axis
ƒ Units mm or degrees
ƒ Position control Axis 1 Axis 2 Axis 3
ƒ Positioning Position control Position control Position control
ƒ Referencing (homing)

om
ƒ Synchronous operation

Communication via Message frames, e.g. speed setpoint, encoder actual value, control word, status word
PROFIBUS/PROFINET

Drive objects

l.c
ƒ Speed control Drive 1 Drive 1 Drive 3
ƒ Current control
ƒ Power module Speed control Speed control Speed control
ƒ Motor

ai
ƒ Encoder
M Motor M M
Encoder

SIMOTION
Siemens AG 2013. All rights reserved.
~
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.2
~
SINAMICS
~

SITRAIN Training for


Automation and Drives
@
General The conventional division into controller and drive system has been retained in
SIMOTION. SIMOTION provides full motion control functionality including
position control. The drive is operated with speed control. Any motion control
functionality present in the drive is not used.
er

Controller The controller handles the execution of the specified (motion) program and
controls the I/Os of the entire machine.
In the interpolator, the motion commands are converted into information about
ez

the axis position to be reached, its velocity and its acceleration.


The position setpoint represents the link to the position controller. This
calculates the required axis speed/velocity from the position setpoint and the
actual position value. This velocity is transferred to the drive system. Transfer
r.s

can be either digital (PROFIBUS, PROFINET) or analog (+/- 10 V).

Drive system The drive system converts this information into a speed setting. The motor runs
at this speed to traverse the axis in the specified time/at the specified velocity
and reach the required target position.
ne

The drive system consists of an inverter, a motor, and an encoder.


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Programming motions of axes
Technology objects (TO) in SIMOTION
Configu-
ration
Configu- System data
ration variable
data
Syn- System
Cam chronous func-
System
operation tions
func- Configu-

om
System tions ration
variable data Alarms Configu-
Alarms
ration
data
Encoder System
func-
System tions Axis
Configu- variable System
System Alarms

l.c
ration func- func-
data tions System tions
variable
Alarms
Measuring Configu-
input ration

ai
data
System Alarms
variable Output
cam System
func-

SIMOTION
Siemens AG 2013. All rights reserved.
gm
System
variable

Date:
File:
Alarms

10.01.2013
MC-SMO-PROG_04.3
tions

SITRAIN Training for


Automation and Drives
@
Technology objects In SIMOTION, the technology objects are provided in loadable technology
packages. Each technology package provides the entire functionality for the
respective technology. For example, the "Position" technology package contains
all functions required for traversing and positioning axes.
er

In SIMOTION, a technology object (TO) is created (instantiated) for each


"physical" automation object (e.g. axis, external encoder, measuring input, etc.).
Each TO in SIMOTION contains:
• Configuration data: The created objects are adapted to the requirements of
ez

the automation task at hand with configuration data.


• System data: The TO provides information on its current status in its
system data. Accordingly, the system data of an axis TO will display
information such as the position setpoint, actual position value, following
r.s

error, etc.
Default values and settings can also be read/specified via system variables.
• System functions: The user program uses system functions to access the
functionality for actuating the associated "physical" object. An axis TO, for
example, will provide powerful system functions for positioning, homing,
ne

stopping, etc., an axis.


Motion commands are issued on an axis to control its motion sequences,
for example. The user program can be used to check the motion status at
any time and to control specific aspects of the motion. Motions can be
aborted, overridden, attached, or superimposed.
ca

• Alarms:If an event (error, note) occurs on a technology object, the object


issues a "technological alarm".
The technology object alarms cause subsequent responses in the system.
For each alarm, certain effects have a default setting. However, these
settings can be adapted to meet the specific requirements of the task at
hand.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Programming motions of axes
Creating and configuring an axis

Using
parameter
screens

om
l.c
ai
Using
expert list

SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm 10.01.2013
MC-SMO-PROG_04.4
SITRAIN Training for
Automation and Drives
@
Configuration You will need to work through several steps before you can use the technology
of TOs objects.
First, an instance of the technology object is created by means of configuration.
A TO is configured with the SCOUT engineering system. Appropriate wizards
er

(parameter screens) assist with object representation and configuration.


An axis instance is inserted in the Axes directory in the project navigator by
double-clicking the "Insert axis" entry. The axis wizard then automatically starts
and helps the user to create and configure an axis.
ez

Certain object-specific properties are determined during first-time configuration


(e.g. drive axis, position axis, following axis). This definition also determines the
"size" of the technology object (i.e. the number of configuration and system
variables it contains).
r.s

It is, therefore, not possible to change properties such as drive axis, position
axis, etc., later. To convert a driveAxis TO to a posAxis TO, the original drive TO
must be deleted and a new posAxis TO inserted.
Configuration data generally determines the static properties of a TO. Certain
properties determined by the configuration can also be changed during runtime.
ne

Expert list In addition to accessing the configuration data and system variables via the
wizards and parameter screens, you can also access the data directly via an
expert list. The expert list for an object is opened via the context menu (Expert
ca

-> Expert list command). Select the object in the project navigator first.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Programming motions of axes
Changing configuration data with SCOUT/the user program

Overwriting the servo gain factor

om
l.c
TO- Config- read data
myKv := Axis_1.activeconfigdata.typeofaxis.numberofdatasets.
dataset_1.controllerstruct.pv_controller.kv;

ai
TO- Config- overwrite data

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Axis_1.setconfigdata.typeofaxis.numberofdatasets.dataset_1.
controllerstruct.pv_controller.kv := 100;

Date:
File:
10.01.2013
MC-SMO-PROG_04.5
SITRAIN Training for
Automation and Drives
@
Configuration data Configuration data defines the principal functionality of a TO. It is generally set
using the SCOUT engineering system during object configuration and remains
fixed during runtime.
Part of this configuration data can, however, be modified while the program is
er

running. Whether or not a configuration data element can be changed online


depends on the variable. This feature is documented for each configuration data
element in the configuration data reference list.
Depending on the configuration data eitem, the following options are available:
ez

• Cannot be changed online: Configuration data of this type can only be


modified during configuration of the technology object with SIMOTION SCOUT.
• Can be modified online, effective after restart: Configuration data of this
type can be changed by variable access from the user program.
r.s

The change does not take effect until the technology object is restarted.
• Can be modified online, effective immediately: Configuration data of this
type can be changed by variable access from the user program. The change is
effective immediately.
ne

Online mode supports both read and write access to configuration data. For
Online access read access, activeconfigdata must be added to the name of the
configuration data; for write access, setconfigdata must be added.
Example:
ca

• Reading the servo gain factor:


kv_factor := Axis_1.activeconfigdata.typeofaxis.numberofdatasets.
dataset_1.controllerstruct.pv_controller.kv
• Writing the servo gain factor
Axis_1.setconfigdata.typeofaxis.numberofdatasets.
dataset_1.controllerstruct.pv_controller.kv := 56

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Programming motions of axes
Collecting and activating changed configuration data

om
Collecting and activating changes

l.c
activationModeChangedConfigData

ai
ACTIVATE_CHANGED_CONFIG_DATA

SIMOTION
Siemens AG 2013. All rights reserved.
gm
COLLECT_CHANGED_CONFIG_DATA

Date:
File:
10.01.2013
MC-SMO-PROG_04.6
SITRAIN Training for
Automation and Drives
@
Effectiveness The "effectiveness" of changes can be controlled with a system variable. The
technology object system variable activationModeChangedConfigData defines
when the changes made to the configuration data are to be activated.
• When the system variable activationModeChangedConfigData is set to
er

ACTIVATE_CHANGED_CONFIG_DATA,
the modified data becomes effective immediately. If the system variable is
set to this value, data collected up to this point is also activated.
ez

• When the system variable activationModeChangedConfigData is set to


COLLECT_CHANGED_CONFIG_DATA,
the modified data is collected and activated as a whole. Activation happens
when activationModeChangedConfigData is set to
r.s

ACTIVATE_CHANGED_CONFIG_DATA.

Values of collected configuration data can be deleted without activation by


calling the corresponding technology object system function (e.g.
ne

resetAxisConfigDataBuffer()).

Note Once the modified configuration data item is written, it will take some time for
the change to take effect, even if the setting activationModeChangedConfigData
= ACTIVATE_CHANGED_CONFIG_DATA is used. Timeouts are likely to occur
ca

in the tasks in particular whenever changes are made to multiple configuration


data items simultaneously.
If you want to change multiple configuration data items simultaneously, it is,
therefore, advisable to collect them first with activationModeChangedConfigData
= COLLECT_CHANGED_CONFIG_DATA and then activate them as a whole
using the ACTIVATE_CHANGED_CONFIG_DATA setting.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Programming motions of axes
Using RESTART to activate configuration data
Activate RESTART

Effectiveness

1. Activate precontrol

om
l.c
3. Control

restartActivation

ai
2. activateRestart

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.7
SITRAIN Training for
Automation and Drives
@
Restarting the TO To integrate configuration data that requires a TO restart, you must reset the
technology object. The procedure depends on the
Restart.restartActivationSetting configuration data item of the TO.
er

If
• Restart.restartActivationSetting RestartInfo = RESTART_BY_COMMAND,
the TO can only be restarted with the corresponding system function (e.g.
resetAxis()). The activateRestart parameter of the corresponding call must be
ez

set to ACTIVATE_RESTART.
If
• Restart.restartActivationSetting =
RESTART_BY_SYSVAR_AND_COMMAND,
r.s

the restart can be performed in two ways:


• By calling the corresponding system function (e.g. _resetAxis). The
activateRestart parameter of the system function must be set to the value
ACTIVATE_RESTART
ne

• By setting the restartActivation system variable to ACTIVATE_RESTART.


After a successful restart of the technology object, the value of this system
variable is automatically reset to NO_RESTART_ACTIVATION.

Note A RESTART can also be activated from within SIMOTION SCOUT by pressing
ca

the corresponding button on the toolbar.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Programming motions of axes
Programming traversing

om
„ Enable / disable axis _enable / _disable
„ Move axis _move
„ Position axis to target position _pos
„ Stop axis motion _stop / _stopEmergency
„ Continue axis motion _continue

l.c
„ Home axis _homing

ai
SIMOTION
Command library

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.8
SITRAIN Training for
Automation and Drives
@
General SCOUT provides what are known as single axis commands to traverse the axes
created.

_enableAxis / This function switches the enable signals on the axis. The states of the
er

_disableAxis drive and power enable signals can be accessed using the system variables
actorMonitoring.driveState (DRIVE) and actorMonitoring.power (POWER).

The position controller enable must be set for position axes. Its state can be
checked with servoMonitoring.controlState. The position controller enable is
ez

ignored for drive axes These commandse cannot be executed in the StartUpTask
of a program.

_move The axis is accelerated or decelerated to the programmed velocity. If no time limit
has been programmed (parameter 'moveTimeOutType
r.s

:=WITHOUT_TIME_LIMIT'), the velocity is maintained at a constant level after


the transition to the constant motion phase.

_pos This function moves the axis to the programmed target position with a definable
velocity profileg. The dynamic parameters can be specified in the command.
ne

This colmmand stops all motion or the specified motion (basic motion or
_stop/ superimposed motion). The stop command affects only single axis motion and
_stopemergency cannot be used for synchronous operation motion.
ca

If an axis has been stopped with STOP_WITHOUT_ABORT, motion can be


_continue resumed with this command.

Function for homing an axis. An axis has the 'referenced' or 'homed' status when
_homing the controller coordinate system is aligned with the axis system. The status can
be read from the 'positioningState.homed' system variable.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Programming motions of axes
General structure of an axis command
Position axis
RetVal := _pos( Return value
axis, // axis to be positioned Axis
direction, // direction: modulo axis
positioningmode, // absolute, relative? Position +
Position // position direction
velocitytype, // direct, userdefault

om
velocity, // velocity: when direct
positiveacceltype, // direct, userdefault
positiveaccel, // accel., only when direct
negativeacceltype, // direct, userdefault
negativeaccel, // accel., only when direct
positiveaccelstartjerktype, // direct, userdefault
positiveaccelstartjerk, // jerk, only when direct Dynamic

l.c
positiveaccelendjerktype, // direct, userdefault response
positiveaccelendjerk, // jerk, only when direct
negativeaccelstartjerktype, // direct, userdefault
negativeaccelstartjerk, // jerk, only when direct

ai
negativeaccelendjerktype, // direct, userdefault
negativeaccelendjerk, // jerk, only when direct
velocityprofile, // trapezoidal, smooth
mergemode, // substitute, attach, Execution

SIMOTION
blendingmode,
nextcommand,
commandid);

Siemens AG 2013. All rights reserved.


//
//
//gm
Date:
File:
active, inactive
waiting until ... ?
identification

10.01.2013
MC-SMO-PROG_04.9
control
Identification

SITRAIN Training for


Automation and Drives
@
General In order to use system functions of technology objects in a program, you must
first integrate the corresponding technology package. The user program uses
TO system functions to send jobs to the addressed technology object.
The TO either accepts the job or returns it for specific reasons. On accepting a
er

job, it then executes it. In the event of an error while a job is being processed
(with the result that the job can no longer be executed correctly and completed),
the TO sets an alarm message with the corresponding error response as set in
the parameters.
ez

Return value In the return value for the system call, the addressed TO indicates whether it is
accepting the job or rejecting it (in the latter case giving the reasons why). All
motion commands normally return a double-precision integer (DINT).
r.s

The calling program can tell from this value whether the job has been accepted
(return value = 0) or rejected (return value <> 0). In the online help for the
_move() command, the possible return values are listed with a corresponding
description.
ne

Input parameters The input parameters of the TO system function call can be divided into the
following groups:
• mandatory: These parameters must be specified with the call. This group
includes the TO instance, the target position, etc.
• optional predefined: These parameters can be specified in the call but do not
ca

have to be.
If they are not specified in the call, a system default setting is activated,
e.g. IMMEDIATELY for command advance conditions.
• optionalUserDefault: These parameters can also be specified in the call but
do not have to be.
If they are not specified in the call, a user-defined default (dialog: Default)
is activated.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Programming motions of axes
Motion buffers of an axis

MotionTask 1
motion buffer for axis 2
start

motion buffer axis 1 basicMotion.position

om
Pos(Achse1) buffer for sequential movement IPO
(basic coordinate system) (Basis)
+ Position
control
buffer for superimposed movement IPO
(superimposed coordinate system)
(überlagernd)

l.c
enable/ disable commands
superimposedMotion.position

ai
end buffer for emergency stop
und stop / continue commands

positioningState.commandPosition

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.10
SITRAIN Training for
Automation and Drives
@
General Commands can be issued from all user tasks of the system. The execution time of
a command on the technology object is the only factor that determines the
effectiveness of the command.
er

Since a technology object does not have a task context, the priority of the task
which issued the command is of no significance for command execution. If
commands are issued from multiple tasks, the user program must ensure
consistency as regards the order in whichm they are executed.
ez

Command buffers
Each axis has a command buffer so ethat multiple commands can be issued to one
axis TO. This buffer consists of ifour command-group-specific sub-buffers. Each
sub-buffer can buffer one cosmmand from one of the following command groups.
r.s

• Sequential traversing (basic motion)


• Superimposed traversing
• Emergency stop and stop/continue commands
• Enable and disable commands
ne

The interpolators on the axis reads the command out of the command buffers (in
the IPO cycle clock) and processes them. Commands from different command
ca

groups are processed in parallel by the interpolators.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Programming motions of axes
Transition behavior of motion commands

RetVal := _pos(
axis := . . ., // Axis
. . ., //
blendingMode:=ACTIVE, // Select: Blending
. . ., //
mergeMode:=NEXT_MOTION ); // Select: Transition behavior

om
IMMEDIATELY NEXT_MOTION
Replace current motion immediately: Attach and clear buffer:

l.c
SEQUENTIAL SUPERIMPOSED_MOTION_MERGE

ai
Attach: Superimpose:

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.11
SITRAIN Training for
Automation and Drives
@
Transition behavior If a motion command is issued from a program when traversing is
Merge_mode active, how to proceed with the motion command issued is selected by setting
the mergemode parameter accordingly:
• Replace (IMMEDIATELY): The motion specified in the issued command
er

becomes active immediately. The motion command being interpolated is


interrupted. If the command buffer contains a command, it is cleared.
• Attach and discard existing command (NEXT_MOTION): The issued
command is entered in the command buffer. If the command buffer contains
ez

a command, it is cleared. The active traversing (interpolator) is not affected.


• Attach (SEQUENTIAL): The issued command is entered if the command
buffer is empty. If the command buffer already contains a command, the call
is returned with a corresponding error message "8 - Command aborted due
r.s

to full command buffer".


• Superimpose (SUPERIMPOSED_MOTION_MERGE): The issued motion is
executed as superimposed motion. Superimposed motions are independent
motions (one can cause another to abort); they can be stopped and resumed
independently.
ne

The superimposed motion is carried out in a superimposed coordinate


system as relative or absolute movement depending on how it was
programmed. Similarly, the basic movement is carried out in the basic
coordinate system as relative or absolute movement depending on how it
was programmed.
ca

Alarm TO Aborted commands in the interpolator trigger a technological alarm.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 Programming motions of axes
Blending motions of axes
RetVal := _pos(
axis := . . ., // Axis
. . ., //
blendingMode:=ACTIVE, // Select: Blending
. . ., //
mergeMode:=NEXT_MOTION ); // Select: Transition behavior

om
_pos (.. position:= 100,.., _pos (.. position:= 200,..,
velocity:= 20,..) velocity:= 40,..)

40

20

l.c
100 200
Profile without
blending
_pos (.. position:= 100,.., _pos (.. position:= 200,..,

ai
velocity:= 20,..) velocity:= 10,..)

20

SIMOTION
10

Siemens AG 2013. All rights reserved.


Date:
File:
gm
100

10.01.2013
MC-SMO-PROG_04.12
200

SITRAIN Training for


Automation and Drives
@
Blending Blending is a special way of linking the positioning motion programmed in the
Blending_Mode command to a previous positioning motion. Unlike overriding, the previous
motion command is completed up to the target position, where the transition
occurs.
er

Blending takes place between two positioning commands. The set velocity
specified in the commands for each motion is never violated. The previous
positioning motion is performed at the velocity specified in the command up to
ez

the target position.

Exception: If the velocity of the new positioning motion is less than the set
velocity of the previous motion and both motions have the same sign, then the
r.s

velocity of the previous positioning motion is reduced to the velocity of the new
Precondition
motion up to the target position .

Blending requires mergeMode NEXT_MOTION or SEQUENTIAL and an


adequate "leading" program advance, i.e. the new motion to be activated with
ne

'blending' must be known to the interpolator or motion control system at the start
of deceleration in the previous command.
If the blending command is not detected by the motion control system until later,
blending is delayed accordingly.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 Programming motions of axes
Superimposed motions of axes
RetVal := _pos(
axis, // Axis
:, //
mergeMode:=SUPERIMPOSED_MOTION_MERGE // Select superimposition
);

om
Basic
coordinate
Sum
+ coordinate

l.c
Superimposed
coordinate

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.13
SITRAIN Training for
Automation and Drives
@
Superimposed Superimposed motion can be specified by setting the mergeMode parameter
motion to SUPERIMPOSED_MOTION_MERGE. Superimposed motions are
independent motions which can be executed in parallel to a basic motion. One
superimposed motion aborts another; superimposed motions can be stopped
er

and resumed separately.

Coordinate system With a position axis, superimposed motions are performed in an additive
coordinate system. The superimposed motion is performed in a superimposed
ez

coordinate system as relative or absolute movement depending on how it was


programmed.
Similarly, the basic motion is performed in the basic coordinate system as
relative or absolute movement depending on how it was programmed. The point
in time at which the superimposed coordinate is returned to the axis coordinate
r.s

or basic coordinate is set in the configuration data item


• decodingConfig.transferSuperimposedPosition
This setting also specifies when superimposed motions are transferred to the
basic motion, and when they are overridden.
ne

Note Only one superimposed motion can be active on an axis at a given time, e.g.
superimposed positioning motion or superimposed synchronous operation.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 Programming motions of axes
Resetting the superimposed coordinate system

Resulting motion
Basic motion

om
Superimposed motion
with: TRANSFER_STANDSTILL

l.c
Basic motion: target position 100 mm, superimposed motion: 30 mm, was started twice
Feedback from the coordinate system, configurable in:

ai
• TypeOfAxis.decodingConfig TransferSuperimposedPosition:
TRANSFER_RESET (_resetAxis() only)
TRANSFER_ MERGE (positioning motion with mergemode = IMMEDIATELY and

SIMOTION
TRANSFER_STANDSTILL

Siemens AG 2013. All rights reserved.


_resetAxis())

gm
(standstill, positioning motion with mergemode =
IMMEDIATELY and _resetAxis())

Date:
File:
10.01.2013
MC-SMO-PROG_04.14
SITRAIN Training for
Automation and Drives
@
Display The position and dynamic values for the basic and superimposed coordinate
systems are displayed in the system variables for motionStateData.
Sum coordinates:
er

• positioningState.commandPosition: Set position (total)


• motionStateData.commandVelocity: Set velocity (total)
• motionStateData.commandAcceleration: Set acceleration (total)
The position values and dynamic values of the basic coordinate system are
ez

displayed in the system variables of the axis for basicMotion.


The position values and dynamic values of the superimposed coordinate system are
displayed in the system variables of the axis for superimposedMotion.
Feedback from the
r.s

coordinate system Superimposed basic coordinate is set in the following axis configuration data:
The time of feedback of the @superimposed coordinate to the axis coordinate or
TypeOfAxis.decoduingConfig.transferSuperimposedPosition

This setting also specifies when superimposed motions are transferred to


ne

the basic motion, and when they are overridden.


Possible settings are:
• TRANSFER_RESET: Only on axis reset with _resetAxis()
• TRANSFER_MERGE: On axis reset and for every command added
with mergeMode = IMMEDIATELY
ca

• TRANSFER_STANDSTILL: On axis reset, on each overriding


command with mergeMode = IMMEDIATELY, and on each axis standstill

In addition, the superimposed coordinate/motion is fed back to the axis


coordinate in the following cases:
• The axis switches into or out of follow-up mode.
• Switchover occurs between speed-controlled, position-controlled, and
force/pressure-controlled modes.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 Programming motions of axes
Delay program execution
RetVal := _pos(
axis, // Axis
. . ., //
nextCommand:=IMMEDIATELY, // Select program advance
. . .); //
Q4.0 := true;

om
Immediately: At start of deceleration
IMMEDIATELY phase:
AT_DECELERATION_START
Set
At end of setpoint

l.c
After entry in the command queue:
interpolation:
WHEN_BUFFER_READY Actual
WHEN_INTERPOLATION_
DONE Set

At start of interpolation: When motion is completed:

ai
Actual
AT_MOTION_START WHEN_MOTION_DONE

End of acceleration phase:


WHEN_ACCELERATION_DONE

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.15
SITRAIN Training for
Automation and Drives
@
Program For synchronizing program execution and command execution in technological
advance objects, you can use the "next_command" parameter to specify when you want
program execution to resume after the command has been issued.
This makes it possible to wait for partial or complete execution of the motion
er

concerned.
The following settings are available for selection:
• IMMEDIATELY
ez

• WHEN_BUFFER_READY
• AT_MOTION_START
• WHEN_ACCELERATION_DONE
• AT_DECELERATION_START
r.s

• WHEN_INTERPOLATION_DONE
• WHEN_MOTION_DONE
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 Programming motions of axes
Command tracking via the CommandId
Var
myId : commandIdType; // Creation of a variable of type
// commandIdType
End_var

om
myID := _getCommandId(); // Assignment of a free number

RetVal := _pos(
axis := . . ., // Axis
. . ., //
commandId:=myID); // Identification of the command

l.c
or, if tracking commands is not important
RetVal := _pos(

ai
axis := . . ., // Axis
. . ., //
// commandID - comment it out, it is an optional parameter

SIMOTION
);

Siemens AG 2013. All rights reserved.


//

gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.16
SITRAIN Training for
Automation and Drives
@
Command All motion commands have a command ID parameter. In conjunction with
identification system functions, this parameter is used to indicate the status of a command.
The status of a command can also be checked in other parts of the program.
At the start of the TechnologicalFaultTask, this command identification is also
er

specified in the start information of the command which caused the fault.

CommandId The CommandId parameter of a TO command is assigned an identification


number. Once a motion command has been issued, other system functions
ez

such as _getStateOfAxisCommand() and _getMotionStateOfAxisCommand()


can be used on the TO to check the current execution status of the motion
command based on the identification number.
For these commands, the same CommandId used for the motion command is
r.s

then specified as an input parameter.


The CommandId parameter is an optional parameter; it can be omitted from the
call. If it is assigned, a variable of the CommandIdType data type must be
specified. Internally, the CommandIdType data type provided by the system
consists of the two DINT data type structure elements SystemID_low and
ne

SystemID_high.

_getCommandID() The system function _getCommandID() always returns a unique CommandId


that has never been used before. This facilitates unique identification and
command tracking for system functions on TOs in library blocks in particular.
ca

This command can also be specified directly at the CommandId parameter.


However, in this case, the command status can no longer be evaluated.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 Programming motions of axes
Evaluating the command status with the CommandId
Var
myId : commandIdType; // Creation of a variable of type
// commandidtype
End_var

myID:= _getCommandId(); // Assignment of a free number

om
RetVal := _pos(
axis := ..., // Axis
. . ., //
commandID := myID); // Identification of the command

l.c
RetVal :=_getStateOfAxisCommand (
axis:= // Axis
commandId:= myID); // Specification of number

ai
RetVal: ACTIVE: Command is being executed.
NOT_EXISTENT: CommandId not known or command already completed.
WAITING: Command is decoded, execution has not yet started.

SIMOTION
ABORTED:

Siemens AG 2013. All rights reserved.


gm
WAITING_FOR_SYNC_START: Command is decoded, waiting for a synchronous start.
EXECUTED: Execution of the command has been completed.
Execution of the command has been aborted.

Date:
File:
10.01.2013
MC-SMO-PROG_04.17
SITRAIN Training for
Automation and Drives
@
_getstateof This function returns the execution state of a motion command. The return
Axiscommand() value is a structure of the type StructRetCommandState with the following
elements:
• functionResult: DINT, for status see online help for _move
er

• commandIDstate:
- ACTIVE: Command is being executed.
- NOT_EXISTENT: CommandId not known or command already
ez

completed.
- WAITING: Command is decoded, execution has not yet started.
- WAITING_FOR_SYNC_START: Command is decoded, waiting for a
synchronous start.
r.s

- EXECUTED: Execution of the command has been completed (see note).


- ABORTED: Execution of the command has been aborted (see note).

Note Unless provision has been made elsewhere in the user program, the technology
ne

object only buffers the CommandId until the command has been executed or
aborted for other reasons. After this, the CommandId is deleted in the
technology object (so the value NOT_EXISTENT will always be returned when
the execution state is checked).
To check the status of a specific command after it has been completed
ca

(EXECUTED or ABORTED), the CommandId must be explicitly buffered or


(following completion) explicitly deleted in the technology object.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 Programming motions of axes
Buffering and deleting the CommandId in the TO
Var
myID : commandIdType; // Creation of a variable of type
End_var

myID := _getCommandId(); // Assignment of a free number

RetVal := _bufferAxisCommandId( // Buffer CommandId in TO

om
axis := . . ., // Specification of axis TO
commandId := myID,
deleteCommandIdWithReset:= ..);

RetVal := _pos(axis := . . ., // Axis


. . ., //

l.c
commandId := myID); // Identification of the command

RetVal :=_getstateofAxisCommand (
axis := . . ., // Axis

ai
commandId := myID); // Specification of number

RetVal := _removeBufferedAxisCommandId(// Delete CommandId

SIMOTION
axis := . . .,

Siemens AG 2013. All rights reserved.


// Axis

gm
removeMode := SPECIFIC_ID, // Specific ID or all IDs
commandId := myID);

Date:
File:
10.01.2013
MC-SMO-PROG_04.18
SITRAIN Training for
Automation and Drives
@
CommandId To determine the status of a specific command once it has been executed, you
buffer must buffer the corresponding CommandId in the technology object.
Within each TO there is a buffer for long-term storage of the CommandIds. The
size of this buffer can be specified using the configuration data item:
er

• <TO>.TypeOfAxis.DecodingConfig.NumberOfMaxBufferedCommandid
ez

Buffer The _bufferAxisCommandid() function is used to save the CommandId in the TO


CommandId so that the corresponding command status can be checked beyond the
execution time of the command.
With this command, as of V3.2, you must specify whether or not the
CommandIds buffered in the axis TO should be deleted in the event of an axis
r.s

reset.
The command completion status (e.g. EXECUTED or ABORTED) then remains
available even after the command has been executed.
ne

Delete The _removeAxisCommandid() function is used to delete the CommandId in the


CommandID TO and thus the corresponding command status along with it.
The removeMode parameter is used to specify the mode.
With SPECIFIC_ID, the specified CommandId and its command status are no
longer available once the command has been completed. With ALL_ID, all
ca

CommandIds and their command status are no longer available once the
command has been completed.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 Programming motions of axes
Evaluating the motion status with the CommandId
Var
myID : commandIdType; // commandidtype
myStateOfMotion: StructRetMotionCommandState;
End_var

myID := _getCommandId(); // Assignment of a free number

om
RetVal := _pos(
axis := axis_blue, // Axis
. . .,
commandId := myID); // Specify CommandId

myStateofMotion:= _getMotionStateofAxisCommand(

l.c
axis := Axis_1, // Axis
commandId := myID); // Specify CommandId

RetVal: NOT_EXISTENT: CommandId not known

ai
BUFFERED: Command is in the command queue
IN_EXECUTION: Command is being executed
IN_ACCELERATION: In acceleration phase
IN_CONSTANT_MOTION: In constant motion phase

SIMOTION
IN_DECELERATION:
AXIS_HOMED:
INTERPOLATION_DONE:

Siemens AG 2013. All rights reserved.


gm
In deceleration phase
Axis synchronized
Setpoint interpolation is complete

Date:
File:
10.01.2013
MC-SMO-PROG_04.19
SITRAIN Training for
Automation and Drives
@
_getMotionstate This function returns the current phase of a command execution. The return
ofAxisCommand() value is a structure of the type StructRetMotionCommandState with the
following elements:
• functionResult: DINT, for status see online help for _move()
er

• motionCommandIdState:
- NOT_EXISTENT: CommandId not known or command already
completed.
ez

- BUFFERED: Command is in the command queue.


- IN_EXECUTION: Command is being executed.
- IN_ACCELERATION: The motion generated by the command is in the
acceleration phase.
r.s

- IN_CONSTANT_MOTION: The motion generated by the command is in


the constant motion phase.
- IN_DECELERATION: The motion generated by the command is in the
deceleration phase.
ne

- AXIS_HOMED: Axis synchronized.


- INTERPOLATION_DONE: The setpoint interpolation of the command
is completed.
- EXECUTED: Execution of the command has been completed.
- ABORTED: Execution of the command has been aborted.
ca

Note The last two return values are only available if the CommandId is explicitly
buffered inside the TO.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 Programming motions of axes
Evaluating the motion status with system variables

System variable: motionStateData

motionstate ACCELERATING CONSTANT_MOVE DECELERATING STANDSTILL

om
l.c
ai
motioncommand IN_MOTION END_OF_INTERPOLATION MOTION_DONE

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.20
SITRAIN Training for
Automation and Drives
@
MotionStateData The status of a motion command and the corresponding motion can be
monitored with the TO system variable motionStateData. motionStateData is
structured as follows:
• motionStateData
er

- motionState "Status of axis motion"


Data type: EnumAxisMotionState
- motionCommand "Status of a motion command"
ez

Data type: EnumAxisMotionCommand


- stillStandVelocity "Velocity-related standstill signal"
Data type: EnumActiveInactive
- actualVelocity "Actual velocity of the axis"
Data type: LREAL
r.s

- actualAcceleration "Actual acceleration of the axis"


Data type: LREAL
- commandVelocity "Set velocity of the axis"
Data type: LREAL
ne

- commandAcceleration "Set acceleration of the axis"


Data type: LREAL
The structure elements for motionStateData indicate the dynamic status of the
axis and the actual values (interpolator).motionstatedata.actualvelocity and
motionstatedata.actualacceleration are mean values (IPO cycle clock). The
ca

actual acceleration is numerically determined from the changes in the actual


velocity.
When motionCommand = END_OF_INTERPOLATION, positioning monitoring
is starting or is active.
When motionCommand = MOTION_DONE, standstill monitoring for position
axes is starting or is active. For drive axes, motion is completed.
stillStandVelocity = ACTIVE indicates that the axis is stationary or lies within the
standstill velocity set for the configuration.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 Programming motions of axes
Stop of an axis

RetVal := _stop(
axis := . . ., // Axis
. . ., //
stopMode := STOP_AND_ABORT, // Stop behavior
stopSpecifcation := ALL_AXIS_MOTION, // Basic or superimposed
stopId := _getcommandid()); // Command ID

om
stopMode:
STOP_AND_ABORT Normal stop with abort
STOP_WITHOUT_ABORT Normal stop without abort

l.c
stopSpecification:
All_AXIS_MOTION Effective on all active motions
BASIC_MOTION Is effective on the basic motion of the axis

ai
SUPERIMPOSED_MOTION Is effective on the superimposed motion of the axis
SPECIFIC_AXIS_MOTION Is effective on a specified motion of the axis

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.21
SITRAIN Training for
Automation and Drives
@
Stop axis The command stops the axis moving. It can be used for both positioning and
Normal stop drive motions.
With a normal stop, the motion is decelerated along the parameterized
deceleration ramp.
er

STOP_AND_ABORT: The motion cannot be continued.


STOP_WITHOUT_ABORT: Motion can be continued with the _continue()
command. For proper function, no other commands can be issued to the axis
between the stop command and the continue command.
ez

It is also possible to specify which motion should be stopped:


• All motion
• Basic motion
• Superimposed motion
r.s

• Motion identified with the StopID parameter

The function resumes all motion or some motion of the specified axis if it was
_continue() stopped with _stop() and STOP_WITHOUT_ABORT in the stopMode parameter.
ne

The motion or part motion that is continued with the command is specified at the
continuespecification parameter:

• ALL_AXIS_MOTION: Effective on all active motions


• BASIC_MOTION: Effective on basic motion
ca

• SPECIFIC_AXIS_MOTION: Effective on the specified motion Parameter


continueID
• SUPERIMPOSED_MOTION: Effective on superimposed motion

When continuing a motion, the dynamic parameters (e.g. velocity profile,


acceleration) of the interrupted command are used.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 Programming motions of axes
Emergency stop of an axis

RetVal := _stopEmergency(
axis := . . ., // Axis
. . ., //
stopDriveMode := STOP_IN_DEFINED_TIME, // Stop behavior
stopTime := 1.0); // Default time

om
stopDriveMode:
STOP_IN_DEFINED_TIME Stop axis with a time-defined ramp
STOP_WITH_MAXIMAL_DECELERATION Stop axis with maximum deceleration

l.c
STOP_WITH_COMMAND_VALUE_ZERO Stop axis with setpoint zero
STOP_WITH_DYNAMIC_PARAMETER Stop axis with dynamic parameters

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.22
SITRAIN Training for
Automation and Drives
@
Emergency stop This function stops the axis with a programmable stop mode. If a motion
command is active, it is aborted and cannot be continued with a _continue()-
command. The axis is not switched to follow-up mode. It remains in position
control. The axis is blocked for further motion commands; the state can be
er

revoked with _resetAxis () or _disableAxis ().

Parameter Quick stop within defined period: The motion is stopped by the interpolator
based on the instantaneous set position within the parameterized time frame
ez

(parameter: stopTime). The stop ramp is defined based on the instantaneous


velocity so that the axis stops within the defined time.
Quick stop with velocity setpoint 0: Motion is stopped along the emergency stop
ramp (dialog: "Limits", tab "Position and velocity", parameter "Emergency stop
deceleration").
r.s

This type of quick stop should only be used for axes that run without precontrol,
i.e. conventionally with following error. With this type of stop, initially, the set
position of the interpolator is counted back by the (following error) distance
resulting from the instantaneous velocity and the time constant
dynamicData.positionTimeConstant. Based on the set position counted back,
ne

the interpolator decelerates the axis along the emergency stop ramp.
In this case, the emergency stop ramp must be dimensioned like the actual
braking ramp of the axis at speed setpoint 0. This is the only way to ensure that
the axis stops with velocity setpoint 0.
ca

Quick stop with maximum deceleration: Motion is stopped by the interpolator


based on the instantaneous set position with the max. dynamic values (dialog
"Limits", tab "Dynamic response", parameter "Acceleration").
Quick stop with dynamic parameters: The axis is stopped by the interpolator
based on the instantaneous set position with the dynamic values specified in the
command.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 Programming motions of axes
Resuming a stopped motion

RetVal := _continue(
axis := . . ., // Axis
continueSpecification := BASIC_MOTION, // Basic or superimp,..
continueId := _getcommandid(), // Command ID
nextCommand:=IMMEDIATELY, //
commandId:= . . .,

om
);

l.c
continueSpecification:
All_AXIS_MOTION Effective on all active motions
BASIC_MOTION Is effective on the basic motion of the axis
SUPERIMPOSED_MOTION Is effective on the superimposed motion of the axis

ai
SPECIFIC_AXIS_MOTION Is effective on a specified motion of the axis

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.23
SITRAIN Training for
Automation and Drives
@
Resume a stopped
motion command This function continues the entire motion or a partial motion of the specified axis,if it
was stopped with the _stop() command using STOP_WITHOUT_ABORT in the
'stopMode' parameter.
er

Continuation of a partial motion is specified using the 'commandId' or the type of


motion. When continuing a motion, the dynamic parameters (e.g. velocity profile,
Parameter acceleration) of the interrupted command are used.
ez

axis (posAxis): Specification of the axis


continueSpecification (EnumRedefineieSpecification): Setting of the assignment for the
specified motion commands
r.s

• ALL_AXIS_MOTION: Effective on all active motions


• BASIC_MOTION: Effec@tive on basic motion
• SPECIFIC_AXIS_MOTION: Effective on the specified motion Parameter
continueID
ne

• SUPERIMPOSED_luMOTION: Effective on superimposed motion continueID:


Motion identified with that parameter
nextComomand: IMMEDIATELY or WHEN_COMMAND_DONE commalndId: as above
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 Programming motions of axes
Setting and shifting the coordinate system

RetVal := _redefinePosition(
axis := . . ., // Axis
redefineSpecification := COMMAND_VALUE, // Setpoint, act. value,..
redefineMode:=ABSOLUTE, // Absolute, relative
position:=0.0, // Offset
velocity:=0.0, // Dynamic data only

om
acceleration:=0.0, // relevant for virtual
nextCommand:=IMMEDIATELY, // axis
commandId:= . . .,
);

l.c
redefineSpecification:
COMMAND_VALUE // Set position is set or offset to position
ACTUAL_VALUE // Actual position is set or offset to position
VIRTUAL_AXIS // Position and dynamic data for a virtual axis are set,

ai
// become effective next time the virtual axis is started
redefineMode:
ABSOLUTE

SIMOTION
Siemens AG 2013. All rights reserved.
gm
// Actual or set position set to absolute value RELATIVE
// Actual or set position offset by position

Date:
File:
10.01.2013
MC-SMO-PROG_04.24
SITRAIN Training for
Automation and Drives
@
Coordinate system: The _redinePosition() function sets the coordinate system of an axis to
set/offset a new value. The position value can be defined as an absolute value or
as a relative position offset. The setpoint or the actual value can be set to a
defined position. The other value is adjusted taking the current following error
er

into account.
The setting of the coordinate system only affects the programmed axis
positions. The software limit switches, whmich are defined by homing, stay in
their original positions.
ez

With a virtual axis, the setpoints for ievelocity and acceleration can be set in
addition to the set position. The values for position, velocity, and acceleration
are used as starting values for s the next motion command, i.e. they are
included when starting a motion command at the virtual axis.
r.s

axis (posAxis): Spec ification of the axis


Parameter redefineSpecificatuion (EnumRedefineSpecification): Setting of the assignment
for the specified poslition
• COMMAND_VALUE: Assignment to the position setpoint of the
axis
ne

• ACTUAL_VALUE: Assignment to the actual position value of the


axis
• VIRTlUAL_AXIS: Assignment to the position setpoint of a virtual
axis redefineeMode (EnumRedefineMode)
• ABSOLUTE: Assignment as absolute value
ca

• RELATIVE: Specification of relative value, i.e. the value is added


to the instantaneous position (offset). Important after taking measurements.
position (LREAL): Specification of value
velocity (LREAL): Only evaluated if redefineSpecification = VIRTUAL_AXIS
acceleration (LREAL: only if redefineSpecification = VIRTUAL_AXIS
nextCommand: IMMEDIATELY or WHEN_COMMAND_DONE
commandId: as above

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 Programming motions of axes
Reset axis TO

RetVal := _resetAxis(
axis := . . ., // Axis
userDefaultData := ..., // Reset user data?
activateRestart := ..., // Restart TO?
nextCommand:=, // Synchronous, asynchronous?
commandId:= . . .,

om
);

usedefaultData:

l.c
ACTIVATE_CONFIGURATION_DATA Set user default values to the configured values
DO_NOT_CHANGE No resetting of the user default values

activateRestart:
NO_RESTART_ACTIVATION Do not execute a technology object restart

ai
ACTIVATE_RESTART Execute a technology object restart

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.25
SITRAIN Training for
Automation and Drives
@
Reset axis The _resetAxis() command places the axis in a defined initial state. The
following actions are carried out with the axis in this state:
• All active motions are stopped with the emergency stop ramp.
er

• Commands in the motion buffer and commands pending at the motion buffer
are deleted; synchronous commands are aborted. The Command aborted
technology alarm is suppressed.
• Optionally, the axis can be restarted using a function parameter in the
ez

command.
• The command is executed synchronously as normal.
• The command can also be executed asynchronously (as of V3.1).
• Pending errors on the axis are reset. The command is terminated with a
r.s

negative acknowledgment if any errors occur that must not be


acknowledged at this point.
• Any system variables changed by the program are reset to the configured
values upon request. Actual values are retained.
• The homing status is retained in the absence of a restart.
ne

Restart When restart is activated on the technology object with the activateRestart
parameter, the technology object performs a restart.
• An active motion on the axis is aborted without error messages or similar.
ca

• The actual value system of the axis and, thus, the homing status, are reset.
• All commands on the axis are aborted.
• All connections to other technology objects are terminated and re-
established.
• The _resetAxis() command stops any synchronous operation command that
is in effect on this axis. The synchronous operation TO on the synchronous
axis is not reset.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 25 Programming motions of axes
Acknowledging errors on the axis TO

RetVal := _resetAxisError(
axis := . . ., // Axis
errorResetMode := ..., // All errors, spec. error?
errorNumber := ..., // Error number
nextCommand:=, //
commandId:= . . .,

om
);

errorResetMode:

l.c
ALL_ERRORS Reset all errors
SPECIFIC_ERROR Reset selected error

ALL_ERRORS resets all errors.


SPECIFIC_ERROR resets the error specified in 'errorNumber'.

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_04.26
SITRAIN Training for
Automation and Drives
@
Acknowledge error The _resetAxisError() function resets a specified error or all errors on the axis.
The command is terminated with a negative acknowledgment if any errors occur
that must not be acknowledged at this point.
er

The command is asynchronous. The command can also be issued


synchronously (as of V3.1). If necessary, the error is not reset until the local
reaction triggered by the error has been compeleted.
Read out
ez

error status The _getAxisErrorNumberState() command mis used to read the status of
a specific error on the axis. The function returns the status (pending, not
pending) of the error specified with the error number (DINT) in its return value.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 26 Programming motions of axes
Reading out errors on the axis TO

MyRetStructRetGetToError := _getAxisErrorState
axis := . . . // Axis
);

om
StructRetGetToError:
StructRetGetToError STRUCT
functionResult; // (DINT) Result of call
errorState; // Yes or No
numberOfErrors; // Number of errors
error1; // Error number 1. Error

l.c
error1Parameter1 // Add. info. 1 for error 1
error1Parameter2 // Add. info. 2 for error 1
...
error1Parameter5 // Add. info. 5 for error 1
...

ai
Error8 // Add. info. 1 for error 8
error8Parameter1 // Add. info. 2 for error 8
...

SIMOTION
error8Parameter5
END_STRUCT

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
// Add. info. 5 for error 8

MC-SMO-PROG_04.27
SITRAIN Training for
Automation and Drives
@
Read out error The _getAxisErrorState() function is used to read out the status of up to eight
on axis TO alarms on an axis TO. The function returns whether any alarms are pending on
the axis in the errorState return value and if so how many in numberOfErrors.
Additional information is also returned for these alarms. The additional
er

information (error3Parameter4, for example) is returned in the return value as


LREAL values.
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 27 Programming motions of axes
Enable axis command
RetVal := _enableAxis(
axis := . . ., // Achse
enableMode:= ALL // All, DRIVE, POWER, BY_STW_BIT,
servoControlMode := ACTIVE, // ACTIVE, INACTIVE
servoCommandToActualMode:=INACTIVE,// ACTIVE, INACTIVE
nextcommand := . . ., // IMMEDIATELY, WHEN_COMMAND_DONE
commandId := . . ., //

om
forceControlMode := INACTIVE, // ACTIVE, INACTIVE
STWBitSet := . . ., // Bits (UINT) für STW1
movingMode := DO_NOT_CHANGE // POSITION_Controlled, SPEED_Co…
);

l.c
enableMode:
ALL // position controller and drive + power is enabled
DO_NOT_CHANGE // no changes
DRIVE // switch only drive enable
POWER // switch on power enable

ai
BY_STW_BIT // the bits in "STWBitSet" are set according to the PROFIdrive-state machine
STATE_MACHINE_CONTROL_BY_APPLICATION // the bits in "STWBitSet" are set
servoControlMode:
ACTIVE
INACTIVE

SIMOTION
Siemens AG 2013. All rights reserved.
gm
// set value path between IPO and position controller is enabled
// set value path between IPO and position controller is disabled

Date:
File:
10.01.2013
MC-SMO-PROG_04.28
SITRAIN Training for
Automation and Drives
@
Switch axis This function switches the axis enables. If not all enables are set, the axis will
enables switch to the following-up mode. The following enable modes can be set. via the
"enableMode" parameter:
ALL: Enable drive and power. This is necessary for a movement initiated by a
er

TO movement command. .
DO_NOT_CHANGE: the current specified setting for the enable mode are not
changed. The axis will remain in the following-up mode, if not all enable signals
are applied.
ez

DRIVE: The drive enable is switched on, the power enable state is not changed.
POWER: The power enable state is switched on, the drive enable state is not
changed.
BY_STW_BIT: the bits specified in 'STWBitSet' are set according to the
r.s

PROFIdrive protocol. A check of the bits according to the PROFIdrive state


machine is internally performed by the command.
STATE_MACHINE_CONTROL_BY_APPLICATION: The evaluation of the bits
must be performed by the user program. The command will simply set the
specified bits in the control word. No internal evaluation of the bits is performed
ne

by the command, whether the exchanged information is compliant with the


PROFIdrive state machine. By means of this setting, also non PROFIdrive
compliant drive systems can be switched on..
ca

ServoControlMode Via the "sevoControlMode" parameter the passing of the setpoint value from the
interpolator to the position controller can be enabled /disabled.
ACTIVE: The passing of the setpoint value from the interpolator to the position
controller is enabled. This setting is also necessary for a peed controlled
movement of an electrical axis.
INACTIVE: The passing of the setpoint value is disabled. The axis can only be
moved via the sepoint superimposition "servosettings.additionalSetPointValue",
e.g. generated by the internal function generator.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 28 Programming motions of axes
Disable axis command

RetVal := _disableAxis(
axis := . . ., // Axis
enableMode:= ALL // All, DRIVE, POWER, BY_STW_BIT,
servoControlMode := ACTIVE, // ACTIVE, INACTIVE
servoCommandToActualMode:=INACTIVE,// ACTIVE, INACTIVE
nextCommand := . . ., // IMMEDIATELY, WHEN_COMMAND_DONE

om
commandId := . . ., //
forceControlMode := INACTIVE, // ACTIVE, INACTIVE
) );

servoCommandToActualMode

l.c
ACTIVE // following-up mode is activated, the axis can be moved externally
INACTIVE // following-up is deactivated, the movement of the axis is controlled by the
// position controller
forceControlMode

ai
INACTIVE // force / pressure controller is deactivated
ACTIVE // force / pressure controller is activated
movingMode:
POSITION_CONTROLLED
SPEED_CONTROLLED
DO_NOT_CHANGE

SIMOTION
Siemens AG 2013. All rights reserved.
gm
// for position –and speed controlled movement
// only for speed controlled movement, also works when the encoder fails
// no changes

Date:
File:
10.01.2013
MC-SMO-PROG_04.29
SITRAIN Training for
Automation and Drives
@
Following-up mode The axis can be switched to the following-up mode by the parameter
"servoCommandToActualMode" :
ACTIVE: Following-up mode is active. No motion commands are executed, the
movement of the axis is not controlled by SIMOTION. An axis has to be
er

switched to the following-up mode, when the movement is generated externally,


e.g. the mechanical fixing of the material inside a press. In this moment the
press infeed must not work against the mechanical fixing procedure, so during
that time the axis of the press infeed must be switched to the following-up mode.
ez

In the following-up mode the command position is set equal to the actual
position of the axis, i.e. the command position will follow the actual position.
INACTIVE: The standard control mode is active, the movement of the axis is
controlled by SIMOTION. The internal mechanism in the following-up mode
r.s

ensures, that an axis can be switched without any jump on the output of the
position controller from the following-up mode to the standard control mode. If
not all enable signals are applied, the axis will remain in the following-up mode.

Force / pressure Only for axis with a configured forse- or pressure controller:
ne

control ACTIVE: The force pressure controller is enabled


INACTIVE:.The force pressure controller is disabled

movingMode An axis can be enabled for position- and speed controlled movements or only for
ca

speed controlled movements.


POSITION_CONTROLLED: The axis is enabled for position- and speed
controlled movements.
SPEED_CONTROLLED: The axis is only enabled for speed controlled
movements. In this mode, the axis can also be moved when the position
encoder fails an no further error reaction is active.
The last active mode is retained, when the setting DO_NOT_CHANGE is
applied.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 29 Programming motions of axes
Libraries in SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_05.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Libraries in "CAM" ............................................................................................................................ 2
The PLCopen function library ........................................................................................................... 3
er

Example: Enable axis (_MC_Power) ............................................................................................... 4


Example: Relative positioning of axis (_MC_MoveRelative) ............................................................. 5
Example: Traverse axis in jogging _FB_Axis_jogPos ....................................................................... 6
ez

Creating custom libraries .................................................................................................................. 7


Block programming in libraries ......................................................................................................... 8
Exporting and Importing libraries ...................................................................................................... 9
Integrating libraries in a custom project ............................................................................................ 10
r.s

Integrating libraries in the user program ........................................................................................... 11


ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 Libraries in SIMOTION
Libraries in "CAM"
• PLCopen library
• PLCopen single axis blocks
• PLCopen multi-axis blocks
• Block for jog
• Controller + I/Os + Drives

om
• Basic control (continuous PID,
PI step controller, pulse width modulation)
• Integration: Communication
processors CP340, CP341
• Integration: Serial interface module

l.c
ET200S
• Integration of FM350-1, FM350-2, FM352
• Control of SIMODRIVE POSMO A

ai
FBs areare designed solely for use in
cyclic tasks (BackgroundTask,
TimerInterruptTask, etc.)

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_05.2
SITRAIN Training for
Automation and Drives
@
Libraries As of V4.0, the "MotLib" and "SysLib" function libraries, which were shipped on a
separate CD in previous versions, are included in the CAM technology package.
Drag-and-drop operations can now be used to move the corresponding library
blocks directly from the command library to the user program like other system
er

functions.

PLCopen This file contains the PLCopen-compliant motion control blocks and an
additional block for implementing JOG traversing for axes. As well as the single
ez

axis blocks, the library also contains the multi-axis blocks for gearing and
camming.
The blocks in the motion control library contain blocks for controlling speed-
controlled axes, position axes, and following axes. The function blocks (FBs)
have been designed by PLCopen for compliance with the language elements for
r.s

standard IEC 61131-3.


The PLCopen-compliant function blocks form an open software interface
between the user program and the SIMOTION system.
ne

Controller + I/Os In addition to the conventional closed-loop control blocks, in particular, this block
+ Drives contains blocks for the integration of various modules (ASI, Ident systems, CP
modules) and drives (SIMODRIVE POSMO A) in a SIMOTION overall system.

Documentation A description of the library blocks is included in the SIMOTION SCOUT online
ca

help.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Libraries in SIMOTION
The PLCopen function library
Single axis blocks compliant with PLCopen
• _MC_Power (Enable and disable axis)
• _MC_Stop (Stop axis)
• _MC_Home (Home axis)
• _MC_MoveAbsolute (Absolute positioning)
• _MC_MoveRelative (Relative positioning)
• _MC_MoveVelocity (Move axis speed or position- controlled)
• _MC_MoveAdditive (Position axis relative to target position)

om
• _MC_MoveSuperImposed (Position axis superimposed)
• _MC_VelocityProfile (traverses an axis along a velocity profile)
• _MC_ReadActualPosition (Read out actual position)
• _MC_ReadStatus (Read out axis status information)
• _MC_Reset (Reset an axis to the basic state)
• _MC_ReadParameter (Read axis parameter)

l.c
• _MC_ReadBoolParameter (Read parameter of type BOOL)
• _MC_WriteParameter (Write axis parameter)
• _MC_WriteBoolParameter (Write parameter of type BOOL)
Multi-axis blocks compliant with PLCopen
• _MC_CamIn (start camming operation between master and following axis)

ai
• _MC_CamIn (stop camming operation between master and following axis)
• _MC_GearIn (start gearing)
• _MC_GearOut (terminate gearing)

SIMOTION
• _MC_Phasing (incorporate additional phase)
JOG block
• _MC_Jog

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_05.3
SITRAIN Training for
Automation and Drives
@
FB instances The motion control function blocks (their interface (parameters), functionality,
and sequence) are implemented according to the PLCopen specification.
Thanks to this standardization, once acquired, motion control knowledge can be
applied directly in the SIMOTION user program.
er

The function blocks for triggering motion control jobs are integrated in the user
program in the usual way. If a single block is to address multiple axes in a
program, for example (e.g. axis enables with the "MC_Power" block), a separate
FB instance must be created for each axis as follows:
ez

• For axis 1 the FB instance: “Axis_1_enable”


• For axis 2 the FB instance: “Axis_2_enable”
Usually, in a cyclic task like the BackgroundTask, for example, each instance of
a block is called just once.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Libraries in SIMOTION
Example: Enable axis (_MC_Power)

_MC_Power
Axis_Ref Axis Status BOOL
BOOL Enable Busy BOOL
_MC_EnableMode Mode Active BOOL

om
_MC_StopMode Stop mode Error BOOL
_MC_ Disablemode Disable mode ErrorID WORD
WORD STWBitSet StatusMode BOOL

l.c
Enable: TRUE = Set axis enable Disable mode
FALSE = Reset axis enable ALL (remove position controller + drive enable)
Mode: ALL (position controller + drive) DRIVE (drive enable retained)
DRIVE (drive enable) BY_STW_BIT (remove bits)

ai
BY_STW_BIT (define bits) Status: TRUE = Axis is enabled
Stop mode FALSE = Axis is not enabled
WITH_COMMAND_VALUE_ZERO StatusMode
WITH_MAXIMAL_DECELERATION

SIMOTION
IN_DEFINED_TIME
DISABLE_DRIVE_IMMEDIATELY

Siemens AG 2013. All rights reserved.


gm
TRUE = Actual enable same as setpoint enable
FALSE = Act. enable not same as setpoint enable

Date:
File:
10.01.2013
MC-SMO-PRG_05.4
SITRAIN Training for
Automation and Drives
@
Description The function block _MC_Power enables or disables an axis or an external
encoder. The enable is controlled statically with the input enable =TRUE from
the user program. A falling edge at the enable input removes the enable.
In addition, the mode parameter can be used to specify whether just the drive
er

enable (DRIVE), the position controller and the drive enable, or the individual
bits of the control word are switched to PROFIdrive.

As of V4.2, the block has been expanded with the addition of the STWBitSet
ez

input parameter. The STWBitSet parameter is only evaluated if the value


BY_STW_BIT is transferred in the ieMode parameter.
The stopMode parameter can be used to specify the type of deceleration if
active braking (remove enable when axis is moving) is required prior to the axis
r.s

being disabled. In this case, the stop mode is activated on a falling edge at the
enable input. The stop@ modes are identical to those of the _stopEmergency
system function.

The status output indicates whether the axis is also enabled according to the
ne

enables specified in mode (status = TRUE) or not (status = FALSE). The busy
parameter indicates whether or not the FB is currently in progress. The active
parameter indicates whether or not a motion control job is currently in progress
at the TO.
The error parameter indicates an error. TRUE means that an error has occurred
ca

during the initialization of the function block. The function block is terminated.
The error description can be read at the errorId output.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Libraries in SIMOTION
Example: Relative positioning of axis (_MC_MoveRelative)

_MC_MoveRelative
Axis_Ref Axis Done BOOL
BOOL Execute Busy BOOL
LREAL

om
Distance Active BOOL
LREAL Velocity CommandAborted BOOL
LREAL Acceleration Error BOOL
LREAL Deceleration ErrorID WORD
LREAL Jerk

l.c
Enable: The traversing block FB is sent to CommandAborted
the TO on a rising edge Indicates that processing of the job has been

ai
Done: TRUE = Motion completed aborted (e.g. due to an overriding command)
successfully Error: Error in block (e.g. job rejected by TO,
Busy: TRUE = FB started error during parameter assignment)
Active: TRUE = Job currently being

SIMOTION
processed at TO

Siemens AG 2013. All rights reserved.


gm
Date:
File:
ErrorID: Error specification

10.01.2013
MC-SMO-PRG_05.5
SITRAIN Training for
Automation and Drives
@
Description The function block _MC_MoveRelative positions an axis relative to the actual
position of the axis. The processing of the FB starts on a rising edge at the
execute input. If the axis is already in motion when the job is started, the job in
progress is overridden and the position that is present in the system at the start
er

of job processing is used as the start position.


Moreover, when calling the FB, the dead time between the point when
processing of the function block starts, the sending of the motion job, and the
start of motion, which has been programmed by the task in the function block
ez

and which depends on the set interpolation cycle clock, must be taken into
account.
The dynamic parameters velocity, acceleration, deceleration, and jerk define the
dynamic response of the motion procedure. If a value greater than zero is
specified, this value is used. If -1.0 is specified, the value that was preset in the
r.s

axis system variable userdefaultdynamics.velocity, etc., is used. The axis stops


after completion of the positioning motion.
Successful termination of the motion is signaled via the parameter done. The
busy parameter indicates whether or not the FB is currently being processed.
The active parameter indicates whether or not a motion control job is currently in
ne

progress at the TO.


The commandAborted parameter indicates that the job that was active originally
(_MC_MoveRelative) has been aborted (e.g. error at TO, override by other MC
command, etc.). The error parameter signals a synchronous error (e.g. error
ca

during parameterization, job rejected by TO, etc.).


In both cases, a detailed error specification is returned at the errorId output.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Libraries in SIMOTION
Example: Traverse axis in jogging _FB_Axis_jogPos

_MC_Jog

PosAxis Axis Done BOOL


BOOL Enable Busy BOOL
BOOL Forward Active BOOL
Backward

om
BOOL CommandAborted BOOL
BOOL ModeInc Error BOOL
LREAL Increment ErrorID DWORD
LREAL Velocity
LREAL Acceleration
LREAL Deceleration
LREAL Jerk

l.c
Enable: Block enable
Forward: Start/stop motion in positive direction

ai
Backward: Start/stop motion in negative direction
ModeInc: Operating mode: FALSE (continuous mode), TRUE (incremental mode)
Increment: Specification of path (only relevant if modeInc = TRUE)

SIMOTION
...

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_05.6
SITRAIN Training for
Automation and Drives
@
Description The function block traverses the axis with the parameterized dynamic response
values either continuously (modeInc = FALSE) or incrementally (modeInc =
TRUE) in a positive or negative direction. A positive edge at the forward or
backward input parameters starts traversing; a negative edge stops traversing.
er

When incremental jogging is selected, the axis is stopped by the function block
after traversing the parameterized distance. If the axis is stopped before
completing the parameterized distance due to a negative edge, the remaining
distance is completed when traversing is restarted. Therefore, when incremental
ez

jogging is selected, the direction can only be changed when there is no


remaining distance to be traversed.
. If both direction bits are set to TRUE, the motion in progress is stopped with the
defined deceleration.
r.s

In incremental mode, done signals that the specified distance has been
completed successfully. In continuous mode, the done output is set to TRUE
once the axis has stopped. The busy parameter indicates whether or not the FB
is currently being processed. The active parameter indicates whether or not a
motion control job is currently active at the TO.
ne

The commandAborted parameter indicates that the job that was active originally
has been aborted (e.g. error at TO, override by other MC command, etc.). The
error parameter signals a synchronous error (e.g. error during parameterization,
job rejected by TO, etc.).
In both cases, a detailed error specification is returned at the errorId output.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Libraries in SIMOTION
Creating custom libraries

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_05.7
SITRAIN Training for
Automation and Drives
@
Creating User libraries are created in exactly the same way as programs. However,
libraries you do not need to insert hardware in the project. The name must be unique
throughout the project.
In the Properties dialog box for the library, you need to specify which SIMOTION
er

devices and which technology packages you want the library to be executable
for. When you compile the library, the data required in the kernel is generated
for each device you have specified.
A library has the property "original name". When the library is created, this name
ez

is taken automatically from the name you specified. The library can still be
identified by this original name even after the library name has been changed.
If the configured SIMOTION devices and their technology packages do not
Note match the properties specified in the library, an error is output when the project
r.s

is compiled/checked for@ consistency and the project cannot be downloaded to


the target device.
To create a library, proceed as follows:
Creating a library 1. In the project navigator, go to the "LIBRARY" folder and double-click
ne

"Insert library". The dialog window for creating a library is displayed.


2. Enter the name of the library on the "General" tab.
3. One the "TPs/TOs" tab, check the boxes for:

– The relevant device types (D425-2, etc.) with corresponding firmware on


ca

which the library blocks are to be used


– The relevant technology packages that can be downloaded to the selected
target devices

4. If necessary, make the settings for the local compiler on the "Compiler" tab
5. Click "OK" to confirm your settings. The library is inserted in the
. project navigator.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Libraries in SIMOTION
Block programming in libraries
Blocks can be created in MCC, LAD, and ST
• However, a debug function is not available
• Blocks are created and tested in the PROGRAMS folder first and then
copied to the library
All commands except the following can be used:

om
• Old task control commands (e.g. _StartMotionTask(..), etc.)
• Old commands for runtime measurement of tasks
(e.g. _getMaximalTaskRunTime(..), etc.)
• Old commands for message programming (e.g. _alarms(..), etc.)

l.c
• System functions of SIMOTION devices, if the library is compiled
independently of the device
Prohibited variable accesses:
• I/O variables

ai
• Global device variables
• Instances of technology objects and their system variables

SIMOTION

independently of the device

Siemens AG 2013. All rights reserved.


gm
System variables of SIMOTION devices, if the library is compiled

Date:
File:
10.01.2013
MC-SMO-PRG_05.8
SITRAIN Training for
Automation and Drives
@
General Libraries usually provide you with user-defined data types, functions, and
function blocks for use by all SIMOTION device blocks within a project. Libraries
can be created in all programming languages. Conversely, blocks from libraries
can be used in all program sources (e.g. ST, MCC, LAD/FBD sources).
er

There are no test functions (functions, function blocks) for ST, LAD/FBD, or
MCC charts available in the LIBRARY folder. Accordingly, the blocks are usually
first created and tested within the PROGRAMS folder and then copied to the
library.
ez

The library with the individual ST source files/LAD programs/MCC charts and
the ST source files/LAD/FBD programs/MCC charts called by the blocks from
the library must use the same technology packages. If they do not, during
compilation and when carrying out the consistency check, an error message will
be generated and the project cannot be downloaded to the target system. In this
r.s

case, the technology package for the library has to be selected again on the
"TPs/TOs" tab in the Properties dialog and the library has to be compiled again.

Restrictions In libraries, all ST/LAD/FBD/MCC commands with certain restrictions (e.g. "old"
task control commands, commands for task runtime measurement, and
ne

commands for programming messages) can be used.


Moreover, variable access to I/O variables and global device variables is not
permitted.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Libraries in SIMOTION
Exporting and Importing libraries
Libraries can be exported and imported in an XML- Format. XML-
export and –import is is initiated from a SCOUT project

om
XML export

l.c
ai
SIMOTION
XML import

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_05.9
SITRAIN Training for
Automation and Drives
@
XML export Arbitrary libraries or other ST/LAD/MMC source files could be exported and
stored outside the project using the XML export functionality. The exported data
could be stored in an arbitrary directory of the file system in a version- and
platform independent way.
er

1. In the project navigator window select the desired library and open the
short cut menu.
2. In the short cut menu select the entry "Expert -> Save project and export
object". The browser for the target direcmtory is opened.
ez

3. Select the directory for the XMLe data export and confirm your settings
via the "OK" button. The data export is istarted. Export information is displayed in
the detailed window of the SIMOsTION SCOUT screen.
r.s

Note If you export in XML format, the libraries or sources are exported in an
encrypted form. When importing the encrypted XML files, the know-how
protection, including log in and password, is retained.
Libraries which were exported in the XML format can also be imported in
XML import an arbitrary SIMOTION project.
ne

1. Select the "LIBRARIES" folder and open the short cut menu.
2. Select the "Import object" entry. A browser dialog is opened.
3. Navigate to the desired XML file of the exported library and confirm
the settings via the OK button.
ca

The library is imported into the project and stored under the "LIBRARIES"
folder.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Libraries in SIMOTION
Integrating libraries in a custom project

om
1. Open library

3. Object properties:
Select target devices

l.c
2. Copy + paste or
export, import xml
4. Save and compile

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_05.10
SITRAIN Training for
Automation and Drives
@
Library In the highest hierarchy of the project navigator, SIMOTION SCOUT supports
an option to create/save user and standard libraries for user-defined data
types, UNIT variables, functions (FC), and function blocks (FB) in the
"LIBRARY" folder. This folder can contain any number of libraries.
er

Libraries provide user-defined data types, unit evariables, functions and


Using function blocks which can be used by all SIMOTION devices.
libraries To enable the blocks, unit variables, and typesm from a library to be used in a
custom project, you first need to copy the library to the project and then
ez

compile it.

1. Start by opening two instancess of the SIMOTION SCOUT interface.


2. In the first instance of the SCOUT interface, open the desired library
(e.g. MyLib). Open the project in the second instance.
r.s

3. In the source project, select the required library and copy it to the
clipboard using the menu co mmand: Edit -> Copy.
In the target project, select the LIBRARIES folder and paste the copied library
to the target folder by with the menu command: Edit -> Paste.
4. Then select the library you have inserted in the destination folder and
ne

select the command: Object properties from the context menu.


In the "Object properties" dialog, go to the "TPs/TOs" tab and select the
SIMOTION devices and technology packages you are compiling the library for.
Confirm your entries by clicking "OK".
5. In the context menu, select the command: Save and compile. The
ca

library is compiled. Now you can use its blocks, etc., in the programs contained
in the project.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Libraries in SIMOTION
The SIMOTION execution system

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Automating technical processes ....................................................................................................... 2
The SIMOTION execution system .................................................................................................... 3
er

Task structure of the execution system (1) ........................................................................................ 4


Task structure of the execution system (2) ........................................................................................ 5
Servo_fast and IPO_fast on SIMOTION D435-2/D445-2/D455-2 ...................................................... 6
ez

Isochronous mode on PROFIBUS .................................................................................................... 7


Setting system cycle clocks .............................................................................................................. 8
Overview of user tasks ..................................................................................................................... 9
Assigning programs to tasks ............................................................................................................ 10
r.s

Task runtimes and task status (2) ..................................................................................................... 11


Task runtimes and task status (2) ..................................................................................................... 12
Task trace - Analyzing task runtimes ................................................................................................ 13
Task trace – Configuration via IT Diag .............................................................................................. 14
ne

Tasktrace – System command for control ......................................................................................... 15


Commands for processing tasks ....................................................................................................... 16
Commands for runtime measurement of tasks .................................................................................. 17
Commands for controlling tasks ....................................................................................................... 18
ca

Checking the state of a task in LAD/FBD .......................................................................................... 19


State model for tasks ........................................................................................................................ 20
Querying tasks: TaskStartInfo .......................................................................................................... 21
Waiting in a MotionTask using WAITFORCONDITION ..................................................................... 22
Declaration and use of an EXPRESSION ......................................................................................... 23
Synchronizing concurrent access: Semaphores ............................................................................... 24

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 The SIMOTION execution system
Automating technical processes

Motions/Part processes Tasks


„ Multitasking
„ Realtime

om
l.c
ai
SIMOTION
Machine/Plant

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
SIMOTION execution system

MC-SMO-PROG_06.2
SITRAIN Training for
Automation and Drives
@
Parallel processes In the automation of machines and other technical processes, it is often
necessary to monitor or control multiple part processes such as the motions of
machine axes at the same time. This is because most technical processes can
be split into multiple linked part processes that are executed at the same time.
er

Since such processes cannot normally be automated with a single, sequentially


executed program, a control system with multitasking capability is necessary to
provide solutions for these tasks.
ez

Multitasking = To maintain a clear overview, complex automation tasks are usually, in practice,
split into smaller function elements, which are then assigned to individual tasks.
Tasks, then, contain complete program units (POUs) and their associated data.
Tasks can be started and executed independently of each other, but must be
coordinated and communicate with to fulfill their common purpose.
r.s

Realtime If a process is to run continuously, the PLC’s associated execution system must
ensure that all necessary tasks are completed within the specified time.
Control systems used for automating technical processes always have their own
ne

temporal relationship with the process. The start of a processing operation is


usually the result of a signal from this process. If processing is not yet finished
or if the result of the process is not available on time, incorrect operation or loss
of control can result.
Many tasks depend not only on external events, but also on defined
ca

chronological sequences. Digital control algorithms, for example, must be


processed in cycles, whereby the algorithms are usually very sensitive to
variations in the cycle time.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 The SIMOTION execution system
The SIMOTION execution system

om
Servo level Pr
io
rit
y

IPO level ž
§

l.c
Timer level

ai
Interrupt level

Round robin level

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.3
SITRAIN Training for
Automation and Drives
@
Execution system The execution system of SIMOTION consists of individual execution levels,
which define the chronological sequence of programs in the execution system.
Each execution level contains one or more tasks for this purpose.
A task provides the execution framework for the user programs. One or a
er

number of programs can be assigned to a task. The order in which programs


contained by a task are executed can also be speceified. Programs written in ST
or MCC must, therefore, be assigned to one or more tasks to be executed.
In addition to these user tasks, several sysmtem tasks are also active. The user
cannot influence the content and of the system tasks or the order in which they
ez

are executed.
This execution system and the e sxecution levels contained therein allow motion
control tasks to be processed together with logic functions on one control
Motion control platform.
Time-controlled execu tion levels such as the IPO level and the TimerInterrupt
r.s

and logic
level usually provide the starting point for implementing motion control tasks and
technology functionsu.
Fast responsesg to process signals are covered by a ProcessInterrupt level. The
requirements of logic switching functions, as typically implemented by a PLC,
are usuaolly met by the round robin level.
ne

The exeecution system of SIMOTION operates like a multitasking system.


Because SIMOTION devices contain only one CPU, it is not possible to achieve
fully parallel processing of tasks. Therefore, structured execution of different
tasks is achieved through a permanently defined prioritization.
Scheduler The scheduler handles task control, specifying "traffic rules" for the operation of
ca

the tasks.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 The SIMOTION execution system
Task structure of the execution system (1)
Time-controlled System level or DP/PN comm. level
execution levels
High
T1 (DCC) task ServoSynchronousTask Servo task

T2 (DCC) task IPOSynchronousTask IPO task


T3 (DCC) task IPOSynchronousTask_2 IPO_2 task

om Priority
Temp. control

T4 DccAux task
Event-driven T5 DccAux task
execution levels Avera
SystemInterrupt ge
SystemInterrupt tasks
tasks

l.c
Wait For Condition

TimerInterrupt
TimerInterrupttasks
tasks

ai
UserInterrupt tasks

Freely executing Low


execution level
System startup, stop

SIMOTION
Siemens AG 2013. All rights reserved.
BackgroundTask

System startup
gm
Date:
File:
10.01.2013
MotionTasks
MotionTasks

System stop

MC-SMO-PROG_06.4
SITRAIN Training for
Automation and Drives
@
Priorities The execution system structures the chronological execution of programs in
SIMOTION. Tasks and the programs assigned to them are started and
executed at a certain time. If several tasks are to be started and executed at the
same time, the task priority determines which task will be executed first.
er

Servo task This task for axis position control has the hieghest priority. It is called and
processed at fixed intervals defined during system clock configuration.
As of V4.0 the user can assign custom prmograms to this execution level. In
ez

this case, the program has to be assigned eto the ServoSynchronousTask. In


the ServoSynchronous task you can impilement time-critical terminal-to-
terminal responses for I/Os or fast influencsing of setpoints at servo level.
DCC blocks assigned to runtim e group (time slice) T1 are executed at this
r.s

level. Execution precedes the user programs of the ServoSynchronousTask.

IPOTask The interpolation leve l has the next highest priority. In IPO-synchronous
tasks, you can implemenut time-critical functions that have a direct effect on the
functions of a telchnology object. The user program is executed before system
ne

interpolation,g i.e. the programmed system functions continue to affect the


same IPO cycle clock (e.g. fast start/stop of an axis) dependent upon an event.
As of V4l.1, blocks assigned to runtime group (time slice) T2 are executed at
this level. eExecution precedes the user programs of the IpoSynchronousTask.
ca

IPO_2Task
Ask well as the interpolation level there is a second interpolation level
(IPOSynchronousTask_2 or DCC time slice T3). While the IPO level is intended
for automating highly dynamic axes, the IPO2 level can be used for controlling
axes with less dynamic characteristics (auxiliary axes).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 The SIMOTION execution system
Task structure of the execution system (2)
Time-controlled System level or DP/PN comm. level
execution levels
High
T1 (DCC) task ServoSynchronousTask Servo task

T2 (DCC) task IPOSynchronousTask IPO task


T3 (DCC) task IPOSynchronousTask_2 IPO_2 task

om Priority
Temp. control

T4 DccAux task
T5 DccAux task
Avera
SystemInterrupt ge
Event-driven SystemInterrupt tasks
tasks

l.c
execution levels
Wait For Condition

TimerInterrupt
TimerInterrupttasks
tasks

ai
UserInterrupt tasks

Freely executing Low


execution level
System startup, stop

SIMOTION
Siemens AG 2013. All rights reserved.
Background Task

System startup
gm
Date:
File:
10.01.2013
MotionTasks
MotionTasks

System stop

MC-SMO-PROG_06.5
SITRAIN Training for
Automation and Drives
@
Temperature For temperature control in connection with the associated technology package,
control execution levels are available for actual value acquisition, control, and pulse
width modulation of the output signals.
er

T4 DccAux task/ As of V4.1, blocks assigned to runtime group (time slice) T4/T5 are processed
T5 DccAux_2 task at this level. The time frames for these tasks are set when configuring the
system clocks.
ez

SystemInterrupt- SystemInterruptTasks (e.g. PeripheralFaultTask, ExecutionFaultTask, etc.) have


Tasks the next lower priority. SystemInterruptTasks are triggered by errors (e.g. I/O
access errors, program execution errors, etc.). SystemInterruptTasks are called
and processed in the order in which the events that trigger them occur.
r.s

WaitforCondition If a wait command is integrated in a MotionTask, the MotionTask is stopped


while the wait command is executed and the wait condition is monitored in the
IPOsynchronousTask. If the condition is fulfilled, the commands that are
assigned to the wait command are executed with the priority specified above.
After this, the priority of the MotionTask is reset.
ne

TimerInterruptTasks TimerInterruptTasks have the next lower priority. Of the 5 TimerInterruptTasks,


a TimerInterruptTask with a smaller time slice has a higher priority than a
TimerInterruptTask with a larger time slice.
ca

UserInterruptTask 2 UserinterruptTasks for responding to events are available.


UserInterruptTask_1 has the higher priority.

Freely executing The BackgroundTask and the 32 MotionTasks share the lowest priority
execution level on what is known as the round robin level. Within this level, an additional time
slice multiplex method ensures that they are assigned free computing time.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 The SIMOTION execution system
Servo_fast and IPO_fast on SIMOTION D435-2/D445-2/D455-2

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.6
SITRAIN Training for
Automation and Drives
@
Servo_fast/IPO_fast As of V4.2, you can operate synchronous devices (drive, measuring input, or
output cam output, I/Os) on the fast bus system (PROFINET) via Servo_fast.
Servo_fast always finishes during the first send clock of the fast bus system with
this type of arrangement. This makes it possible to operate two bus systems in
er

different application cycle clocks. An assigned position control cycle clock and
IPO cycle clock are available for each of the two application cycle clocks.
A second position control cycle clock is only necessary in applications with
special requirements, e.g.:
ez

• For fast I/O processing via PROFINET IO (for particularly short sampling
times and response times)
• If, in addition to the electric axes (e.g. servo drives), hydraulic axes
with particularly high-performance pressure/position control are implemented
r.s

• If the electric axes have to be split into 2 performance classes


(fast servo - slow servo)
If the axes have to be split into 2 performance classes, a split at IPO level (IPO,
IPO_2) is usually sufficient; a split at servo level (Servo, Servo_fast) is only
required for electric axes in exceptional circumstances
ne

Since most electric servo axes are operated with DSC (Dynamic Servo Control),
the part of the position controller that acts dynamically in the drive runs at the
clock rate of the speed control circuit (i.e. usually 125 μs on SINAMICS S120).
As a result, a split at servo level is usually reserved for hydraulic drives, so that
ca

high-performance control can be implemented for special deep-drawing


processes, for example.

Note For V4.3, only the SIMOTION modules SIMOTION D435-2 DP/PN, D445-2
DP/PN and SIMOTION D455-2 DP/PN support the second position control cycle
clock.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 The SIMOTION execution system
Isochronous mode on PROFIBUS
PCT
T dp interrupt

SIMOTION BT PCT1 PCT2 PCT3 IPO

om
DP Sl. Sl. Sl. Acycl. Sl. Sl. Sl.
GC Res. GC
communication ... 1 2 3 part 1 2 3 ...

T dx

l.c
Drives Ts
Ta Sl: Slave communication (bidirectional)

ai
GC: Global control message frame
Actual values T a: Time of actual value acquisition
T s: Time of setpoint transfer Setpoints
T dx: Sum of transfer times for all slaves

SIMOTION
Siemens AG 2013. All rights reserved.
T dp:
PCT:
BT:
DP cycle time

gm
Position controller
BackgroundTask

Date:
File:
10.01.2013
MC-SMO-PROG_06.7
SITRAIN Training for
Automation and Drives
@
Isochronous mode If high-precision positioning must be performed on PROFIBUS DP, this requires
short, reproducible (i.e. of the same length) cycles with defined actual value
acquisition, position control, and setpoint output.
With SIMOTION, the equidistant (isochronous) DP bus cycles and
er

synchronization of all the individual cycles (actual value acquisition, provision of


actual values on PROFIBUS, data communication with SIMOTION, control and
setpoint output in SIMOTION, setpoint transfer and acceptance by the drive,
speed control, etc.) involved throughout the entire process chain are achieved
ez

using the isochronous PROFIBUS MC.

DP cycle time Cyclic data exchange with the slaves is carried out in this time frame. This time
frame depends on the number of slaves, the data to be transferred, the baud
rate, and additional factors. In addition to pure data exchange, sufficient time
r.s

must be provided for the position control to allow calculation of new speed
setpoints for the drives.

T dx The time duration that is necessary for data exchange to be performed with the
configured slaves is specified in this parameter. This time is calculated internally
ne

There is an assurance that data can be exchanged with all the slaves during this
time duration. After this time has expired, the position controller starts
processing the data.
ca

Global control SIMOTION outputs the global control message frame at the beginning of each
cycle for the purpose of synchronizing the drives with SIMOTION.

Ta Describes the length of time which expires before the GC message frame is
broadcast for the drives to save their actual values to. This ensures that all
actual values are acquired at the same time.

Ts Describes the length of time which expires after the GC message frame is
broadcast for the drives to accept the transferred setpoints.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 The SIMOTION execution system
Setting system cycle clocks

System cycle clocks

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.8
SITRAIN Training for
Automation and Drives
@
Bus cycle clock Specifies the basic clock cycle and is generally grayed out. Is only displayed if an
isochronous bus has been parameterized for the interface. The basic/bus cycle clock
(DP cycle clock or PN cycle clock) is used as a basis for setting further tasks.
er

The integer ratio between the position control cycle clock and the bus cycle clock is
Servo/T1 (DCC) set here. In this clock cycle, the blmocks in DCC charts, those of time slice T1, the
user programs of the ServoSynchronousTask and, among others, the position control
of the axes are perocessed. Generally, factor 1 is applied. If a different ratio is
ez

selected, it must aliso be entered in the HW Config for the drive as the "master
application cycsle". This setting is used for life-sign monitoring.

IPO/T2 (DCC) The integer ratio between @the IPO cycle clock and the position control cycle clock is
r.s

set here. By default, the DCC blocks of time slot 2, the programs of the
IPOSynchronousTask , and motion control (i.e. calculation of the position setpoints for
positioun axes) are processed in the IPO cycle clock.

IPO_2/T3 (DCC) The ratio betgween the IPO_2 and IPO cycle clocks is set here. The DCC blocks in
ne

time slice T3, the programs of IPOSynchronousTask, and motion control for axes with
less dynamic characteristics (auxiliary axes) are processed in this task.

The intervals for DCC time slices T4 and T5 are set here.
ca

DxxAux/DccAux_2

TControl Use this arrow to open the configuration of the system tasks for the TControl
technology package. The cycle clock ratios for the temperature channels task in
Copy aserynchr. relation to the position control cycle clock are set in this dialog.
cyclic I/O data
As of V4.2, you can select when the asynchronous cyclic I/O data should be
copied. The copy operation can be performed in either the IPO cycle clock or the
IPO_2 cycle clock.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 The SIMOTION execution system
Overview of user tasks

Task Task Number


Startup/Shutdown StartupTask 1
ShutdownTask 1

Time-driven ServoSynchronousTask T1 1 + 1(fast)

om
IPOSynchronousTask T2/T3 2 +1(fast)
DccAuxTask T4/T5 2
TimerInterruptTask 5

Event-controlled system TimeFaultTask 1

l.c
TimeFaultBackgroundTask 1
TechnologicalFaultTask 1
PeripheralFaultTask 1

ai
ExecutionFaultTask 1
Event-controlled user UserInterruptTask 2

SIMOTION
Round robin level

Siemens AG 2013. All rights reserved.


gm
BackgroundTask
MotionTask

Date:
File:
10.01.2013
MC-SMO-PROG_06.9
1
32 (as of V4.0)

SITRAIN Training for


Automation and Drives
@
StartupTask/ The StartupTask is executed once on transition from STOP or STOP U
ShutdownTask to RUN. It serves the purpose of initialization. The ShutdownTask is called on
transition from RUN to STOP or STOP U.
er

BackgroundTask This task is called cyclically. When the programs in this task have been
processed, the task is automatically restarted. This task implements the
conventional interlock functions of a PLC.
ez

MotionTasks MotionTasks are tasks that are started from within a cyclic user program, for
example, and are then processed only once.

ServoSynchronous This task is processed in synchronism with the servo task. In this task, fast
task terminal-to-terminal responses can be programmed, for example.
r.s

IPOSynchronous These tasks are started synchronously with the specified system cycle clock
tasks (IPO cycle clock, IPO_2 cycle clock) before the technology package. They can
be used to implement time-critical functions for starting and stopping axes, for
example.
ne

T4/T5 DccAux task The blocks of DCC charts that are assigned to time slices T4 and/or T5 are
processed in these tasks.

TimerInterruptTasks TimerInterrupt Tasks are started and processed at fixed intervals and can be
ca

used to implement control tasks that need a fixed time reference, for example.
For temperature control using the associated technology package, additional
tasks are available.

UserInterruptTasks These are event-triggered and processed only once. They can be used to
respond to user-defined events.

SystemInterrupt These are triggered by system events such as faults and alarms and
tasks processed only once.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 The SIMOTION execution system
Assigning programs to tasks

5. Using tasks in the


1. Open execution system execution system

om
2. Select task

l.c
3. Select program

ai
4. Assign program

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.10
SITRAIN Training for
Automation and Drives
@
Execution levels tree The execution levels tree is displayed in the left-hand section of the execution
system. The available execution levels/tasks are displayed as fixed entries. The
OperationLevel folder contains the tasks that are available in RUN. To open the
OperationLevel folder, click the plus sign in front of it.
er

The list below each execution level or task name shows the configured tasks
and the programs assigned to them. After you have assigned programs to tasks,
they are displayed in the execution levels tree.
ez

Click the "Select tasks" entry to display a list of all configurable tasks in the right-
hand section. Check the box next to the task you want to display in the
execution levels tree. The right-hand section contains an overview of all
execution levels and tasks.
r.s

Assignment of 1. Open the execution system dialog by double-clicking the "execution system"
programs icon.
2. Select the required task. Make sure that the "Use task in execution system"
option is selected.
3. Click the "Program assignment" tab. In the "Programs" list box on the left-
ne

hand side, select the program you wish to assign to the task.
4. Click "Assign >>". The assigned program is displayed in the list box on the
right and in the execution levels tree. The "Programs" list box on the left still
displays the program; the number of assignments that have been made is
displayed in brackets after the program.
ca

Alternatively, you can use a drag-and-drop operation to move programs from


the "Programs" list box to the task list box on the right.
5. Repeat steps 2 and 4 if necessary.

Note With DCC, blocks are assigned to time slices T1 through T5 and thus to the
corresponding tasks within the DCC editor.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 The SIMOTION execution system
Task runtimes and task status (2)

Target system -> Device diagnostics

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.11
SITRAIN Training for
Automation and Drives
@
Task runtimes The statuses and runtimes of the individual tasks can be read out using the
device diagnostics of the control system.

Call Via the device (for example D425-2) -> Target device -> device diagnostics, you
er

can access the diagnostics information of the device.


General information, the diagnostics buffer, thee task runtimes and the system
utilization are saved here.
ez

Overview Task name, task status, actual, miniemum, maximum and the average value
task runtimes are displayed for each taski in the overview.
The task status can also be read sout using the system function
(_getStateOfTask) and processed in the user program.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 The SIMOTION execution system
Task runtimes and task status (2)

om
System variables of the SIMOTION device
• TaskRuntime
• EffectiveTaskRuntime

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.12
SITRAIN Training for
Automation and Drives
@
System variables The task runtimes can also be read out via the associated system variables of
the SIMOTION device. For this functionality, measurement of the task runtime
must first be activated via the following system variable:
• TaskRunTimeMonitoring = active
er

Then the task runtimes are provided by the system in the associated system
variables.

The task runtimes alone, i.e. the runtime excluding interruptions by higher-
ez

TaskRunTime
priority levels, are displayed in this system variable.

Effective The task runtimes including inte srruptions by higher-priority levels are
TaskRunTime displayed in this system variable. The following always applies:
r.s

Effective TaskRunTime >@= TaskRunTime


ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 The SIMOTION execution system
Task trace - Analyzing task runtimes
Task mananger
Graph setting

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.13
SITRAIN Training for
Automation and Drives
@
Overview The "SIMOTION Task Trace" supports you when troubleshooting in the
SIMOTION multitasking environment. The SIMOTION Task Trace records the
sequence of individual tasks, identifies user events that you can generate via a
program command, and displays these graphically. This makes the interaction
er

between programs and tasks easily traceable, thereby affording better control
over them.

Task Trace - The SIMOTION Task Trace includes two main components:
ez

structure • The SIMOTION Task Tracer, which writes the task change and events to a
buffer on the target device
• The SIMOTION Task Profiler, an application for displaying the recorded data
SIMOTION IT DIAG (standard web pages) is used to configure the SIMOTION
r.s

Task Tracer. The recording data is saved as a JEN file on the memory card of
the target device.
If you start the Task Profiler via the device diagnostics, the trace data is
automatically read from the memory card via the online connection and
displayed. Alternatively, you can also save the JEN file from the target device to
ne

the file system of the PC using the SIMOTION standard web pages and then
open the file in the SIMOTION Task Profiler.

Start task trace Start the Task Profiler in the device diagnostics as described below: Switch to
the "Task Manager" tab. The following options are available:
ca

Click the "Display" button. The Task Profiler starts. In addition, the trace file is
loaded from the memory card of the target device and opened in a new tab in
the Task Profiler. If you click the button again, the same file is read again.
Click the "Create snapshot" button. The setting that you have made using IT-
Diag is reset to the default state. The settings made using the SIMOTION.ini file
are retained. The Task Trace is started, written to the memory card, and then
the Task Profiler started. If you click the button again, a new recording is started.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 The SIMOTION execution system
Task trace – Configuration via IT Diag

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.14
SITRAIN Training for
Automation and Drives
@
Configuration SIMOTION IT DIAG (standard web pages) is used to configure the SIMOTION
Task Tracer. The recording data is saved as a JEN file on the memory card of
the target device. If you start the Task Profiler via the device diagnostics, the
trace data is automatically read from the memory card via the online connection
er

and displayed. Alternatively, you can also save the JEN file from the target
device to the file system of the PC using the SIMOTION standard web pages
and then open the file in the SIMOTION Task Profiler.
ez

Note The button "Get Trace File" offers a further possibility to upload and store a
Trace file, from the SIMOTION memory card to the PG/PC. Afterwards the trace
file could be opened and displayed via the trace profiler.
The trace profiler could also be opened using the Windows start menu:
r.s

Start -> SIMATIC -> STEP 7 -> SIMOTION Task Profiler


ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 The SIMOTION execution system
Tasktrace – System command for control

System function Description

om
_taskTraceStart() : UDINT Starts the task trace recording

_taskTraceStop() : UDINT Stops an active task trace recording

_taskTraceWriteOut() : UDINT Stops a running task trace recording and


store the data on memory card

l.c
_taskTraceUserEvent(UDINT) : This function stores an event with the
UDINT event number (freely selectable ID
between 0 and 255) in the buffer of the
SIMOTION Task Tracers

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.15
SITRAIN Training for
Automation and Drives
@
Control The Task Tracer could be configured using either the tool "SIMOTION IT DIAG"
(standard web pages of the target system) or via system functions which were
called in the user program.
er

Note The data of the task tracer, which was stopped by _taskTraceWriteOut() are
stored in a JEN File (ttrace.jen) on the memory card of the target system. This
JEN file is stored in following directory:
ez

/USER/SIMOTION/HMI/SYSLOG/TASKTRACE/DIAG
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 The SIMOTION execution system
Commands for processing tasks

Two groups of commands

Commands for kernel versions <= V3.0 Commands as of kernel versions V3.1

Example: Example:
_startTask ( // Only short form _startTaskId (

om
name : Task_Name // MotionTasks only id : StructTaskId // MotionTasks only
) : VOID ) : DWORD

Assignment: Assignment:
<name>: MotionTask_1, ... <id>: _task.MotionTask_1
• Only "constants" permitted for <name> e.g. • MotionTask identified via its "Id"

l.c
MotionTask_1, etc., no variables possible • Variables can be used
for <name> • Can be used in libraries
• Cannot be used in libraries • Can be called in LAD/FBD
• Cannot be called in LAD/FBD • Both call variants possible

ai
• Only short form of call permitted
Determination of "Id":
• _task.MotionTask_1

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
• _getTaskId(Task_Name)

10.01.2013
MC-SMO-PROG_06.16
SITRAIN Training for
Automation and Drives
@
Special features There are generally two groups of functions for processing tasks in SIMOTION.
The differences between them are to be found in how tasks are defined:
The task is defined with a unique TaskId:
These functions are available in SIMOTION Kernel V3.1 and higher and can be
er

used in libraries.
You can obtain the TaskId for a task in the folloewing two ways:
• As the task.name variable, where namme designates the task as defined
in the execution system (e.g. _task.MotionTask_1)
ez

• With the _getTaskId(name) function. eThe task is defined once again by


means of its identifier (as it appeiars in the execution system)
These functions must not be used sin libraries or LAD/FBD programs.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 The SIMOTION execution system
Commands for runtime measurement of tasks

Command Description
_getMaximalTaskIdRunTime(taskId): TIME „ Returns the maximum runtime of the task since the last
transition from STOP to RUN, including all interruptions by
_getMaximalTaskRunTime(name): TIME
higher-priority tasks.

om
_getMinimalTaskIdRunTime(taskId): TIME „ Returns the minimum runtime of the task since the last
transition from STOP to RUN, including all interruptions by
_getMinimalTaskRunTime(name): TIME
higher-priority tasks.
_getCurrentTaskIdRunTime(taskId): TIME „ Returns the runtime of the task from the previous cycle,
including all interruptions by higher-priority tasks.
_getCurrentTaskRunTime(name): TIME

l.c
_getAverageTaskIdRunTime(taskId): TIME „ This command returns an average runtime of the task
from the last 10 cycles, including all interruptions by
_getAverageTaskRunTime(name): TIME
higher-priority tasks.

_retriggerTaskIdControlTime(taskId):DWORD „ The monitoring time is reset once for the task.

ai
„ The function is applicable to MotionTasks,
_retriggerTaskControlTime(name): DWORD
BackgroundTask, TimerInterruptTasks,
UserInterruptTasks, SystemInterruptTasks.

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_06.17
SITRAIN Training for
Automation and Drives
@
Special features The commands for runtime measurement are permissible for all tasks.
Measurement is not supported by the IPOsynchronousTask and the
ShutDownTask. For calls involving tasks which do not support measurement, 0
is returned as the measured value.
er

The following commands do not interrupt measurement:


• _suspendTask()
• _disableScheduler(..)
ez

The commands may only be called in the short form, i.e. with a complete listing
of all parameter values, but without specification of the formal parameters.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 The SIMOTION execution system
Commands for controlling tasks
Command Description
„ Starts a MotionTask; the startup code is executed.
_startTaskId(taskId) : DWORD
„ The function has no effect on MotionTasks whose status is set to
TASK_STATE_RUNNING.
_startTask(name) : VOID „ Command must not directly follow _resetTask(). Use
_restartTask() instead.

om
_resetTaskId(taskId) : DWORD „ Resets a MotionTask to the original state
_resetTask(name) : VOID TASK_STATE_STOPPED.
_restartTaskId(taskId) : DWORD „ Resets a MotionTask to the original state TASK_STATE_STOPPED
and restarts it; the startup code (initialization of variables) is
_restartTask(name) : VOID executed.
_suspendTaskId(taskId) : DWORD „ The relevant task is suspended; for cyclic tasks, time monitoring is
suspended.

l.c
_suspendTask(name) : VOID „ Cannot be used for IPOsynchronousTask, StartupTask, and
ShutdownTask.
_resumeTaskId(taskId) : DWORD „ The relevant task is resumed; time monitoring is resumed.
„ Cannot be used for IPOsynchronousTask, StartupTask, and
_resumeTask(name) : VOID ShutdownTask.

ai
_getStateOfTaskId(taskId) : DWORD „ Returns the state of the relevant task.
_getStateOfTask(name) : DWORD
_disableScheduler() : DINT „ Prevents scheduling of all user tasks except ServoSynchTask,

_enableScheduler() : DINT

SIMOTION
Siemens AG 2013. All rights reserved.
gm
IPOsynchTask, and IPOsynchTask_2
„ Re-enables scheduling of user tasks

Date:
File:
10.01.2013
MC-SMO-PROG_06.18
SITRAIN Training for
Automation and Drives
@
Controlling Various commands are available for controlling tasks. The parameter name
tasks represents the task name as indicated in the execution system (e.g.
"MotionTask_1", "IPOsynchronousTask", "StartupTask", "BackgroundTask",
etc.).
er

The commands may only be called in the short form, i.e. with a complete listing
of all parameter values, but without specification of the formal parameters.

Task states The task states can be queried with _getStateOfTask(taskname) or


ez

_getStateOfTaskId(taskname). This function requires the task name or the


corresponding TaskId as an input parameter and returns a value of data type
DWORD, from which the task state can be derived (see next slide).
i
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 The SIMOTION execution system
Checking the state of a task in LAD/FBD

_getStateOfTaskId
Determine task BOOL EN ENO BOOL
state StructTaskId id OUT DWORD

om
Return value "OUT" indicates ORing of the following states:
• 16#0000:
Specified task does not exist (TASK_STATE_INVALID)
• 16#0001:
Transition from RUN to STOP (TASK_STATE_STOP_PENDING)

l.c
• 16#0002:
Task stopped (TASK_STATE_STOPPED)
• 16#0004:
Task running (TASK_STATE_RUNNING)
• 16#0010:
Task waiting (TASK_STATE_WAITING)
• 16#0020:
Task suspended (TASK_STATE_SUSPENDED)

ai
• 16#0040:
TimerInterruptTask waiting for next cycle
(TASK_STATE_WAIT_NEXT_CYCLE)
• 16#0080 UserInterruptTask or SystemInterruptTask waiting for
next event (TASK_STATE_WAIT_NEXT_INTERRUPT)

SIMOTION
Siemens AG 2013. All rights reserved.
gm
• 16#0100 Task locked by _disableScheduler (TASK_STATE_LOCKED)

Date:
File:
10.01.2013
MC-SMO-PROG_06.19
SITRAIN Training for
Automation and Drives
@
Task states This functions returns the state of the relevant task. It can be used for all tasks
except StartupTask and ShutdownTask.
This function requires the task name as an input parameter and returns a value
of data type DWORD, from which the task state can be derived.
er

The states of tasks are linked by an OR bit string.


ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 The SIMOTION execution system
State model for tasks

• WAITFORCONDITION
TS TS • _waitTime() TS
_INVALID _WAITING _RUNNING
(16#0000) (16#0010) Condition fulfilled (16#0004) _
r es
e

om
d tT
kI as
T as kI
nd d
pe d
us kI
_s

_restartTaskId
as

MT completed
T
me

t
su TS_STOP

up
e
_r

rr
_PENDING
TS_

te

d
(16#0001)

te
in
SUSPENDED

l.c
le
xt
(16#0020)

mp
Ne

Co
TS

ai
_WAIT_NEXT TS
TS _CYCLE TS
_STOPPED
_LOCKED (16#0040) _WAIT_NEXT
(16#0002)
(16#0100) _INTERRUPT

SIMOTION
_disableScheduler
_enableScheduler

Siemens AG 2013. All rights reserved.


Date:
File:
gm
(16#0080)

10.01.2013
MC-SMO-PROG_06.20
SITRAIN Training for
Automation and Drives
@
TS_INVALID The task does not exist in the execution system. It is not used in the execution
system’s parameterization.

TS_STOP_PENDIING Task has received signal to stop; however, it is in a state between RUNNING
er

and STOPPED. Actions may be performed until the task stops.

TS_STOPPED The task has been stopped due to the following actions:
• The _resetTaskId() function has been camlled
ez

• SIMOTION SCOUT has performede a stop


The task is running due to the fosllowing actions:
TS_RUNNING
• The _startTaskId() func tion has been called (MotionTasks)
r.s

• Active cyclic task (Backg@roundTask, etc.)


• The associated ev ent has occurred (UserInterruptTask, etc.)

Task in Wait statle due to one of the following functions:


TS_WAITING
ne

• _waitTime()g
• WAITFORCoONDITION...
TS_SUSPENDED
ca

TS_WAIT_NEXT The etask has been suspended by the _suspendTaskId() function.


_CYCLE
TimerInterruptTask is waiting for start trigger.
TS_WAIT_NEXT
_INTERRUPT SystemInterruptTask is waiting for the triggering alarm to occur, or the
UserInterruptTaskis is waiting for the triggering event to occur.
TS_LOCKED
Task has been locked by the _disableScheduler() function.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 The SIMOTION execution system
Querying tasks: TaskStartInfo

Query system variables:


• TSI#<info>
TSI#<info> Meaning
TSI#startTime Start time of the task

om
TSI#taskId Task that caused the error
(system error tasks)
TSI#interruptId Event that triggered the call
comparison operation, e.g.
TSI#alarmNumber Alarm number of triggering TO TSI#taskId = _task.MotionTask_1

l.c
TSI#toInst Instance of triggering TO
TSI#commandIdlow ID of causing command
(low word)
TSI#commandIdhigh ID of causing command

ai
(high word)
TSI#executionFaultType Type of processing error
. . . ...

SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm 10.01.2013
MC-SMO-PROG_06.21
SITRAIN Training for
Automation and Drives
@
TaskStartInfo Important information about starting the task is stored in the TaskStartInfo for
each task, e.g.:
• Start time of task
• For the TechnologicalFaultTask: the triggering instance of the technology
er

object and the alarm number


• For the TimeFaultTask: the TimerInterruptTask that caused the timeout error
• For the ExecutionFaultTask: the task in which the error was caused
ez

and the type of error (divide by zero, invalid floating-point number, etc.)
Within a task, its TaskStartInfo can be queried with the following system
variable:
• TSI#<info> (<info> is the information to be queried)
r.s

The content and scope of the TaskStartInfo and the associated system variables
depend on the relevant task.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 The SIMOTION execution system
Waiting in a MotionTask using WAITFORCONDITION
INTERFACE
USEPACKAGE CAM;
PROGRAM feeder;
END_INTERFACE

IMPLEMENTATION
EXPRESSION myExpression // Declaration of an EXPRESSION
myExpression := IOfeedCam; // always with retVal equals BOOL

om
END_EXPRESSION
// feeder is assigned to MotionTask_1
PROGRAM feeder
VAR
retVal : DINT ;
END_VAR ;
; // further commands

l.c
WAITFORCONDITION myExpression WITH TRUE DO
retVal := _pos(axis := Achse_1,
positioningMode := RELATIVE,
position := 500,
velocityType := DIRECT,

ai
velocity:= 300,
mergeMode:= IMMEDIATELY,
nextCommand := WHEN_MOTION_DONE);
END_WAITFORCONDITION;

SIMOTION
;
END_PROGRAM
END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


gm
// further commands

Date:
File:
10.01.2013
MC-SMO-PROG_06.22
SITRAIN Training for
Automation and Drives
@
Properties You can use the WAITFORCONDITION statement to wait for a programmable
event or condition in a MotionTask. The statement suspends execution of the calling
MotionTask until the condition is true. In the mean time the MotionTask is witched to
the task state TASK_STATE_WAITING.
er

The evaluation of the Expression is performed by the system an the end of the
IPO Task. If the expression evaluates to TRUE, the MotionTask is switched from the
task state TASK_STATE_WAITIN to TmASK_STATE_RUNNING, i.e. it is
competing with the other tasks in that state to be dispatched to the processors.
ez

Additionally the priority of the MotioneTask is increased. The priority is higher


than for UserInterruptTasks and TiimerInterruptTasks and lower than for
SystemInterruptTasks. So wshen no errors are present in the system, i.e. no
SystemInterruptTasks are ac tivated, the MotionTask has its turn before the other
r.s

task in the round-robin execution level, as well as before the UserInterruptTasks and
TimerInterruptTasks.
This increased task pr iority applies to all statements between the
WAITFORCONDITuION command and the END_WAITFORCONDITION command.
The lEND_WAITFORCONDITION command ends the increased task priority.
ne

By means oof the WAITFORCONDITION command one has a very powerful


method to respond very fast an with nearly no jitter to external and internal events.
Inel comparison with an event handling in a cyclic task like the IPO task, the use of
the WAITFORCONDITION in a MotionTask has the following adkvantages:
ca

• The MotionTask waiting for the event is switched to the task state
TASK_STATE_WAITING, i.e. the MotionTask does not consume any
processor load. Only a small amount of processor load is required by the
system to evaluate the EXPRESSION.
• Due to the increase of the execution priority, the MotionTask will be the next
task which is dispatched to the processor when the EXPRESSION returns
with TRUE. So in maximum one has a delay of one IPO cycle until the
response, e.g. start or stop of axis motion will be effective.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 The SIMOTION execution system
Declaration and use of an EXPRESSION
INTERFACE An EXPRESSION must be declared in the
USEPACKAGE CAM; implementation part of an ST source file
PROGRAM feeder;
END_INTERFACE
The return value is always of data type BOOL
(it is not explicitly assigned in the declaration)
IMPLEMENTATION In the declaration part of an EXPRESSION the
following sections are permitted:
EXPRESSION myExpression

om
• TYPE
VAR_INPUT
myInput : BOOL; • VAR und VAR_CONSTANT
. . . • VAR_INPUT und VAR_IN_OUT
END_VAR In the instruction part access is permitted to the
VAR_INOUT following variables:
. . .
END_VAR • local variables and parameters

l.c
; • Unit variables
myExpression := . . .; • global device variables
END_EXPRESSION • IO variables and process image variables
An expression of type BOOL must be assigned
PROGRAM feeder to the "Expression name" (return value)

ai
. . .
WAITFORCONDITION myExpression(…)
Instructions between WAITFORCONDITION
WITH TRUE DO
and END_WAITFORCONDITION are executed
; // Instructions with high priority with a higher priority to avoid task switches

SIMOTION
END_WAITFORCONDITION;

END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


gm
Date:
File:
Optional a rising edge evaluation could be
integrated by the keyword "WITH TRUE"

10.01.2013
MC-SMO-PROG_06.23
SITRAIN Training for
Automation and Drives
@
Expression For the use of the WAITFORCONITION instruction the declaration of a so-
called "Expression" is necessary. An "Expression" is a special case of a function
declaration. The data type of the return value is always defined as BOOL, it is
not specified explicitly in the declaration.
er

An "Expression" must be declared in the implementation part of an ST source


file. Optionally, the following can be declared in the declaration section:
• Local (temporary) variables
ez

• Local constants
• User-defined data types (UDT)
• Input and in-out parameters (as of Version V4.1 of the SIMOTION kernel)
The following can be accessed in the statement section:
r.s

• To the local variables of the expression


• To the input and in/out parameters (provided their declaration is permitted)
• Unit variables
• Global device variables, I/O variables, and process image variables
ne

An expression of data type BOOL must be assigned to the "Expression name" in


the statement section of the "Expression".
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 The SIMOTION execution system
Synchronizing concurrent access: Semaphores
UNIT This UNIT That
INTERFACE INTERFACE
VAR_GLOBAL USES This;
my_struc: S;
mySema: DINT;
END_VAR
END_INTERFACE END_INTERFACE

Execution system

om
IMPLEMENTATION IMPLEMENTATION

MotionTask 2
PROGRAM motion2 //Motion Task2
PROGRAM motion1 //Motion Task1
WHILE TRUE DO
IF _testAndSetSemaphore(mysema) IF _testAndSetSemaphore(mysema)
THEN THEN
my_struc.a := a;

l.c
my_var_a := my_struc.a;
my_var_b := my_struc.b; my_struc.b := b;
_releaseSemaphore (mySema); _releaseSemaphore (mySema);

MotionTask 1
END_IF; END_IF;
END_WHILE;
END_PROGRAM

ai
END_PROGRAM

END_IMPLEMENTATION

SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm 10.01.2013
END_IMPLEMENTATION

MC-SMO-PROG_06.24
SITRAIN Training for
Automation and Drives
@
Inconsistent All accesses to variables of elementary data types are managed consistently by
access the system. The system makes sure that changes cannot be made to these
variables while they are being processed.
However, where access to global compound variables is concerned (derived
er

data types STRUCT, ARRAY), users are responsible for ensuring data
consistency. Inconsistencies can occur when several tasks access the same
variables (symbolic I/O variables, system variables of SIMOTION devices and
technology objects, global device variables and unit variables).
ez

For example, a program belonging to MotionTask_1 writes to a structure,


thereby overwriting the first variable. MotionTask_1 is then interrupted and
MotionTask_2 is started. The program in MotionTask_2 reads the same
structure. Without additional synchronization, MotionTask_2 would read an
inconsistent data set, since the first variable would have originated from the last
r.s

execution of MotionTask_1, and the second variable from an earlier execution.

Semaphores Without additional synchronization mechanisms, such concurrent access to


shared data structures would result in inconsistent data and therefore
inconsistencies in processing. Semaphores are one way of synchronizing
ne

concurrent access operations. Semaphores must be declared as global


variables of data type DINT.

Test&Set _testAndSetSemaphore() scans the content of a semaphore and then sets it to


ca

1. If its original content is 0, the value TRUE is returned. The semaphore was
free and access is, therefore, permitted.
If its original content is 1, the value FALSE is returned. The semaphore is not
free and access is, therefore, not permitted.

Release Following consistent access, a set semaphore can be released again (i.e. its
content reset to 0) with the _releaseSemaphore() system function.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 The SIMOTION execution system
Gearing in SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.1
SITRAIN Training for
Automation and Drives
@
Contents Page
How synchronous operation is structured in SIMOTION ................................................................... 3
Camming in SIMOTION ..................................................................................................................... 4
er

Creating a following axis .................................................................................................................... 5


Making an assignment to leading axes and cams ............................................................................. 6
Settings for synchronous operation .................................................................................................... 7
ez

Default settings for synchronous operation ........................................................................................ 8


Enabling gearing in MCC (1) .............................................................................................................. 9
Absolute and relative gearing ............................................................................................................. 10
Enabling gearing in MCC (2) .............................................................................................................. 11
r.s

Leading axis synchronization ............................................................................................................. 12


Reference point for leading axis synchronization .............................................................................. 13
Synchronization with direction specification ...................................................................................... 14
Enabling gearing in ST ....................................................................................................................... 15
ne

"Optimum" synchronization profile (leading axis synchronization) ..................................................... 16


Useful system variables for synchronization ...................................................................................... 17
Leading axis synchronization (absolute synchronous operation) ....................................................... 18
Leading axis synchronization (relative synchronous operation) ......................................................... 19
ca

Time-related synchronization ............................................................................................................. 20


Trailing synchronization (how it works) .............................................................................................. 21
Trailing synchronization (trace recording) ......................................................................................... 22
Trailing synchronization with reversing of leading axis ..................................................................... 23
Leading synchronization (how it works) ............................................................................................. 24
Leading synchronization (trace recording) ......................................................................................... 25
Leading synchronization, changing the leading axis velocity (1) ....................................................... 26

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 Gearing in SIMOTION
Gearing in SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.2
SITRAIN Training for
Automation and Drives
@
Contents Page
Leading synchronization, changing the leading axis velocity (2) ....................................................... 27
Synchronization without overshoot (engagement) ............................................................................. 28
er

Engagement (trace recording) ........................................................................................................... 29


Enabling gearing in MCC (3) .............................................................................................................. 30
Enabling gearing in MCC (4) .............................................................................................................. 31
Disabling gearing in MCC ................................................................................................................... 32
ez

Disabling gearing in ST ...................................................................................................................... 33


Enabling velocity gearing in MCC ...................................................................................................... 34
Enabling velocity gearing in ST .......................................................................................................... 35
Set master setpoint (_setmaster) ...................................................................................................... 36
Set in synchronous motion (trace recording) ..................................................................................... 37
r.s

Set offset on the gearing in MCC ....................................................................................................... 38


Set offset on the gearing in ST .......................................................................................................... 39
Commands for reading out master and slave values in ST ............................................................... 40
Actual value coupling with extrapolation (1) ....................................................................................... 41
ne

Actual value coupling with extrapolation (2) ....................................................................................... 42


Structure of superimposed synchronous operation ........................................................................... 43
Example: Filling chocolate molds on a conveyor belt ........................................................................ 44
Insert superimposed synchronous object .......................................................................................... 45
Structure of distributed synchronous operation ................................................................................. 46
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Gearing in SIMOTION
How synchronous operation is structured in SIMOTION

Master value
• Position axis External
• Following axis encoder
• Ext. encoder Virtual
• Virtual axis axis
Slave value

om
Leading
Synchro-
axis
nous
operation
Settings TO

l.c
• Master value Master value
• Gear ratio
• Synchronization and
desynchronization profile

ai
Buffer IPO Servo

• Limitations of use

SIMOTION
• Monitoring functions

Siemens AG 2013. All rights reserved.


gm
Following axis TO

Date:
File:
10.01.2013
MC-SMO-PRG_07.3
SITRAIN Training for
Automation and Drives
@
How synchronous The "Synchronous operation" technology object is used to connect two
operation is or more axes to create a synchronous group.
structured A leading axis (master) generates a master value, which is processed by the
synchronous object according to specific criteria (gear ratio, scaling, cam, etc.)
er

and assigned to the following axis (slave) as a reference variable.


The master value source can be a position axis or a following axis, for example,
or an external encoder. As of SW3.0 SP 1, a setpoint or actual value coupling
can be selected as the master value sourmce for axes. With an actual value
coupling, it is also possible to configuere dead time compensation of the master
ez

value.

The master and slave values arse coupled without physical conversion in the
relevant parameterized units. If the leading axis is a linear axis (unit mm), for
example, and the following axis is a rotary axis (unit degrees), then with a
r.s

conversion ratio of 1:1, one millimeter corresponds to one degree.

Mechanical Mechanically, the suynchronous object represents the gear with driving gear/
model driven gear or, inl conjunction with the "Cam" TO, the cam gear with the
mechanical cam and sensor system. The model also includes a coupling for
ne

enabling and disabling the following motion on-the-fly.

Coupling via The geaelr functionality is characterized by a constant ratio between master
gear value source and following axis. The ratio can either be programmed as a
rational gear factor or using a numerator/denominator ratio.
ca

The slave value is calculated from the programmed gear factor and the master
value and transferred to the gear axis. A following axis can be interconnected
with more than one master value by means of the synchronous object, but only
one of these is evaluated. At runtime, you can switch over the master setpoint in
the user program.
When you select the gearing, you differentiate between absolute and relative
synchronous operation. You can also select from different types of
synchronization/desynchronization profile (related to master value or time).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Gearing in SIMOTION
Camming in SIMOTION

Master value
• Position axis External
• Following axis encoder
• Ext. encoder Virtual
• Virtual axis Cam_1
axis

om
Slave value
Leading Cam_2
axis TO Synchro-
nous
operation Cam_3
Settings
• Master value
TO

l.c
• Cam
• Scalings Master value
• Synchronization and
desynchronization profile

ai
Buffer IPO Servo

• Limitations of use Following axis TO

SIMOTION
• Monitoring functions

Siemens AG 2013. All rights reserved.


Date:
File:
gm 10.01.2013
MC-SMO-PRG_07.4
SITRAIN Training for
Automation and Drives
@
Coupling via The cam gear functionality is characterized by a variable ratio between master
cam value source and following axis. The user can program it by using a cam. In
addition, the scaling and offset can be adapted for both the master value and the
slave value.
er

SIMOTION supports both distributed and superimposed synchronous operation.


With distributed synchronous operation, rather than being on the same
SIMOTION device, the leading axis, synchronous operation TO, and following
axis TO are distributed among several controllers. With superimposed
ez

synchronous operation, a following axis does not receive its position setpoints
from one synchronous operation TO but from two, i.e. the basic synchronous
operation TO and a superimposed synchronous operation TO.
Several cams can be used in camming. You can switch from one cam to
another in the user program during runtime.
r.s

Rules The following rules apply for interconnection in general:


• The synchronous object and the following axis are on the same runtime
system
ne

• The synchronous object and the following axis are permanently assigned to
one other in the configuration
• The master value object (position axis, virtual axis, following axis or external
encoder) can be interconnected with several synchronous objects
ca

• The synchronous object can be interconnected with several master values


and cams

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Gearing in SIMOTION
Creating a following axis

om
Synchronous operation

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.5
SITRAIN Training for
Automation and Drives
@
Create synchronous If the "synchronous operation" technology is selected when creating an axis in
object SIMOTION SCOUT, SIMOTION SCOUT will automatically create a
synchronous object belonging to the axis.
The synchronous object appears in the project navigator underneath the
er

corresponding axis. The object is automatically assigned the axis name


and suffixed with "_SYNCHRONOUS_OPERATION.

Assignments Master value and cam assignments are indmicated in the SIMOTION
ez

SCOUT project navigator by links:


• The links to the master values (aixes, external encoder) and cams are
displayed underneath the "synchsronous object"
• The link to the synchronou s object is displayed underneath the "cams"
r.s

used
• The link to the synchr@onous object is displayed underneath the
"master values" (axes, external encoder)
These assignments are made in the "Interconnections" dialog (see next slide).
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Gearing in SIMOTION
Making an assignment to leading axes and cams

om
• Setpoint coupling
• Actual value coupling
with extrapolation

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.6
SITRAIN Training for
Automation and Drives
@
Interconnections Assignments between the synchronous object and possible leading axes and
cams are made in the "Interconnections" dialog. This dialog opens when you
double-click Interconnections under the <AxisName>_SYNCHRONOUS
OPERATION object in the project navigator.
er

In this dialog, the possible master values and cams are assigned to the
synchronous object of the following axis. The currently used master value/active
cam is defined during runtime using the appropriate functions.
ez

Setpoint and actual With real axes, you can also choose between setpoint and actual value
value coupling coupling. External encoders only support actual value coupling, virtual axes only
support setpoint coupling.
With actual value coupling, the reference value for the actual value coupling
r.s

must be extrapolated to compensate dead times. The corresponding


compensation is set at the TO of the leading axis.

Notes Gearing or camming with a following axis is only possible if at least one master
value has been assigned to the associated synchronous object
ne

To select camming, a cam must also be assigned.

Expert list You can access all configuration data and system variables of the synchronous
object via the expert list. You can open the expert list by selecting Expert ->
Expert list from the synchronous object's context menu.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Gearing in SIMOTION
Settings for synchronous operation

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.7
SITRAIN Training for
Automation and Drives
@
Configuration The most important configuration settings for synchronous operation can be
made in this dialog.

Direction-related Allowance for direction-dependent or direction-independent effect of the


er

dynamic parameters programmed dynamic values (syncingMotion.directionDynamic).

Abs. synchr. with For absolute synchronization, if "Yes" is set the jerk is taken into account.
consideration of jerk If "No" is set, the set jerk will be ignored in spite of velocity profile = SMOOTH
ez

being selected. Travel follows a trapezoidal path


(syncingMotion.smoothAbsoluteSynchronization).

Adaptation of Adaptation to the leading axis dynamic response in the synchronous position
r.s

dynamic values (syncingMotion.synchronizingAdaption). If "Yes" is set, the "Overdrive factor"


parameter is available:

Overdrive Overdrive factor for the adapted dynamic response values to compensate
factor a remaining path difference (syncingMotion.overdriveFactor) The value is
ne

specified in percent (%). Reference to the current master value velocity for the
start of synchronization.

Tolerance for Tolerance window for aborting synchronization for direction reversal of the
direction reversal master values (syncingMotion.masterReversionTolerance). Position value in the
ca

user unit of the master values

Permissible velocity Maximum permissible change in master value velocity


change (syncingMotion.maximumOfMasterChange)
Refers to the current master value velocity for the start of synchronization. The
value is specified in percent (%).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Gearing in SIMOTION
Default settings for synchronous operation

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.8
SITRAIN Training for
Automation and Drives
@
Setting default Default settings for synchronous operation are made in the "Default" dialog. In
parameters this dialog, parameters (defaults) for calling synchronous operation functions
are set. However, these parameters are only evaluated if no special settings
have been made in the associated function calls for synchronization/
er

desynchronization (ST and LAD/MCC).


You can specify conditions for synchronizatione and desynchronization either
directly via function parameters at function call or via these settings (what we
call user default values). These user defaumlt values are also stored in the
ez

appropriate system variables of synchronous object.


Three tabs are provided for makising the required settings for the default
Settings
parameters for the "synchronous operation" functionality:
• "Gearing" tab
r.s

- Gear type (absolut@e or relative synchronous operation)


- Direction (same or inverse direction)
- Gear ratlio
• "Gear syncghronization" tab
- Seottings for synchronization positions
ne

- Slettings for desynchronization positions


• "Deynamic response" tab
- Settings for synchronization profile (related to leading axis or time)
- Settings for synchronization length (for leading-axis-related
synchronization profile only)
ca

- Settings for dynamic parameters (for time-related synchronization


profile only)

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Gearing in SIMOTION
Enabling gearing in MCC (1)

Gearing
on

Specification of master
and following axes

om
Specification of direction
and gear ratio

Select:

l.c
• Absolute or
• Relative
gearing

ai
Settings for transition
behavior and program

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.9
advance

SITRAIN Training for


Automation and Drives
@
Programming On the "Parameters" tab of the MCC command "Gearing ON", you can make
gearing settings for master and following axes as well as for the gear type and gear
ratio.

Here you select the following axis for synchronization. All axes of the device for
er

Following axis
which the synchronous operation functionality has been configured as well as
all variables of the MCC chart with data type "followingAxis" are available for
selection.
ez

Here you select the axis or external encoder which supplies the master value
Leading axis in the synchronous relationship. You can choose from all position axes,
following axes, and external encoders as well as from all variables of the MCC
chart with data type: posAxis, followingAxis, or externalEncoderType.
r.s

Here you select the e ffective direction of the gear.


Gear direction
Here you can sellect whether the gear ratio is specified as a fraction
(nominator/denominator) or as a floating-point number.
Type of
Depending on the selected "type of gear ratio", the gear ratio can be entered
ne

ratio
as a nominator/denominator pair or as a floating-point number.
Nominator/ Here you select the type of synchronous operation. SIMOTION diff
denominator
Check this box to reset the master value of the synchronous operationrentiates
ca

Reference point between absolute synchronous operation, i.e. angular-locked synchronous


operation/position synchronous operation (select "Gearing takes place relative
to axis zero") and relative synchronous operation, i.e. velocity gearing (select
"Gearing takes place relative to start position").
relationship (default setting). If this box is not checked, a master value set
previously is retained.
Reset master value

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Gearing in SIMOTION
Absolute and relative gearing
Gearing

Position synchronous operation/ Velocity gearing


angular-locked synchronous operation (gearingType = RELATIVE,
(gearingType = ABSOLUTE, reference point: Gearing takes place
reference point: Gearing takes relative to start position)
place relative to axis zero)

om
Slave value Slave value

l.c
g g

φ Master value φ Master value

ai
Slave value = g x master value + φ

φ is well- defined φ is undefined

SIMOTION
(can be specified in system function call
"Synchronize")

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.10
("chosen at random"
at synchronization)

SITRAIN Training for


Automation and Drives
@
Gearing Gearing is characterized by a constant gear ratio between master value source
and following axis.
In addition, phase offset can occur between leading axis and following axis. The
way in which this additional phase/position offset is specified/handled marks the
er

difference between absolute and relative gearing.

Absolute With absolute gearing, i.e. "Gearing takes place relative to axis zero"
gearing (gearingType = ABSOLUTE), the master values and slave values are
ez

interpreted as absolute. This means that any offset between master value and
slave value existing prior to synchronization is compensated.
After completion of the synchronization procedure, both the velocities and the
positions of the leading axis and the following axis are identical (φ = 0) or a
r.s

defined phase relationship (φ <> 0) has been established between the positions
of leading axis and following axis.
A phase (φ ) can be specified if: "Start of synchronization: at leading axis with
offset" or "Synchronize immediately with offset" is selected.
ne

Relative With relative gearing, i.e. "Gearing takes place relative to start position"
gearing (gearingType = RELATIVE), a synchronization profile is calculated so that only
the velocities of the leading axis and the following axis are adapted in
accordance with the gear ratio.
An offset existing before synchronization or additional phase (φ' ) resulting from
ca

the synchronization process is not compensated.


After synchronization of the following axis, position control of the following axis
ensures that phase offset or position offset caused by interference, for example,
is compensated.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Gearing in SIMOTION
Enabling gearing in MCC (2)

Selection of synchroni-
zation reference:
• Leading axis

om
• Time

Settings for positions,


offset, and synchroni-
zation length

l.c
Settings for transition
behavior and program

ai
advance

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.11
SITRAIN Training for
Automation and Drives
@
Programming On the "Synchronization" tab of the MCC command "Gearing ON", you can
gearing make settings for the synchronization reference as well for synchronization
positions and lengths.
er

Start of Synchronize immediately:: In this case, synchronization is initiated immediately.


synchronization Select "Gearing takes place relative to axis zero" for absolute position
synchronous operation (φ = 0). An additional phase offset (φ <>0) is not
possible.
ez

At leading axis position: Synchronization starts once the leading axis has
reached a specific position. Select "Gearing takes place relative to axis zero" for
absolute position synchronous operation (φ = 0). An additional phase offset
(φ <>0) is not possible.
r.s

At leading axis position with offset: Synchronization starts once the leading axis
has reached a specific position.
Select "Gearing takes place relative to axis zero" for absolute position
synchronous operation. In this case, an additional phase offset (φ) can be
specified between leading axis and following axis.
ne

Synchronize immediately with offset In this case, synchronization is initiated


immediately. A phase offset (φ <>0) can also be specified with absolute gearing.
Following axis position Synchronization starts once the following axis has
reached a specific position. Select "Gearing takes place relative to axis zero"
for absolute position synchronous operation (φ = 0).
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 Gearing in SIMOTION
Leading axis synchronization

Position/Velocity Following axis velocity

Leading axis
velocity

om
Position
Leading axis

Position

l.c
Following axis Leading axis position

Start End
Synchronization length

ai
Leading-axis-related synchronization profile
• Specification of synchronization position -> Start and end positions are clearly defined,
and synchronization length dynamic parameters are not effective

SIMOTION
Siemens AG 2013. All rights reserved.
gm
• SIMOTION uses the positions of the following axis and the ratio of the velocities of the following
and leading axes at the start and the end to calculate the synchronization profile

Date:
File:
10.01.2013
MC-SMO-PRG_07.12
SITRAIN Training for
Automation and Drives
@
Synchronization The profile for synchronization can reference the leading axis or time. In ST and
reference LAD, the profile can be selected using the function parameter
syncProfileReference.
• Leading axis (syncProfileReference = relate_sync_profile_to_leading_value)
er

• Time (syncProfileReference = relate_smync_profile_to_time)

Master-value-related
With master-value-related synchroinization, a start value or an end value for
ez

synchronization and a synchronsization length related to the master value are


synchronization specified. SIMOTION uses the specified synchronization length to calculate a
synchronization profile that is independent of the dynamic behavior of the leading
axis.
r.s

The synchronization profile between start and end is specified as a cubic spline
(SyncingMotion.VelocityMode = CONTINUOUS):
y = a0 + a1*x + a2 * xu 2 + a3 * x3 (y: following axis position, x: leading axis position)

The coefficients la0 ... a3 are calculated using the 4 conditions for the positions of
ne

the following axis and the inclines (ratio of the velocities of the following and
leading axes = gear ratio) at the start and at the end of the profile.
Setting the lparameters in this way ensures that the synchronous operation TO has
synchronized the leading axis and the following axis at a specific position, but
without consideration of the dynamic parameters from the "Dynamic response" tab.
ca

If any limits (velocity, acceleration, etc.) are exceeded during synchronization, they
are not applied until the TO of the following axis.
Note Setting SyncingMotion.VelocityMode = NON_CONTINUOUS calculates a non-
continuous synchronization profile. In this case, a straight line joins the start and end
point.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 Gearing in SIMOTION
Reference point for leading axis synchronization

Following axis
Synch. position

om
l.c
Leading axis

ai
Synchronize before synchronization position

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Synchronize symmetrically
Synchronize from synchronization position

Date:
File:
10.01.2013
MC-SMO-PRG_07.13
SITRAIN Training for
Automation and Drives
@
Reference point of The "Reference point of leading axis" (syncPosition-Reference) parameter is
leading axis position used to manipulate the position of the synchronization point during
synchronization:
Synchronize from synchronization position (syncPositionReference =
er

synchronize_when_position_reached): In this case, synchronization starts with


all other conditions (e.g. synchronization lengthe, etc.) when the
synchronization position is reached.
ez

Synchronize before synchronization posmition (syncPositionReference =


be_synchronous_at_position): Synchronization takes place so that all other
conditions (e.g. synclength, etc.) are ieadhered to and the following axis is
synchronized with the leading axsis at the synchronization position.
r.s

Symmetrical (syncPositionRefe rence = synchronize_symmetric): In this case,


synchronization takes place in symmetry with the specified synchronization
position.
Notice
In earlier versions (u<= V3.2), the synchronous operation command was
ne

aborted with the error melssage "50007: Error occurred while activating/
deactivating the synchronous operation" if the leading axis reversed during
leading axis synchronization. Asg of V4.0, a tolerance window can be defined
for aborting the synchoronization procedure if the master value was reversed
(syncinlgMotion.masterReversionTolerance).
ca

Wehen leading axis synchronization is selected, a synchronization length


greater than 0 must always be specified. A synchronization length of 0 can only
be specified if the following axis is synchronized directly with the leading axis at
standstill, for example. In this case, a corresponding message is also displayed.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 Gearing in SIMOTION
Synchronization with direction specification

Synchronization direction (synchronizingDirection) for the following axis

Leading axis
„ Retain system behavior (SYSTEM_DEFINED): Following
axis
(as originally in versions <= 3.0)

om
Leading axis
„ Shortest path (SHORTEST_WAY) Following
axis

l.c
„ Positive direction (POSITIVE_DIRECTION)

„ Negative direction (NEGATIVE DIRECTION)

ai
„ Maintain direction of the following axis (SAME_DIRECTION)

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.14
SITRAIN Training for
Automation and Drives
@
Functionality Depending on the difference between the leading axis and the following axis,
many machines require synchronization related to the positive direction, negative
direction, or shortest path. This function is relevant, for example, for modulo axes,
for which synchronization is possible in both directions. With non-modulo axes,
er

the parameter is not taken into account (SYSTEM_DEFINED applies).


The direction of motion of the following axis in the synchronization phase can be
defined with the synchronizingDirection parameter. The criterion for the definition
is the direction of motion of the following axis at the synchronization point
ez

corresponding to the synchronous operation rule (plus possibly the current


direction of motion of the master).

SYSTEM_DEFINED Retain present system behavior (as in <= V3.0). In case of a moving slave axis, a
check is made to determine whether the direction of motion can be retained.
r.s

SAME_DIRECTION The same direction of motion of the following axis at the synchronization point is
also retained for the synchronization phase (same direction of motion). As such, it
also depends on the master direction of motion.
ne

• During synchronization when the master is at a standstill, the direction of


motion of the slave is retained.
• During synchronization both when the master is at a standstill and when the
slave is at a standstill, synchronization is performed related to the positive
direction.
ca

SHORTEST_WAY Synchronize to the "shortest way", regardless of which direction of motion results
in the synchronization phase.

POSITIVE/NEGATIVE Positive / negative synchronization direction.


DIRECTION • An error message is displayed if the required synchronization cannot be
performed in the specified direction.
• The function is not relevant for velocity gearing, because the axis accelerates
directly to the new velocity.
SITRAIN Training for MC-SMO-PRG
Automation and Drives Page 14 Gearing in SIMOTION
Enabling gearing in ST
Enable gearing
RetVal := _enablegearing(
followingobject, // Specification of synchronous object
direction, // Specification of gear direction
gearingtype, // Master evaluation: abs., relative?
gearingmode, // Fraction or floating-point number
gearingratiotype, // Type parameter for gear ratio
gearingratio, // Floating-point number

om
gearingnumerator, // Gear ratio numerator
gearingdenominator, // Gear ratio denominator
synchronizingmode, // Synchr., lead. axis pos.?, immediate?..
syncpositionreference, // Before, after, symmetrical?
syncprofilereference, // Leading-axis-related or time-related
synclengthtype, // Type "Synch.length": direct,...?
synclength, //Synchronization length

l.c
syncpositionmastertype, // Type "Lead. axis pos.": direct, user-def.?
syncpositionmaster, // Leading axis position
syncpositionslavetype, // Type "Slave offset": direct,...?
syncpositionslave, // "Offset in slave direction"
velocitytype, // Type "Veloc.": direct, user-def.?

ai
velocity, // Velocity: Only if direct
. . ., // Remaining dynamic parameters
mergemode, // Substitute, attach, etc.?
nextcommand, // Wait for ... ?

SIMOTION
Commandid,

Siemens AG 2013. All rights reserved.


// Command ID

gm
synchronizingDirection);// Specific. of synchronization direction
// (V3.1 specifically for rotary axes)

Date:
File:
10.01.2013
MC-SMO-PRG_07.15
SITRAIN Training for
Automation and Drives
@
_enablegearing The _enablegearing system function is used to enable gearing in the ST
language.
ST MCC
er

followingobject: "Parameter", following axis


direction "Parameter", gear direction
gearingtype "Parameter", reference point
gearingmode "Parameter", gear ratio mode
ez

gearingratiotype "Parameter", gear ratio type


gearingratio "Parameter", gear ratio
gearingnumerator "Parameter", numerator
gearingdenominator "Parameter", denominator
r.s

synchronizingmode "Synchr.", start of synchronization


syncpositionreference "Synchr.", reference point of leading axis
syncprofilereference "Synchr.", synchronization reference
synclengthtype "Synchr.", synchronization length type
ne

synclength "Synchr.", synchronization length


synchpositionmastertype "Synchr.", leading axis position type
synchpositionmaster "Synchr.", leading axis position
syncpositionslavetype "Synchr.", offset type
syncpositionslave "Synchr.", offset
ca

velocitytype "Dynamic response", velocity


velocity "Dynamic response", velocity
...
mergemode "Parameter", transition behavior
nextcommand "Parameter", delay program execution
commandId "Expert", CommandId variable
synchronizingDirection "Synchr.", synchronization direction

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 Gearing in SIMOTION
"Optimum" synchronization profile (leading axis synchronization)

om
Sensor

Sensor Following axis Synch.


position position position

Position

l.c
Synchronization
length

ai
Following axis position =
Leading axis position

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.16
Time

SITRAIN Training for


Automation and Drives
@
"Optimum" With leading axis synchronization, an "optimum" synchronization profile can be
synchronization achieved for position synchronous operation with constant leading axis velocity
profile and stationary following axis. In this case, optimum means:
• The velocity of the following axis does not exceed the velocity of the leading
er

axis
• The following axis is not reversed at the start of synchronization

This optimum synchronization behavior can be achieved by making the following


ez

Settings
settings:
• Synchronization reference: leadsiing axis
• Start of synchronization: at leading axis position
• Reference of the lead@ing axis position: symmetrical
r.s

Additionally, the position of the following axis must be the same as the position
of the leading axis at the start of synchronization:
Following axislu position = leading axis position
With these settings, the velocity of the following axis is increased to the
ne

velocity of the leading axis in a linear fashion. The acceleration of the following
axis is dependent of the synchronization length.
With tehe following axis at rest, the acceleration of the following axis can be
calculated as follows:
ca

Acceleration = (leading axis velocity)2 / synchronization length

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 Gearing in SIMOTION
Useful system variables for synchronization

Position
Leading axis
GL-TO.current-
syncposition.
slave

om
GL-TO.current-
syncposition.
master

l.c
Following axis
Time

ai
Start of synchronization: Synchronicity:
GL-TO.state = gearing GL-TO.syncstate = yes
FA-TO.syncmonitoring. FA-TO.syncmonitoring.

SIMOTION
Siemens AG 2013. All rights reserved.
gm
followingmotionstate = BASIC_MOTION_ACTIVE

Date:
File:
10.01.2013
MC-SMO-PRG_07.17
syncstate = yes

GL-TO: Synchronous object for following axis


FA-TO: Technology object following axis

SITRAIN Training for


Automation and Drives
@
System variables A number of system variables are available at the synchronous object for
monitoring the status of synchronization during synchronous operation.

GL-TO.state The state system variable at the synchronous object indicates whether gearing
er

(state = gearing) or camming (state = camming) is active.


The system variable is set to the appropriate value at the start of
synchronization and reset at the end.
ez

GL-TO.syncstate This system variable displays the state of synchronicity between leading axis
and following axis at the synchronous object. If the leading axis and the
following axis are synchronized, this variable is set to "yes".
The start of desynchronization or any other loss of synchronization causes the
r.s

variable to be reset to no.

Note The syncstate system variable being set to "yes" simply indicates that following
calculation of the synchronous object, the leading axis value supplied (GL-TO.
currentmasterdata.value) and the slave value output at the TO of the following
ne

axis (GL-TO.currentslavedata.value) are synchronized.


Any limitation of the transferred slave value by the following axis TO resulting in
non-synchronism between leading axis and following axis is not mirrored in the
state of the "syncstate" variable.
ca

Sync. position The synchronization position of each of the leading axis and the following axis,
i.e. the position from which the leading axis and the following axis are operating
in synchronism, is saved in the following two variables:
• GL-TO.currentsyncposition.master
• GL-TO.currentsyncposition.slave

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 Gearing in SIMOTION
Leading axis synchronization (absolute synchronous operation)

om
Master velocity (10 mm/s) Slave velocity

"state"
"syncstate"
Master pos.

l.c
Slave pos.

ai
Gearing: Absolute, i.e. relative to axis zero
Gear ratio: 1:1

SIMOTION
Synchronize:
Synchronization length:

Siemens AG 2013. All rights reserved.


Immediately
30 mm
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.18
SITRAIN Training for
Automation and Drives
@
Absolute synchro- This diagram illustrates synchronization with absolute synchronous operation.
nous operation The following settings have been made on the individual tabs:

Parameters Gear ratio: 1 : 1


er

Reference point: Gearing takes place relative to axis zero (absolute gearing, i.e.
position synchronous operation)
ez

Synchronize Synchronization reference: Leading axis


Start of synchronization: immediately
Synchronization length: 30 mm
r.s

Execution The synchronous operation TO of the following axis calculates the required
position/angle reference between leading axis and following axis from the
specified leading axis position and the synchronization length.
In this case, synchronization is initiated immediately. A parabolic acceleration
ramp is used to accelerate the speed of the following axis to that of the leading
ne

axis. At the end of the synchronization length (30 mm), the position of both axes
is synchronous.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 Gearing in SIMOTION
Leading axis synchronization (relative synchronous operation)

"syncstate"
"state"

om
Master velocity (10 mm/s)
Master pos.

l.c
Slave pos.
Slave velocity

ai
Gearing: Relative, i.e. relative to start position
Gear ratio: 1:1

SIMOTION
Synchronize:
Synchronization length:

Siemens AG 2013. All rights reserved.


Immediately
30 mm
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.19
SITRAIN Training for
Automation and Drives
@
Relative synchro- This diagram illustrates synchronization with relative synchronous operation.
nous operation The following settings have been made on the individual tabs:

Parameters Gear ratio: 1 : 1


er

Reference point: Gearing takes place relative to start position (relative gearing,
i.e. velocity gearing)
ez

Synchronize Synchronization reference: Leading axis


Start of synchronization: immediately
Synchronization length: 30 mm
r.s

Execution Synchronization is started immediately. The velocity of the following axis is


accelerated to that of the leading axis in a linear fashion. At the end of the
synchronization length (30 mm), the velocity of both axes is synchronous.
The position offset at the end of synchronization between the leading axis and
following axis results from the offset at the beginning of synchronization (approx.
ne

15 mm) and the offset during synchronization itself (15 mm).


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 Gearing in SIMOTION
Time-related synchronization

Position/Velocity Following axis velocity

Leading axis
velocity

om
Position
Leading axis

Position

l.c
Following axis Time

Start End

Time-related synchronization profile

ai
• Specification of dynamic parameters -> SIMOTION calculates a time-related
and a position synchronization profile

SIMOTION
• Start position
• End position

Siemens AG 2013. All rights reserved.


gm
Date:
File:
-> Trailing synchronization
-> Leading synchronization

10.01.2013
MC-SMO-PRG_07.20
SITRAIN Training for
Automation and Drives
@
Time-related When time-related synchronization is selected, SIMOTION calculates the
synchronization synchronization profile using a specified position and the parameters from the
"Dynamic response" tab.
Dependent upon whether the start or end position of the synchronization
er

procedure is specified, SIMOTION differentiates between:

• Trailing synchronization:
ez

Selected with "Synchronize from synchronization position" or by setting


(syncPositionReference = synchronize_when_position_reached).
• Leading synchronization:
Selected by setting "Synchronize iebefore synchronization position" or
r.s

Notes
(syncPositionReference = be_synchronous_at_position).
• "Symmetrical" cannot be selected for time-related synchronization.
The command is rejected with the following error message:
"030001 - Alarm followingObjectType
ne

Illegal parameter"
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 Gearing in SIMOTION
Trailing synchronization (how it works)
Following axis
Position/Velocity velocity

Leading axis
velocity

om
Position
Leading axis

Position

l.c
Following axis Time

Start position

ai
Trailing synchronization profile
• Specification of start position
• Velocity

SIMOTION
• Acceleration

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.21
SITRAIN Training for
Automation and Drives
@
Trailing When trailing synchronization is selected, SIMOTION calculates the
synchronization synchronization profile using the specified position and the parameters from the
"Dynamic response" tab. The end point of synchronization is determined from
the dynamic values and the behavior of the leading axis.
er

At the start, the following axis is accelerated to the specified velocity at the rate
of acceleration indicated. At the end of synchronization, the target velocity of the
leading axis is reached.
ez

Notes • If the velocity of the leading axis changes during the synchronization
procedure, the synchronization profile is recalculated. The end point of the
synchronization procedure is then brought forward (reduction in velocity of
leading axis) or put back (increase in velocity of leading axis) accordingly.
r.s

• When the profile is recalculated, by default, only the instantaneous


position and velocity of the leading axis are taken into account. To include
the acceleration of the leading axis in the calculation, "Extended look-ahead"
must be selected in the synchronous operation command.
• The synchronization profile is also recalculated if the leading axis
ne

reverses its direction of motion during the synchronization procedure.


• The configuration data item "syncingMotion.maximumOfMasterChange" is
of no relevance in trailing synchronization. The synchronization profile is
always recalculated whenever the velocity of the leading axis changes.
• By default, only the trapezoidal velocity profile is supported in time-related
ca

trailing synchronization on the "Dynamic response" tab. For the constant


velocity profile, the configuration data item (Settings -> Allow absolute
synchronization with consideration of jerk):
SyncingMotion.SmoothAbsoluteSynchronization = Yes
must be set.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 Gearing in SIMOTION
Trailing synchronization (trace recording)

"state"

Slave velocity

om
"syncstate"

Master velocity (100 mm/s)

Slave pos.

l.c
Master pos.

ai
Gearing: Absolute, i.e. relative to axis zero
Synchronization direction: Shortest path
Synchronize: From leading axis position 150 mm

SIMOTION
Velocity:
Acceleration:
Jerk:

Siemens AG 2013. All rights reserved.


200 mm/s
200 mm/s2
500 mm/s3

Date:
File:
gm 10.01.2013
MC-SMO-PRG_07.22
SITRAIN Training for
Automation and Drives
@
Trailing This diagram illustrates synchronization with a trailing synchronization profile.
synchronization The following settings have been made on the individual tabs:

Parameters Gear ratio: 1 : 1


er

Reference point: Gearing takes place relative to axis zero (absolute gearing, i.e.
position synchronous operation)
ez

Synchronize Synchronization reference: Time


Start of synchronization: From leading axis position
Reference point of the leading axis position: Synchronize from synchronization
i

position
r.s

Leading axis position: 150 mm

Dynamic response Velocity: 200 mm/s

Acceleration: 200 umm/s2


ne

Jerk: 500 mm/s2


Execution The synchoronous operation TO of the following axis calculates a time-related
synchronization profile using the specified velocity and acceleration of the
followeling axis and assuming constant leading axis velocity.
Synkchronization of the following axis starts at a leading axis position of 150
ca

mm. At the end of the jerk phase, the velocity of the following axis is accelerated
in a linear fashion along the programmed acceleration ramp to the programmed
velocity.
At the end of the constant motion phase, the following axis is synchronized with
the dynamic response of the leading axis in accordance with the specified
parameters.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 Gearing in SIMOTION
Trailing synchronization with reversing of leading axis

Slave velocity

om
Master pos. Slave pos.

"syncstate"

l.c
"state"
Master velocity

ai
Gearing: Absolute, i.e. relative to axis zero
Synchronization direction: Shortest path
Synchronize: From leading axis position 150 mm

SIMOTION
Velocity:
Acceleration:
Jerk:

Siemens AG 2013. All rights reserved.


200 mm/s
200 mm/s2
500 mm/s3 gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.23
SITRAIN Training for
Automation and Drives
@
Trailing This diagram illustrates synchronization with a trailing synchronization profile.
synchronization
During the synchronization procedure, the leading axis reverses.
Parameters Gear ratio: 1 : 1
er

Reference point: Gearing takes place relative to axis zero (absolute gearing, i.e.
position synchronous operation)
Synchronization reference: Time
ez

Synchronize Start of synchronization: From leading axis position


Reference point of the leading axiis position: Synchronize from synchronization

position
Leading axis position: 150 mm
r.s

Dynamic response Velocity: 200 mm/s


Acceleration: 200 umm/s2
Jerk: 500 mm/s2
ne

As in the porevious case, the synchronous operation TO of the following axis


Execution calculatles a time-related synchronization profile using the specified velocity and
acceeleration of the following axis and assuming constant leading axis velocity.
Synkchronization of the following axis starts at a leading axis position of 150
mm. At the start, the velocity of the following axis is accelerated to the programmed
ca

velocity.
The leading axis reverses in the middle of the deceleration phase. If the
"Extended look-ahead" setting has not been selected, the following axis will
overtake the leading axis at the start of deceleration and synchronize accordingly
with the leading axis subsequently.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 Gearing in SIMOTION
Leading synchronization (how it works)

Specified velocity
Position/Velocity and acceleration

syncingMotion.
maximumOfMasterChange

om
Actual velocity and
acceleration
Leading axis
velocity

Position

l.c
Leading axis
Position
Following axis
Time

ai
End position
Leading synchronization profile
• Specification of end position

SIMOTION
• Velocity
• Acceleration

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.24
SITRAIN Training for
Automation and Drives
@
Leading When leading synchronization is selected, SIMOTION also calculates the
synchronization synchronization profile using the parameters from the "Dynamic response" tab
and the specified end position. The start point of synchronization is determined
from the end point, the dynamic values, and the behavior of the leading axis.
er

During leading synchronization, the synchronization motion starts:


• At the point in time determined by the specified dynamic parameters of the
following axis with constant master value velocity assumed during
synchronization to optimize the approach to the synchronization point
ez

(moving master value)


• Immediately if an optimum synchronization time cannot be calculated and
the synchronization point can be reached (stationary master value, for
example).
r.s

With leading synchronization, the dynamic parameters are reduced according to


the value set in the configuration data item:
syncingMotion.maximumOfMasterChange. The following axis then accelerates
at the reduced rate of acceleration to the reduced velocity.
If the master value velocity changes, the dynamic response values of the
ne

following axis change accordingly. If the tolerance band specified with the
configuration data item syncingMotion.maximumOfMasterChange is overshot or
undershot, the following error message is displayed:
• 050009 - Alarm followingObjectType
ca

Changing the dynamic response of the master leads to a dynamic violation


when synchronizing and desynchronizing.

Note If the leading axis reverses its direction of motion during synchronization by
more than the values specified in the settings in the tolerance window,
synchronization is aborted with the following error message:
• 050007 - Alarm followingObjectType
Error while activating/deactivating synchronous operation

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 Gearing in SIMOTION
Leading synchronization (trace recording)

Slave velocity
"state"

om
"syncstate"
Master pos.

Master velocity (100 mm/s)

Slave pos.

l.c
Gearing: Absolute, i.e. relative to axis zero

ai
Gear ratio: 1:1
Synchronize: to leading axis position 800 mm
Velocity: 200 mm/s
Acceleration: 500 mm/s2

SIMOTION
Jerk:
MaxOfMasterChange:

Siemens AG 2013. All rights reserved.


1,000 mm/s2
20%
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.25
SITRAIN Training for
Automation and Drives
@
Leading This diagram illustrates synchronization with a leading synchronization profile.
synchronization The following settings have been made on the individual tabs:
Gear ratio: 1 : 1
Parameters Reference point: Gearing takes place relative to axis zero (absolute gearing, i.e.
er

position synchronous operation)


Synchronization reference: Time
Start of synchronization: From leadiing axis position
Reference point of the leading a sxis position: Synchronize before
ez

Synchronize
synchronization

position
Leading axis position: 800
r.s

@mm
Dynamic response Velocity: 200 mm/s

Acceleration: 500 lmm/s2


ne

Jerk: 1,000 gmm/s3


Execution The sylnchronous operation TO of the following axis calculates a time-related
syncheronization profile using the specified velocity and acceleration of the
fokllowing axis and assuming constant leading axis velocity.
Synchronization is started at the optimum time before the synchronization
ca

position. At the start, the following axis is accelerated to the reduced velocity
(160 mm/s) along the reduced acceleration ramp ("MaxOfMasterChange" =
20%).
When the brake is applied, the following axis is decelerated to the leading axis
velocity along the reduced brake ramp. The following axis runs in synchronism
with the leading axis from the 800 mm position.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 25 Gearing in SIMOTION
Leading synchronization, changing the leading axis velocity (1)

"state"
Slave velocity

om
"syncstate"

Master pos.
Master velocity (110 mm/s)

l.c
Slave pos.

Gearing: Absolute, i.e. relative to axis zero

ai
Gear ratio: 1:1
Synchronize: to leading axis position 800 mm
Velocity: 200 mm/s

SIMOTION
Acceleration:
Jerk:
MaxOfMasterChange:

Siemens AG 2013. All rights reserved.


500 mm/s2
1,000 mm/s2
20% gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.26
SITRAIN Training for
Automation and Drives
@
Leading This diagram illustrates synchronization with a leading synchronization profile.
synchronization The following settings have been made:
Gear ratio: 1 : 1
Parameters Reference point: Gearing takes place relative to axis zero (absolute gearing, i.e.
er

position synchronous operation)


Synchronization reference: Time
Start of synchronization: From leading axis position
Synchronize Reference point of the leading axiis position: Synchronize before
ez

synchronization

position
Leading axis position: 800 mm
r.s

Dynamic response Velocity: 300 mm/s

Acceleration: 500 umm/s2


Jerk: 1,000 mm/sl2
ne

MaxOfMasterCghange: 20%
The sylnchronous operation TO of the following axis calculates a time-related
Execution synchronization profile using the specified velocity and acceleration of the
following axis and assuming constant leading axis velocity.
Synchronization is started at the optimum time before the synchronization
ca

position. The following axis is accelerated to the reduced velocity (160 mm/s)
along the reduced acceleration ramp.
After this, the leading axis velocity is increased from 100 mm/s to 110 mm/s
(< 20%). If the synchronization profile is not recalculated, there is a percentage
increase (10%) in the velocity of the following axis.
At the original point of brake application, the following axis is then decelerated to
the leading axis velocity in a linear fashion along an increased brake ramp. The
following axis runs in synchronism with the leading axis from the 800 mm position.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 26 Gearing in SIMOTION
Leading synchronization, changing the leading axis velocity (2)

Slave velocity

"state"

om
"syncstate"

Master pos.
Master velocity (150 mm/s)

l.c
Slave pos.

ai
Gearing: Absolute, i.e. relative to axis zero
Gear ratio: 1:1
Synchronize: to leading axis position 800 mm
Velocity: 200 mm/s

SIMOTION
Acceleration:
Jerk:
MaxOfMasterChange:

Siemens AG 2013. All rights reserved.


500 mm/s2
1,000 mm/s2
20%
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.27
SITRAIN Training for
Automation and Drives
@
Leading This diagram illustrates synchronization with a leading synchronization profile.
synchronization The following settings have been made:

Parameters Gear ratio: 1 : 1


er

Reference point: Gearing takes place relative to axis zero (absolute gearing, i.e.
position synchronous operation)
ez

Synchronize Synchronization reference: Time


Start of synchronization: From leading axis position
Reference point of the leading axis position: Synchronize before synchronization
position
r.s

Leading axis position: 800 mm

Dynamic response Velocity: 300 mm/s


Acceleration: 500 mm/s2
Jerk: 1,000 mm/s2
ne

MaxOfMasterChange: 20%

Execution In this case, in the constant motion phase, the velocity of the leading axis is
increased from 100 mm/s to 150 mm/s (> 20%). If the synchronization profile is
ca

not recalculated, there will also be a percentage increase (50%) in the velocity
of the following axis.
The following alarm is also output:
050009 - Alarm followingObjectType
Changing the dynamic response of the master leads to a dynamic violation
when synchronizing and desynchronizing.
If the following axis is able to follow the dynamic response, the synchronization
point (800 mm) is retained.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 27 Gearing in SIMOTION
Synchronization without overshoot (engagement)
Specified speed
Position/Velocity and acceleration

Leading axis
velocity

om
Position
Following axis

Position

l.c
Leading axis Following axis velocity

Time

ai
End position
Leading synchronization profile
• Specification of end position

SIMOTION
• Acceleration
• Jerk

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.28
SITRAIN Training for
Automation and Drives
@
How it works The leading time-related synchronization strategy is the only one to offer a
solution for synchronizing a following axis which is moving in front of the leading
axis with a moving leading axis with feedback and without overshoot in velocity.
In particular, overshoot-free synchronization is also possible if the velocity of the
er

leading axis is unknown at the start of synchronization or if the velocity of the


leading axis changes after the synchronous operation command is issued.
The following settings (configuration data):
ez

• Adaptation of dynamic values during synchronization


(syncingMotion.synchronizingAdaption = yes)
• Overdrive factor
(syncingMotion.overDriveFactor = 100.001)
determine the velocity of the following axis during synchronization from the
r.s

maximum of the velocity value in the synchronous operation command and the
leading axis velocity with overdrive factor.
The following axis always synchronizes with the leading axis correctly, even if
the velocity of the leading axis changes during synchronization. Error messages
are only displayed if the dynamic values of the synchronous operation TO are
ne

violated or changed.

Notes • If the leading axis velocity increases during synchronization, the overdrive
factor must be set to slightly higher than 100% (e.g. 100.001%).
ca

Otherwise, internal algorithms will cause synchronization to be aborted.


• Where dynamic values are specified for the following axis, it is not possible
to provide a solution to this synchronization problem for every geometrical or
dynamic configuration of the leading and following axis. In cases where
a solution cannot be provided, synchronization is not started and there is no
additional error message or note in the system variables.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 28 Gearing in SIMOTION
Engagement (trace recording)

"state"

"syncstate"

om
Master velocity (100 mm/s)
Slave velocity

Master pos. Slave pos.

l.c
Gearing: Absolute, i.e. relative to axis zero

ai
Gear ratio: 1:1
Synchronize: to leading axis position 50 mm
Velocity: 1 mm/s
Acceleration: 500 mm/s2

SIMOTION
Jerk:
MaxOfMasterChange:

Siemens AG 2013. All rights reserved.


20%
gm
1,000 mm/s2

Date:
File:
10.01.2013
MC-SMO-PRG_07.29
SITRAIN Training for
Automation and Drives
@
Leading This diagram illustrates synchronization with a leading synchronization profile.
synchronization The following settings have been made:
Gear ratio: 1 : 1
Parameters Reference point: Gearing takes place relative eto axis zero (absolute gearing,
er

i.e. position synchronous operation)


Synchronization reference: Time
Start of synchronization: From leadieing axis position
Reference point of the leading axsis position: Synchronize before
ez

Synchronize
synchronization
position
Leading axis position: 50 mm@
r.s

Dynamic response Velocity: 1 mm/s


ne

Acceleration: 500 umm/s2


Jerk: 1,000 gmm/s2
MaxOfMasoterChange: 20%
Adjulstment of the dynamic response values during synchronization: Selected
ca

Overderive factor: 100.001%


Execution
Synchronization is started at the optimum time before the synchronization
position. The start point is determined by the dynamic parameters of the
synchronous operation command or the instantaneous speed of the leading
axis. Once synchronization is underway, the following axis is accelerated to the
velocity (100 mm/s) of the leading axis along the acceleration ramp reduced by
"MaxOfMasterChange".

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 29 Gearing in SIMOTION
Enabling gearing in MCC (3)

om
Settings for:
• Velocity profile
• Velocity
• Acceleration

l.c
• Jerk

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.30
SITRAIN Training for
Automation and Drives
@
Dynamic response Settings for the velocity profile, velocities, acceleration, and jerk of the axis
during synchronization and desynchronization are made on the "Dynamic
response" tab.
These dynamic settings can only be entered when selecting a time-related
er

synchronization profile. If a leading axis synchronization reference is selected,


no dynamic settings are taken into account.
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 30 Gearing in SIMOTION
Enabling gearing in MCC (4)

om
Variables for recording the
• CommandId
and the return value of:
• Set master setpoint

l.c
• Camming on

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.31
SITRAIN Training for
Automation and Drives
@
CommandId The status of motion commands can be tracked with the CommandId, which is
unique throughout a project. Previously, the CommandId was reserved for use
in ST programming. However, as of V4.0, it can also be used in MCC
commands.
er

If you enter the name of a variable of data type CommandIdType, you can track
the command status with this variable. The variable (data type: DINT) must
previously have been declared in the MCC source file or in the MCC chart.
If the "Assign value" box is checked, a CommandId that is unique throughout the
ez

project is automatically generated, stored in the variables, and transferred to the


command. If the box is not checked, the variable is simply transferred to the
command. You must take steps to ensure that a CommandId that is unique
throughout the project is stored in the variable. You can do this with the
_getCommandId() function.
r.s

If the field is left blank, no variables are assigned to the CommandId parameter
of the command. If the field is blank, the "Assign value" box must be checked.

Return values Many MCC commands are mapped to one or more system functions. They
ne

usually send a return value to the user indicating whether or not the call has
been successful.
If a variable of the specified data type is entered, the return value of the
command step is saved in this variable. The variable must previously have been
declared in the MCC source file or in the MCC chart.
ca

If the field is left blank, the return value of the command step is assigned to an
internal variable which cannot be accessed by the MCC chart (default setting).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 31 Gearing in SIMOTION
Disabling gearing in MCC

Gearing off

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.32
SITRAIN Training for
Automation and Drives
@
Gearing Gearing is disabled in a similar way to that in which it is enabled. You simply
have to enter the leading axis and the following axis for which gearing is to be
disabled on the "Parameters" tab.
The type of desynchronization is specified on the "Desynchronization" tab. The
er

possible parameter settings are exactly the same as those for synchronization.
Either a leading-axis-related or a time-relamted synchronization profile can be
Synchronization selected here. As with synchronization:
reference
ez

• The dynamic parameters are ineffecetive with a leading-axis-related profile


• With a time-related profile, the diynamic parameters are effective, but the
position is difficult to deter smine at the end of desynchronization procedure
r.s

Desynchronization For desynchronization, the@ position of the leading axis or the


position following axis, or "Desynchroni ze immediately" can be selected.
Here again it isl possible to choose between before or after the
Reference point of synchronization position and, in the case of a leading-axis-related
desynch. position
ne

synchronization profile, in symmetry withg the synchronization position.

Desynchronization For a elleading-axis-related profile, the desynchronization length can be


length specified here.
ca

Leading axis/follow- If the position of the leading or following axis has been selected as the
ing axis position desynchronization position, the required position can be specified here.

Dynamic parameters If a time-related desynchronization profile has been selected, the


dynamic values for the desynchronization procedure can be specified
here.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 32 Gearing in SIMOTION
Disabling gearing in ST

Disable gearing
RetVal := _disablegearing(
followingobject, // Specification of synchronous object
syncoffmode, // Master or slave pos.?
syncoffpositionreference,//Before/after leading axis pos., symm.?
syncprofilereference, // Leading-axis-related or time-related

om
syncofflengthtype, // Type "Desynch. length", direct,...?
syncofflength, // Desynchronization length
syncoffpositionmastertype,// Type "Lead. axis pos.": direct,
user-def.?
syncoffpositionmaster, // Leading axis position
syncoffpositionslavetype,// Type "Slave pos.": direct,...?
syncoffpositionslave, // Slave position

l.c
velocitytype, // Type "Veloc.": direct, user-def.?
velocity, // Velocity: Only if direct
. . ., // Remaining dynamic parameters
mergemode, // Substitute, attach, etc.?
nextcommand, // Wait for ... ?

ai
commandid); // Command ID

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.33
SITRAIN Training for
Automation and Drives
@
_disablegearing This function is used to deselect gearing:

MCC ST
er

followingobject: "Parameter", synchronous object


synchoffmode "Desynchronize", desynchronization position
syncoffpositionreference "Desynchronize", desynchronization ref. point
ez

syncprofilereference "Desynchronize", synchronization reference


syncofflengthtype "Desynchronize", type: desynchr. length
syncofflength "Desynchronize", desynchr. length
syncoffpositionmastertype "Desynchronize", type: leading axis position
r.s

syncofftpositionmaster "Desynchronize", leading axis position


syncoffpositionslavetype "Desynchronize", type: following axis position
syncoffpositionslave "Desynchronize", following axis position
velocitytype "Dynamic response", type: velocity
ne

velocity "Dynamic response", velocity


...
mergemode "Parameter", transition behavior
ca

nextcommand "Parameter", delay program execution


commandId "Expert", CommandId variable

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 33 Gearing in SIMOTION
Enabling velocity gearing in MCC

Velocity gearing

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.34
SITRAIN Training for
Automation and Drives
@
Velocity Unlike gearing or camming, velocity gearing relates not to the position of an axis
gearing but to its velocity, with constant gear ratio between master value source and
following axis.
With velocity gearing, non-position-controlled (i.e. speed-controlled)
er

synchronous operation up to the velocity of a leading axis is activated on an axis


that is set as a position-controlled axis (following axis).
The master value can be:
ez

• Velocity of a leading axis set as a position-controlled axis


• Velocity of an external encoder

Enable/ Velocity gearing is enabled with the _enableVelocityGearing command. The


Disable dynamic parameter settings induce acceleration up to the synchronous
r.s

operation velocity or from the synchronous operation velocity to the new target
velocity.

Transmission A linear transmission function is implemented. A gear ratio can be specified.


function An additional velocity offset cannot be specified.
ne

Direction The gear ratio can be set in the same direction or in the opposite direction
(corresponding to a negative gear ratio) using the "Gear direction" parameter.
ca

Monitoring The syncMonitoring system variable on the following axis also displays the
status of velocity gearing (as of V3.1):
• differenceCommandVelocity: Setpoint difference in velocity between
master and slave (only valid for velocity gearing).
• differenceActualVelocity: Actual difference in velocity between
master and slave (only valid for velocity gearing).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 34 Gearing in SIMOTION
Enabling velocity gearing in ST

Enable velocity gearing


RetVal := _enablevelocitygearing(
followingobject, // Specification of synchronous object
direction, // Direction specification
gearingratiotype, // Type parameter
gearingratio, // Gear ratio

om
positiveacceltype, // Dynamic parameters for synchronization
positiveaccel, // procedure
negativeacceltype, //
negativeaccel, //
positiveaccelstartjerktype, //
positiveaccelstartjerk, //

l.c
positiveaccelendjerktype, //
positiveaccelendjerk, //
negativeaccelstartjerktype, //
negativeaccelstartjerk, //
negativeaccelendjerktype, //

ai
negativeaccelendjerk, //
velocityprofile, //
mergemode, // Attach, substitute, etc.

SIMOTION
nextcommand,
commandid);

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.35
SITRAIN Training for
Automation and Drives
@
_enablevelocity- The _enablevelocitygearing system function is used to enable true velocity
gearing gearing in the ST language.
ST MCC
er

followingobject: "Parameter", following axis


direction "Parameter", direction
gearingratiotype "Parameter", gear ratio type
gearingratio "Parameter", gear ratio
ez

velocitytype "Dynamic response", velocity


velocity "Dynamic response", velocity
...
mergemode "Parameter", transition behavior
r.s

nextcommand "Parameter", delay program execution


commandId "Expert", CommandId variable
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 35 Gearing in SIMOTION
Set master setpoint (_setmaster)

Switch master setpoint

om
l.c
ai
Assignment of a leading axis (master) to a synchronous object
RetVal := _setmaster(
followingobject, // Specification of synchronous object

SIMOTION
master,
...);

Siemens AG 2013. All rights reserved.


gm
Date:
File:
// Specification of master
// Dynamic values

10.01.2013
MC-SMO-PRG_07.36
SITRAIN Training for
Automation and Drives
@
Set This command switches the master setpoint for an existing synchronous
master/slave operation relationship. The master/slave can be set when synchronous
operation is active.
The _setMaster() command is used to assign a new master value source to a
er

synchronous object. When it is enabled, the master values are referenced to the
units system of the current master value source.

Transition process A relative or absolute coupling influences the transition process. The transition
ez

behavior when the master value source is set is different for absolute
synchronous operation and relative synchronous operation.
• With a relative coupling, an additional slave value discrepancy occurs only if
the dynamic master values are different with regard to velocity and
r.s

acceleration.
• With absolute coupling, a non-continuous master value transition can occur.
Slave value monitoring at the following axis limits discontinuities in the slave
values to the maximum dynamic axis parameters; compensating motion is
generated in some cases.
ne

Different modulo settings of the master value sources are taken into account.
The dynamic parameters for the compensating motion can also be included in
the command. To include them in the command, select "With programmed
dynamic values" in the "Transition behavior" field. Selecting "Direct" might lead
to a reduction in the dynamic values in the following axis TO.
ca

Note If a synchronous object is assigned to multiple master values, a master value is


selected at random internally following system startup. The correct master value
must be specified in the user program.
For programming in MCC, the commands _enablegearing and _enablecamming
already have a leading axis assignment via the _setmaster command.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 36 Gearing in SIMOTION
Set in synchronous motion (trace recording)

Compensating motion

Slave velocity
"state"

om
_setMaster
Master_2

Slave pos.
Master_1
"syncstate"

l.c
Slave velocity

ai
Gearing: Absolute, i.e. relative to zero
Gear ratio: 1:1

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.37
SITRAIN Training for
Automation and Drives
@
General This diagram shows a switch on-the-fly between two master values with an
absolute synchronous operation coupling. In this case, synchronous operation
monitoring of the position setpoint had been disabled.
er

Execution First, the following axis is synchronized with the axis position of Master_1. The
synchronization procedure starts at the Mastere_1 position of 70 mm and is
completed at 110 mm.
With a Master_2 position of 180 mm, the _setmasm ter call is sent to the
ez

synchronous object of the following axis with the new master value of Master_2.
Since the following axis is in absolute position synchronous operation,
compensating motion is started firsit to move the following axis to the set
position of Master_2. This compensatings motion is executed with the specified
r.s

dynamic values of the following axis.


After this compensating@ motion, the following axis moves synchronized with
the position of the Master_2 axis.
Note
In the case of relalutive synchronous operation, there is no compensating
ne

motion in the set position.


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 37 Gearing in SIMOTION
Set offset on the gearing in MCC

Set offset on the gearing

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.38
SITRAIN Training for
Automation and Drives
@
Functionality With gearing, this function activates an offset in the master or slave range. A
master range offset moves a straight line which has not moved forward in the X
direction. A slave range offset moves the straight line forward in the Y direction.
The dynamic values for the transition can also be specified. The current and
er

permanent offsets in effect can be read in the system variables of


"gearingAdjustments"

Range Here you select whether the leading axis or following axis range will be offset.
ez

Master range (default value): The leading axis range is offset.


Slave range: The following axis range is offset.

Offset Offset for the selected range. Enter the value as a signed floating-point number.
r.s

Mode Select the offset mode.


Absolute (default value): The offset is applied as an absolute value.
Relative: The offset is relative to the corresponding value in the
ne

"gearingAdjustments" system variable.

Effect Make a selection from this dropdown list box defining when the programmed
offset comes into effect:
ca

On active command (default value) The offset acts on the active gearing
command and remains active until this command is replaced or
desynchronization is activated with the "Gearing off" command.
On following commands: The active gearing command is executed; the offset is
stored and acts on subsequent "Gearing on" commands.
On active command and the following commands: The offset acts on the current
gearing command and all subsequent "Gearing on" commands.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 38 Gearing in SIMOTION
Set offset on the gearing in ST

Set offset at synchronous object


_setgearingoffset(
followingobject, // Specification of synchronous object
offsetrange, // Master or slave
offsetmode, // Absolute or relative
offsetvalue, // Value
velocitytype, // Dynamic parameters for the

om
velocity, // compensating motion
positiveacceltype, //
positiveaccel, //
negativeacceltype, //
negativeaccel, //
positiveaccelstartjerktype, //

l.c
positiveaccelstartjerk, //
positiveaccelendjerktype, //
positiveaccelendjerk, //
negativeaccelstartjerktype, //
negativeaccelstartjerk, //

ai
negativeaccelendjerktype, //
negativeaccelendjerk, //
velocityprofile, //
nextcommand, //

SIMOTION
commandid,
activationmode);

Siemens AG 2013. All rights reserved.


gm
Date:
File:
//
// Effectiveness

10.01.2013
MC-SMO-PRG_07.39
SITRAIN Training for
Automation and Drives
@
ActivationMode This parameter is also used to specify whether or not the _setgearingOffset
command is to act on the currently active gearing or on commands sent
subsequently.
• ACTUAL_VALUE
er

The offset acts on the active gearing and remains active until this is substituted
or gearing or desynchronized with the "_disablegearing" command.
• DEFAULT_VALUE
The active gearing command is executed, the offset is not taken into account for
ez

this command. The offset sis saved and acts on subsequent gearing commands.
• ACTUAL_AND_DEFAUL@T_VALUE
The offset acts on the current gearing command and on all subsequent
commands.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 39 Gearing in SIMOTION
Commands for reading out master and slave values in ST

Read out slave value of a synchronous operation relationship


_Retstructretgetvalue :=_getslavevalue(
followingobject, // Specification of
synchronous object
masterpositiontype, // CURRENT or DIRECT?

om
masterposition // DIRECT only
);

Read out master value of a synchronous operation relationship

l.c
_Retstructretgetvalue :=_getmastervalue(
followingobject, // Specification of
synchronous object
slavepositiontype, // CURRENT or DIRECT?

ai
slaveposition // DIRECT only
masterapproachpositiontype, // DIRECT or NONE
masterapproachposition // DIRECT only
);

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.40
SITRAIN Training for
Automation and Drives
@
General Commands that calculate values and supply them as return values are available
for reading out master value positions and slave value positions in pairs:
• When the master value position is programmed, the associated slave value
position is read out (_getSlaveValue)
er

• When the slave value position is programmed, the associated master value
position is read out (_getMasterValue)
ez

_getSlaveValue The _getSlaveValue command supplies the slave value at a specified master
value position. The following is applicable:
• When the master value position is CURRENT, the current slave value is
always returned, regardless of whether or not a synchronous relationship is
active.
r.s

• When the master value position is DIRECT, the specified master value
position is used. This command only supplies the correct slave value
position, if a synchronous relationship is active and synchronized.
• If camming is active, the cam must be interconnected and interpolated when
the command is executed.
ne

_getMasterValue The _getMasterValue command supplies the master value at a specified slave
value position (inverse mapping). The following is applicable:
• When the slave value position is CURRENT, the current master value is
ca

always returned, regardless of whether or not a synchronous relationship is


active.
• When the slave position is DIRECT, the specified slave position is used.
This command only supplies the correct position if a synchronous
relationship is active and synchronized.
• If camming is active, the cam must be interconnected and interpolated
when the command is executed.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 40 Gearing in SIMOTION
Actual value coupling with extrapolation (1)
„ Selection between setpoint and actual value coupling is
made when the synchronous object is configured

om
„ Extrapolation at the leading axis for actual value coupling:

TypeOfAxis.Extrapolation.extrapolationTime
TypeOfAxis.Extrapolation.ExtrapolationPositionFilter

l.c
extrapolationData.position
Filtered Position
actual position 2 x PT1 filter Extrapolation Velocity

ai
extrapolationData.velocity
Filtered PT1 filter or mean
actual velocity value generation

SIMOTION
Siemens AG 2013. All rights reserved.
gm
TypeOfAxis.Extrapolation.Filter

Date:
File:
10.01.2013
MC-SMO-PRG_07.41
extrapolationData.filteredvelocity

SITRAIN Training for


Automation and Drives
@
Actual value An interface on the leading axis (position axis, synchronous axis, ext. encoder)
coupling is available for actual value coupling; this interface is created automatically
every time by the axis or external encoder. The configuration settings for the
synchronous object specify whether the setpoint interface or the actual value
er

interface of the leading axis is used. With an external encoder, only the actual
value interface is available.

Extrapolation Extrapolation compensates the local delays (dead times) resulting from using
ez

the actual value instead of the setpoint. Extrapolation is set and parameterized
at the leading axis with the following configuration data item. If 0.0 is entered,
there is no extrapolation.
• Extrapolation time (extrapolation.extrapolationTime).
r.s

Extrapolation starts with the smoothed velocity value being multiplied by the
extrapolation time. The resulting position offset is added to the smoothed
position value and sent to the synchronous operation TO of the following axis as
a new master value.
ne

Smoothing of the So that the position can be extrapolated accurately, the actual velocity must be
actual velocity smoothed accordingly so the "nervous" position changes by the encoder do not
lead to dramatic changes in actual velocity (by differentiation of the encoder
values).
As of V4.2, the individual signals and the parameter settings of the individual
ca

filters can be monitored and made respectively in the new signal flow dialogs.
The signal flow for extrapolation is found at the leading axis under the entry:
Signal flow -> Extrapolation

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 41 Gearing in SIMOTION
Actual value coupling with extrapolation (2)

Extrapolation time

om
Actual
position filter

Actual

l.c
velocity filter

ai
Hysteresis
settings

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.42
SITRAIN Training for
Automation and Drives
@
Smoothing of The position actual value is smoothed by connecting two PT1 filters in series.
of the position The corresponding time constants are set in the following configuration data:
• Time constant 1 (Extrapolation.PositionFilter.T1)
er

• Time constant 2 (Extrapolation.PositionFilter.T2)

Hysteresis In addition, a hysteresis element can be activated for the position value before
the master values are sent to the synchronous operation TO of the following axis
ez

(not shown in the diagram on this slide). The hysteresis element prevents the
would-be "reversing" of the leading axis in the event of "nervous" position
values.
With a leading-axis-related synchronization strategy, reversing the leading axis
would abort the synchronization procedure. The activation and size of the
r.s

hysteresis range can be set with the following configuration data:


• Tolerance window for position reversal
(Extrapolation.ToleranceRange.enable)
• Tolerance window (Extrapolation.ToleranceRange.Value)
ne

With the hysteresis active, it is also possible to select whether the velocity sent
to the synchronous operation TO of the following axis is generated from the
extrapolated position actual value (including hysteresis) by differentiation or the
extrapolated actual velocity is simply used.
• Extrapolation.extrapolatedVelocitySwitch
ca

Note The SRC\ 4_TOOLS directory on the Utilities & Applications CD contains the
"EXTRAPOLATION_EN_V1.1.XLS" program which will assist you in calculating
extrapolation times.
The extrapolation time can only be set exactly by recording the corresponding
actual positions of the leading and following axes with the trace tool.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 42 Gearing in SIMOTION
Structure of superimposed synchronous operation

LA LA
...
...
LA LA

CAM CAM

om
Synchronous Synchronous_

...
...

object object_1

CAM CAM

l.c
Following axis

ai
Basic synchronous object: Superimposed synchronous object:
SyncingMotion.motionImpact: SyncingMotion.motionImpact:
"Standard" "SuperImposed_Motion"

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.43
LA:
CAM:
Leading axis
Cam

SITRAIN Training for


Automation and Drives
@
Superimposed SIMOTION Version V3.0 and higher supports superimposed synchronous
synchronous operation in addition to standard synchronous operation. Superimposed
operation synchronous operation is achieved by interconnecting a second superimposed
synchronous object to an axis in addition to the (basic) synchronous object.
er

Connections to leading axes and cams can be configured from this


superimposed synchronized object.

Note Only one connection can be configured to each leading axis. Connections
ez

cannot be configured from the basic synchronous object and from the
superimposed synchronous object to the same leading axis.

Functions The functions for superimposed synchronization can be used in ST, LAD, and
MCC alike. All functions familiar from the basic synchronous object can be used
r.s

for the superimposed synchronous object (e.g._enablegearing, _disablegearing,


etc.).
In MCC, the selection of the leading axis (unique nature of configured
connection) defines whether the basic synchronous object or the superimposed
synchronous object is involved. If a leading axis assigned to the superimposed
ne

synchronous object is selected, a corresponding symbol is displayed after the


"Leading axis" selection box (dialog: "Gearing on", tab: "Parameters").

Coordinate system As in the case of a superimposed motion, each synchronous object has its own
ca

coordinate system. The "outputs" of the synchronous objects are added together
in the TO of the following axis. The output values of a synchronous object (and
thus also the motion component of the superimposed synchronous operation for
the axis) can be read out in the "currentSlaveData" system variables of the
synchronous object concerned.
The positions and dynamic values of the basic motion are also provided within
the TO of the following axis via the "basicmotion" system variable; the positions
and dynamic values of the superimposed motion are provided via the
"superimposedmotion" system variable.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 43 Gearing in SIMOTION
Example: Filling chocolate molds on a conveyor belt

Axis_2

om
Axis_1

Filler Molds

l.c
Sensor
Sheet

ai
Conveyor belt External encoder
(not driven by SIMOTION)

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.44
SITRAIN Training for
Automation and Drives
@
Filling chocolate The above slide illustrates the principle of a "filling installation" for chocolate
molds molds. The filling installation essentially consists of the conveyor belt and the
chocolate hopper.
The conveyor belt is not controlled by SIMOTION, but by a higher-level control
er

system. Producing various chocolate shapes - such as frogs, dog bones, balls,
etc. - involves a highly complex chain of processes where many stations are
connected in series.
To coordinate the chain of processes connected in series, the higher-level
ez

control system needs to continuously change the velocity of the conveyor belt.
The "chocolate mold filling station" must adjust to these conditions.

Filling motionless When the hopper fills a single motionless mold, it has to traverse to the origin
r.s

sheets of each mold and then traverse the appropriate contour relative to the sheet.
Where more chocolate is required in a mold due to its shape (e.g. the ends of a
dog bone), the hopper needs to remain in this position for longer; in places
where less chocolate is required in the mold (middle of a dog bone), the hopper
must move more quickly.
ne

A solution for complex motionless molds is provided by interpolating Axis_1 and


Axis_2 with cams.

Filling moving Sheets are transported at different speeds on the conveyor belt. To meet the
sheets requirements for speed variation, Axis_1 can be synchronized with the motion of
ca

the conveyor belt via an external encoder using basic gearing.


Then the appropriate relative motion for filling the molds can be modeled via
superimposed camming for Axis_1. Motion for Axis_2 is handled with basic cam
synchronization.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 44 Gearing in SIMOTION
Insert superimposed synchronous object

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_07.45
SITRAIN Training for
Automation and Drives
@
Insert super- In the SIMOTION project navigator, you can insert a maximum of one additional
imposed object superimposed synchronous object under a following axis. To do this, proceed as
follows:
1. Select the required following axis in the project navigator.
er

2. Right-click to open the context menu and select


Experts -> Insert superimposed synchronous object.
SIMOTION automatically inserts the superimposed synchronous object
ez

called <Axis_n_SYNC_2>.

When the superimposed synchrionous object is inserted, the configuration


data item syncingMotion.motionImpact is automatically set to the value
SUPERIMPOSED (value: STANDARD for the basic synchronous object).
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 45 Gearing in SIMOTION
Structure of distributed synchronous operation

CAM
Leading Synchro-

...
axis nous
object
CAM

om
Following
PROFIBUS axis
master

l.c
Synchro- CAM Synchro- CAM
nous nous
...

...
object object

ai
CAM CAM
Following Following
axis axis

SIMOTION
Siemens AG 2013. All rights reserved.
...
PROFIBUS
slave_1 gm
...

Date:
File:
10.01.2013
MC-SMO-PRG_07.46
PROFIBUS
slave_n

SITRAIN Training for


Automation and Drives
@
Distributed synchro- SIMOTION supports distributed synchronous operation. The "distributed
nous operation synchronous operation" functionality allows the master value source (axis or
external encoder) and the following axes to be created on different devices.
The leading axis (or the external encoder) is linked to the following axes via
er

PROFIBUS DP. With distributed synchronous operation, function groups can be


generated in a project so that a machine can be built from modules.
Synchronized axes no longer need to be controlled with the same control
system and can be distributed across multiple modules.
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 46 Gearing in SIMOTION
Creating cams in SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Using cams in SIMOTION .................................................................................................................. 2
Creating a cam ................................................................................................................................... 3
er

Creating cams with SIMOTION .......................................................................................................... 4


Using interpolation points to create cams in CamEdit ....................................................................... 5
Using interpolation points to define the basic form of a cam ............................................................. 6
ez

Defining the interpolation type in CamEdit ......................................................................................... 7


Comparison of the various interpolation types .................................................................................. 8
Defining behavior with gaps ............................................................................................................... 9
Defining the type of cam and master range ....................................................................................... 10
r.s

"Absolute", "cyclic relative", and "cyclic absolute" cams ................................................................... 11


Scaling and offsetting cams ............................................................................................................... 12
Using polynomials to create cams in CamEdit .................................................................................. 13
Motion laws in accordance with VDI .................................................................................................. 14
Creating geometry data with the VDI wizard ..................................................................................... 15
ne

Creating cams with CamTool ............................................................................................................. 16


Defining the range of the master and slave axes ............................................................................... 17
Inserting elements in a cam ............................................................................................................... 18
Simulation of velocity, acceleration, or jerk ........................................................................................ 19
ca

Downloading and uploading a cam from CamTool ............................................................................ 20


Using interpolation points to create cams at runtime ......................................................................... 21
Adding polynomial segments to a cam ............................................................................................. 22
Interpolating cams ............................................................................................................................. 23
Offsetting and scaling cams in MCC .................................................................................................. 24
Offsetting and scaling cams in ST ...................................................................................................... 25
Commands for reading out function values ....................................................................................... 26
System variables for cams ................................................................................................................. 27
SITRAIN Training for MC-SMO-PRG
Automation and Drives Page 1 Creating cams
Using cams in SIMOTION

External Slave
Virtual- encoder Cam_1
axis Camming
Master Cam_2
operation
axis Synchro-
nous TO
Cam_3
Master

om
Folgeachse
Axis position/
-speed

Axis traverse with position


and velocity profile

l.c
Time

Speed//pressure

ai
Characteristics of valves

SIMOTION
Siemens AG 2013. All rights reserved.
gm
(hydraulic axis)

Date:
File:
10.01.2013
MC-SMO-PRG_08.2
Voltage

SITRAIN Training for


Automation and Drives
@
Cam TO The "cam" technology object is initially used to define a transmission function
y := F(x), i.e. describing an output variable in relation to an input variable.
These input and output variables can be as follows:
er

• Input variable is the actual position of a leading axis, i.e. a virtual master
value source, a voltage applied at a valve, or the time
• Output variable is e.g. the position of a following axis, the velocity of an axis,
etc.
ez

The "cam TO" is a stand-alone technology object which can be interconnected


with other technology objects.

Application The "cam TO" can be used in SIMOTION as follows:


r.s

• With the "synchronous operation TO" as a transmission function (input


variable is the master value, output variable is the position of a following
axis)
• With the "axis TO", e.g. as a velocity, position, or pressure profile
(in this case, the input variable is time)
ne

• With the "hydraulic axis TO" as a valve characteristic curve or inverted valve
characteristic curve.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Creating cams
Creating a cam

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.3
SITRAIN Training for
Automation and Drives
@
Cams Cams are stand-alone technology objects. Cams can be created, configured,
and parameterized with the SCOUT interface and then downloaded to the target
device.
Like other technology objects, cams can be modified at runtime using system
er

function calls. Cams have system variables which provide information about the
current state.

Creating Cams can be created and edited in SIMOTION SCOUT using the CamEdit tool
ez

cams or with the optional add-on SIMOTION CamTool. Which tool is to be used to edit
a cam must be defined when the cam is created.
The following two options are available for selection under the "Cams" folder:
• Insert cams (edit with CamEdit)
r.s

• Insert cams with CamTool (edit with CamTool)

Converting Cams created with CamEdit can subsequently be converted to CamTool and
cams vice versa. Corresponding commands for converting cams are available in the
ne

cam shortcut menu.

Exporting and Cams can also be both exported and imported. The Expert context menu
importing cams contains corresponding commands for export and import operations.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Creating cams
Creating cams with SIMOTION

CAM EDIT CAM tool


as As
polynomial
polynomial
as As
interpolation
interpolation
point
point
table
table
Position

om
Velocity

l.c
Acceleration

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.4
SITRAIN Training for
Automation and Drives
@
CamEdit The CamEdit cam editor is used to describe cams by means of either
interpolation points or segments. These two methods cannot be combined. One
of them must be selected when the cam is created. This selection cannot be
changed at a later date.
er

If the cam is being defined using interpolation points, a linear, cubic or Bezier
spline can be selected for the interpolation type.
If the cam is being created using segments, CamEdit provides the VDI wizard
for describing the segments.
ez

CamTool With SIMOTION CamTool, you can use fixed points, straight lines, sine curves,
arc sine curves, and interpolation points to create cam segments.
SIMOTION CamTool calculates interpolation curves between the individual cam
r.s

segments and displays the V diagram (velocity diagram), A diagram


(acceleration diagram), and J diagram (jerk diagram) in addition to the position
curve.
Thus, when changes are made to the cam, the effects on velocity, acceleration,
and jerk are immediately visible to the user.
ne

Defining cams Cams stored in a device can be manipulated from within the user program with
with ST ST commands. Cams cannot be created with the user program. System
commands can only be used to modify cams already stored in the SIMOTION
device.
ca

The ST programming language provides calls for defining cams by specifying


interpolation points, segments, and interpolation type. Cams can also be scaled.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Creating cams
Using interpolation points to create cams in CamEdit

Name

Selection:
• Polynomial
• Interpolation point table

om
Slave value

l.c
= interpolation points

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Start value

Date:
File:
10.01.2013
Master range

MC-SMO-PRG_08.5
End value
Master
value

SITRAIN Training for


Automation and Drives
@
General The CamEdit tool supports two different ways of defining cams:
• Based on interpolation points
• Based on segments
er

One of these must be selected when the cam is created. This selection cannot
be changed at a later date.

Definition based on Interpolation points are represented in the form P = P(x,y) in interpolation point
ez

interpolation points tables. The order in which the value pairs are entered is irrelevant. They are
automatically sorted in the defineition range in ascending order.
SIMOTION interpolates between the indiividual interpolation points according
to the parameterized "interpolatsion type".
r.s

Definition based on Individual segments are des@cribed in accordance with "VDI Directive 2143",

"Motion Laws for Cam Mechanisms". Polynomials with a maximum polynomial


degree of 6 and an (optional) compound trigonometric function are used for the
segments.
ne

Advantages and
disadvantages Definition blased on interpolation points
Definition based on segments
Advantages: Less data used for definition
ca

Simple definition
Any algorithms can be mapped by Standard transitions in
interpolation points accordance with VDI
Curve creation assisted by teach-in Contour is very precise
Simple interface to HMI
Continuous transitions
Large number of interpolation points Complex arithmetic required for
Disadvantages: for precise contour required calculation of coefficients

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Creating cams
Using interpolation points to define the basic form of a cam

Draw basic form

om
l.c
Define interpolation points

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
Basic form of interpolation point table

10.01.2013
MC-SMO-PRG_08.6
SITRAIN Training for
Automation and Drives
@
General Creating the cam geometry as an interpolation point table. The cam
characteristic is specified in the form of an interpolation point table. The cam
itself is created by interpolation between the points in the table.
er

Entering inter- The table for entering the interpolation points contains a master column and a
polation points slave column. It appears on the left-hand side of the CamEdit editor. The values
for the interpolation points of the master and slave axes can be entered
unsorted. When the cam is displayed, they are listed sorted automatically.
ez

One or more lines of the table can be selected by clicking with the mouse or
using a drag-and-drop operation on the entries in the first column.

Context menu The following functions for the lines in the table are accessed via the commands
r.s

in the context menu for the interpolation table (opened by right-clicking with the
mouse):
• Delete Contents: Deletes one or a number of selected lines
• Delete Lines: Deletes one or a number of selected lines from the
interpolation point table
ne

• Insert Line: Inserts a blank line in front of the selected line in the table
• Insert Lines: Inserts a number of lines in front of the selected line
• Sort Table: Sorts the table in ascending order of master values
ca

Draw basic form Select this option to draw the curve of the table entered in the right-hand section
of the editor window. When the cam is displayed, the individual points are linked
by means of straight lines. If an interpolation type has been defined, it is not
taken into account.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Creating cams
Defining the interpolation type in CamEdit

om
Interpolation type:
• Linear

l.c
• Cubic splines
• Bezier splines

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.7
SITRAIN Training for
Automation and Drives
@
"Interpolation When you create a new cam based on an interpolation point table, you can
type" tab select the interpolation types to be used by the SIMOTION target device for
interpolation between the individual interpolation points on the "Interpolation"
tab.
er

The following options are available for selection in the "Interpolation type"
selection box:
• Linear: The individual interpolation poinmts in the table are
interpolated by means of linear segments. This results in discontinuities with
ez

respect to velocity and other time-based derievatives such as acceleration and


jerk.
• Cubic splines: The connections between two interpolation points is
achieved using cubic splines. Cubic splines are 3rd degree polynomials
(e.g.: a0 + a1 * x + a2 * x@2 + a3 * x3). The four coefficients are determined
r.s

between two interpolation points by four boundary conditions for position


continuity and their derivatives.
• Bezier splinesuThe approximation curve normally runs along the
specified interpolation points. The defined interpolation points act as attractors,
ne

as it were.
Note The speclified interpolation type is transferred only to the target device which
created the actual cam characteristic curve from a predefined interpolation point
table. The resulting interpolation curve for the interpolation points entered is not
ca

included when the basic form is displayed in "CamEdit".

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Creating cams
Comparison of the various interpolation types

om
l.c
Cubic splines Bezier splines

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.8
SITRAIN Training for
Automation and Drives
@
Displaying To visualize the actual curve form, in online mode, for example, you
cams download the cam with the selected interpolation type (linear, cubic splines,
Bezier splines) to the SIMOTION device and then upload it again.
The SIMOTION target device converts the downloaded interpolation point table
er

into the appropriate polynomial segments. Then, when the cam is uploaded,
these polynomial segments are visualized when the "Display uploaded cam"
option is selected.
The uploaded cam can be added to the SCOUT project by clicking the Accept
ez

button.

Note An individual cam can then only be reloaded to a SIMOTION device


subsequently if it has been saved in the target device previously by means of a
r.s

project download.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Creating cams
Defining behavior with gaps

Expert mode min


max

Maintain gaps

om
min
max

l.c
Merge points

ai
min
max

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.9
Add new
segment

SITRAIN Training for


Automation and Drives
@
Gaps in a curve In Expert mode, you can define the procedure for the gaps between individual
characteristic segments of the cam. Gaps are discontinuities in the curve characteristic. They
occur whenever cam segments do not overlap. Discontinuities are dealt with
separately for the master range and the slave range.
er

In the Expert mode dialog, two distances can essentially be specified:


• If the distance between two segments is less than the value entered
under "Maintain gaps", the discontinuimty is retained.
When this discontinuity point is accessed, the right boundary point is output
ez

• If the distance lies between the "Maieintain gaps" entry and the "Merge
points" entry, the gap is corrected bys merging the end points of the segments.
The mean value of the dist ance is calculated for this purpose. The shape of the
relevant segments changes as a result.
r.s

• If the distance is greate@r than the value in "Merge points", a new


segment appropriate for the set interpolation type is inserted.

Overlapping Conversely, if indlividual segments overlap, the cam segment with priority can
be selected in theg "If segments overlap" selection box.
ne

The followoing options are available for selection:


• Starlting point (leading axis): Continues the curve characteristic with
the segment starting point of the following segment
• End point (leading axis): Starts the curve characteristic of the following
segment with the end point of the current segment
ca

• Time sequence: The curve characteristic is determined by the


chronological order in which the segments were inserted

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Creating cams
Defining the type of cam and master range

Cam type
• Non-cyclic
• Cyclic relative
• Cyclic absolute

om
Master range

l.c
Non-cyclic Cyclic relative Cyclic absolute

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.10
SITRAIN Training for
Automation and Drives
@
Master range Under "Master range", you can define the range between the starting point and
the end point of the cam (definition range). Activate "From geometry" to define
the smallest and largest coordinate entered for the leading axis as the start and
end points of the definition range respectively. Defining the range like this
er

means that there are no gaps at the start and end of the cam.
If the "From geometry" option is not selected, ethe definition range of the cam
can be defined by entering values in the "Start" and "End" input fields. The value
in the "Start" input field must always be less than or equal to the smallest
coordinate specified for the leading axis inm the interpolation point table; the
ez

value in "End" must always be greater than oer equal to the largest coordinate
specified for the leading axis in the interpolatiion point table.
If the value specified for "Start" iss a lot smaller than the range of the cam
covered by the interpolation points and the value for "End" is much larger than
it, gaps will appear at the st@art and the end of the cam.
r.s

The "Cam type" selec tion box tells the SIMOTION target device whether the
Cam type characteristic of the ucam downloaded is absolute, cyclic absolute, or cyclic
relative.
ne

Dependent gupon this selection, the target system makes specific changes at
the start and end oof the cam.

Non-cycllic: The SIMOTION device does not make any changes to the cam.
SIMOTION assumes that the cam will have an absolute characteristic when it is
ca

subsequently activated.

If, when the cam is subsequently processed, it has a cyclic characteristic


(specification with command "_enablecamming"), discontinuities in position and
velocity will occur on transition from the end to the start of the cam. This can
lead to motion being aborted on the slave.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Creating cams
"Absolute", "cyclic relative", and "cyclic absolute" cams

om
Original cam with cubic spline
Non-cyclic
interpolation

l.c
ai
SIMOTION
Cyclic absolute

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.11
Cyclic relative

SITRAIN Training for


Automation and Drives
@
Continued Cyclic absolute (constant position and speed). In the event of a cam where the end
value of the following axis is not equal to the start value of the following axis, for
example, the SIMOTION device will attempt to achieve constant-position and
constant-speed transition between end and starting points.
er

If this is not possible, an error message is displayed accordingly when the cam is
downloaded. So that the target device can peerform interpolation at these transition
points, a small "gap" might need to be created at the end or start of the cam.
Otherwise, in some cases, the dynammic response of synchronous operation
ez

motion might not be maintained during processing when


"discontinuous" transitions like this aree reached.
Cyclic relative: (constant speed). siIn this case, when the cam is interpolated in the
target system, the derivat ive of the cam attempts to achieve continuity at the end or
r.s

starting point. If this is not possible, an error message is displayed accordingly when
the ca@m is downloaded (as is the case with cyclic absolute).
Note
The procedure follo wed by the SIMOTION device is clear in particular at cams
where there is a gap at uthe start or end. This effect can be illustrated by
ne

downloading the lcam and then uploading it.


Example
In the exaomple above, one unit has been added to the master range of the cam at
both lthe start and the end (-1, ..., 51). The "cubic splines" interpolation type ehad
been selected for the cam.
ca

Aftekr this, the possible entries for "Cam type" ("absolute", "cyclic absolute", and
"cyclic relative") were varied and the cam was downloaded to and then uploaded
from the target device.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 Creating cams
Scaling and offsetting cams

Scalings
Scaled and offset
curve

om
Basic curve

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.12
SITRAIN Training for
Automation and Drives
@
Scaling and You can scale and offset the cam geometry previously defined. You can scale
offsetting the leading axis and following axis or individual sections of these axes
separately. Separate settings can be made for offsetting the leading axis and the
following axis.
er

You can use this functionality on a packaging machine, for example, to adapt a
previously configured cam to varying product lengths.

Basic scaling Basic scaling can be specified for every axis. The scaling factor is entered in the
ez

"Basic scaling" input field. The coordinate origin always forms the center of
basic scaling.

Scaling 1/2 Two ranges for basic scaling can be set for each axis. A separate scaling factor
r.s

can be assigned to each of these ranges.


You can define the section you want to scale in "From" and "To" and under
"Factor" you can enter the scaling factor. If you are scaling two sections, the
sections must not overlap. The center of scaling forms the starting point of the
scaling range.
ne

Offset Use "Offset" to specify a factor for offsetting the master and following axis,
respectively. The offset refers to the previously scaled cam or the basic form if
you have not scaled the range.
ca

Notes • Select the "Draw scaled and offset" option to draw in the scaled and offset
cam with the basic form.
• The functions for scaling and offsetting a cam can also be used at runtime
via corresponding system functions, provided that the cam is not active
(e.g. _enablecamming(...).
So, at runtime, a downloaded cam can be adapted to meet different
requirements such as varying product lengths, etc.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 Creating cams
Using polynomials to create cams in CamEdit

Enter coefficients a0, a1, ...

om
Double-click

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.13
SITRAIN Training for
Automation and Drives
@
Cam type: Once a new polynomial type cam has been created, the geometry of the
Polynomial individual segments can be created. A cam defined based on polynomials
consists of any number of individual segments.
Each cam segment is described as a polynomial of up to the 6th degree which
er

can also be superimposed with a sine. This function, consisting of polynomial


and sine, is then mapped to a real range of the cam.
Each segment of the cam is described by the following variables:
ez

• A definition range (normalized range) for the polynomial and the sine
The definition range is defined in the table with the xn1 and xn2 entries.
• A polynomial P(x) of up to the 6th degree with coefficients a0, ..., a6
P(x) = a0 + a1 * x2 + a3 * x3 + a4 * x4 + a5 * x5 + a6* x6 with arguments x from
definition range xn1, xn2.
r.s

• A sine function S(x) with amplitude A, period p, and phase ϕ


S(x) = A* sin(p*x + ϕ) with arguments x from definition range xn1, xn2
The total function F(x) = P(x) + S(x) is mapped to a real segment of the cam.
The real range of the cam is described by:
ne

• A master range x1, x2. The definition range xn1, ..., xn2 of the function
is mapped to this master range, i.e. xn1 to x1 and xn2 to x2
• A corresponding slave range (value range) y1, y2. The value range of the
function F(x) with arguments from the definition range is mapped to this
ca

range, i.e. the minimum of the function F(x) is mapped to y1 and the
maximum is mapped to y2

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 Creating cams
Motion laws in accordance with VDI

R G U R
Slave value

om
l.c
Master value

ai
R: Dwell (velocity = 0, acceleration = 0)
G: Constant velocity (velocity ≠ 0, acceleration = 0)
U: Reversal (velocity = 0, acceleration ≠ 0)
B: Motion(velocity ≠ 0, acceleration ≠ 0)

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.14
SITRAIN Training for
Automation and Drives
@
General Calculating coefficients for segments of cams manually is usually incredibly
difficult. For this reason, the "CamEdit" tool features the VDI wizard to assist
users when creating cams.
er

VDI 2143 The VDI concept describes the entire cam characteristic by putting together
what are known as working ranges linked by motion transitions. Working ranges
are the sequences of a process.
VDI defines four different types of working range:
ez

• R: Dwell (velocity = 0, acceleration = 0)


• G: Constant velocity (velocity ≠ 0, acceleration = 0)
• U: Reversal (velocity = 0, acceleration ≠ 0)
• B: Motion (velocity ≠ 0, acceleration ≠ 0)
r.s

Motion transitions are transitions between working ranges, which are not directly
relevant to the process but must satisfy certain boundary conditions (such as
continuity in velocity and acceleration).
ne

VDI wizard A cam consists of individual motion segments and transitions. The VDI wizard
must be executed once for each motion segment or transition. The VDI wizard
provides 2 predefined motion segments (constant velocity and dwell) plus 16
motion transitions. Motion segments and transitions are also parameterized in
the wizard.
ca

The VDI wizard uses the input values to calculate the corresponding coefficients
for the polynomials and enters these in the selected line of the table.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 Creating cams
Creating geometry data with the VDI wizard

2. Enter geometry
data

1. Select
motion transition

om
l.c
3. Preview

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.15
SITRAIN Training for
Automation and Drives
@
Creating geometry The VDI wizard provides a user-friendly means of creating the geometry data of
data with the wizard a cam and entering it in the table.
1. To open the VDI wizard, either select the menu command:
Cam -> VDI wizard or press the "VDI wizard" button. The VDI wizard is
er

displayed.
2. In the "Type of Motion Transition" dialog, select the required motion segment
or transition and then click the "Next" button.
ez

Based on the selected motion segment or transition, a second dialog is


displayed in which you should make the necessary settings as appropriate.
3. Make the settings and then click the "Next" button.
At the end of the process, a summary of the geometry data you have entered
is displayed. You can also display the motion segment you have entered by
r.s

clicking the "Preview" button.


4. To apply the geometry data you have entered, click the "Complete" button.
The VDI wizard calculates the coefficients accordingly from the geometry
data entered and enters these in the table.
ne

5. Repeat steps 1 to 4 until you have created all cam segments.


6. Click the "Interpolation" tab and enter any necessary data if there are to be
gaps in the cam segments you have created.
ca

Note In each of the dialogs, you can click "Back" to go back to the previous dialog and
make changes to the data entered if necessary.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 Creating cams
Creating cams with CamTool

Toolbar

om
l.c
Creating cams
with CamTool

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.16
SITRAIN Training for
Automation and Drives
@
General SIMOTION CamTool is fully integrated in SCOUT. This allows you to use data
configured in SCOUT in SIMOTION CamTool as well (e.g. axis settings).

Basic functions SIMOTION CamTool provides the following basic functions:


er

• Insert and edit cams


• Convert cams from CamEdit to SIMOTION CamTool and from SIMOTION
CamTool to CamEdit
• Import cams from text files and exeport cams to text files
ez

• Upload cams from target devicesi and download cams to target devices
• Print cams
SIMOTION CamTool prov@ides the following functions for editing cams:
r.s

Creating
• Defining and displaying parameters for the leading axis and following
axis (e.g. dimension unit)
• Defining and dilusplaying the processing type of the cam (e.g. cyclic
relative processingg type)
ne

• Definiong and displaying the offset and scaling of a cam


• Graphlic and textual input in S diagram (distance diagram) of cam
segments as:
- Fixed point (position, velocity and acceleration)
- Straight line (position and velocity)
- Sine line (position)
ca

- Arc sine line (position)


- Interpolation point (position)
• If cam segments are defined as interpolation points, SIMOTION
CamTool uses polynomial splines to calculate the interpolation curve

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 Creating cams
Defining the range of the master and slave axes

Context menu: Representation parameters -> master, slave

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.17
SITRAIN Training for
Automation and Drives
@
Representation To change the representation parameters for the leading axis or following axis:
parameters 1. Select the menu command: Cam -> Representation parameters for the
for which you want to modify the representation parameters.
2. The "Master properties" dialog (for the leading axis) or the
er

"S diagram (slave) properties" dialog (for the following axis) is displayed.

Master range
The definition range for the cam in SIMOTmION CamTool is defined based on
ez

the start and end points of the cam in the master range. Cam segments inserted
in CamTool must lie within the definition range.
Specify the definition range of the sicurve displayed in the representation range
by setting its start and end points . The representation range can be selected
r.s

larger or small than the master range.

Slave The settings for grid lines @are also made in this dialog.
Settings for theu representation range and grid lines for the following axis can be
made in the "S dliagram (slave) properties" dialog.
ne

Specify the repgresentation range of the curve for the following axis by setting its
start and end opoints.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 Creating cams
Inserting elements in a cam

om
Interpolation points

Straight line

l.c
Fixed point

ai
Double-click

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.18
SITRAIN Training for
Automation and Drives
@
General Fixed points, straight lines, sine/arc sine lines, and interpolation points can be
inserted via the toolbar or using the context menu. Input remains active for the
selected element until you press the ESC key or click the pointer symbol with
the mouse.
er

You can enter more detailed information about the specific properties of the
selected element in the Properties dialog.

Fixed points A fixed point is a predefined following axis position for a given leading axis
ez

position.
The Properties dialog, in which youi can specify the velocity and acceleration at
the fixed point position, opens wshen you double-click the fixed point.
r.s

Straight line A straight line defines a sy@nchronous section in the cam. In the Properties
dialog, you can specify the exact start and end positions, as well as the velocity
along the straight line.

Sine, arc sine The arc sine cuglrve is calculated internally as an interpolation point table. You
ne

can specify the number of interpolation points in the "Fx arc sine properties"
window.

Interpolation points An ineterpolation point is a specified position in the S diagram (distance diagram).
ca

Ukse a fixed point to specify a single, fixed position. CamTool calculates


optimum transitions between adjacent cam segments.
Interpolation points must be used for any profile you wish to define. CamTool
links the interpolation points with a cubic spline in order to create the profile
specified by the interpolation points as accurately as possible.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 Creating cams
Simulation of velocity, acceleration, or jerk

Cam -> Simulation settings


Distance

om
Velocity

l.c
Acceleration

ai
Jerk

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.19
SITRAIN Training for
Automation and Drives
@
Simulation The simulation settings are used to simulate camming of leading axis and
settings following axis offline in CamTool. The main element specified for simulation is
the velocity of the leading axis. The resulting dynamic values for the following
axis (e.g. velocity, acceleration, and jerk) are displayed in separate diagrams.
er

The dynamic effects resulting from changes to the cam are also displayed.
You can either take the axis settings for the master and slave axes from axes
configured in the SCOUT project or specify your own.
ez

To specify the simulation settings:


1. Click a diagram to show the Cam menu.
2. Click the Cam >Simulation Settings menu. The Simulation settings window
opens.
r.s

3. Specify the parameters on the "Master" tab.


. 4. Click the "Slave" tab and specify the parameters.

Diagram The S diagram (distance diagram) for the cam is always displayed first in the
representation SIMOTION SCOUT working area.
ne

To show or hide the V diagram (velocity diagram), A diagram (acceleration


diagram), or J diagram (jerk diagram), click the required button on the toolbar or
use the context menu.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 Creating cams
Downloading and uploading a cam from CamTool

Cam -> Download/upload cam

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.20
SITRAIN Training for
Automation and Drives
@
General If you create a cam and the cam has never been previously downloaded to the
SIMOTION device, you must first download the entire configuration with the new
cam to the SIMOTION device.
Only after this can you download the cam to the SIMOTION device
er

independently of the other technology objects. Downloads are only possible


when SIMOTION SCOUT is in ONLINE status.

Downloading cams Proceed as follows to download a cam to the SIMOTION device:


ez

1. Click the "Connect to target system" button. SCOUT switches to


ONLINE status.
2. Select the menu command: Cam -> Download cam. The cam
is downloaded to the SIMOTION target device.
r.s

3. You can switch back to OFFLINE status once the download is complete.
Proceed as follows to upload a cam from a SIMOTION device:

Uploading cams 1. Click the "Connect to target system" button. SCOUT switches to
ne

ONLINE status.
2. Select the menu command: Cam > Upload cam. If you upload a cam from
the SIMOTION target device and have previously made changes to the
displayed cam, a window opens. In this window you can make the changes
to the cam effective in the project.
ca

After this, the cam is uploaded from the SIMOTION device to CamTool.
3. You can switch back to OFFLINE status once the upload is complete.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 Creating cams
Using interpolation points to create cams at runtime
1. Reset downloaded cam

RetVal :=_resetcam(
cam, // Specification of the cam
insertmode, // Overlapping segments?
usederdefaultdata, // Reset user default values?
activaterestart, // Restart cam TO?

om
camdata); // Delete cam or reset to ES value?

2. Add interpolation points to a reset cam (e.g. pass in a loop, corresponds to


the interpolation points in the table)

l.c
RetVal := _addpointtocam(
cam, // Specification of the cam
campositionmode, // Basic sys. or scaled system?

ai
leadingrangeposition, // Coordinate of leading axis
followingrangeposition); // Coordinate of following axis

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.21
SITRAIN Training for
Automation and Drives
@
Resetting When a cam is created, the order in which the curve is processed with
a cam system calls is important. If the shape of the cam is dependent on parameters
such as interpolation points, the curve must be reset before each calculation
using the command.
er

The "_resetCam" command "deletes" the cam. The interpolation is cleared, and
the points and segments are removed. The technology object is retained but is
empty.
When resetting a cam, you can specify whether the cam (camdata) or the user
ez

default variables (userdefaultdata) should be deleted completely or reset to the


value downloaded from SCOUT. It is also at this point that behavior for
overlapping segments (insertmode) is defined. Moreover, it is also possible to
specify whether or not a restart (activaterestart) should be performed.
r.s

Adding inter- A cam can comprise any number of interpolation points and segments. The
polation points interpolation points and/or segments can then be arranged in the appropriate
order.
The "_addPointToCam" command is used to add an interpolation point. The
ne

coordinate system is also specified by calling this command.


• Basic system: The coordinates reference the coordinate system which is not
offset and not scaled (basic form).
• Actual system: The specified coordinates reference the scaled and shifted
coordinate system.
ca

If no offsets or scaling have been applied, the basic and actual systems are
identical. However, in principle, part of the cam could be created initially in the
basic coordinate system and offset or scaling applied subsequently.
If a new interpolation point is added at this stage, whether the specified
coordinates reference the basic system or the actual system is relevant.
New interpolation points and segments can only be added provided that the cam
has not been interpolated.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 Creating cams
Adding polynomial segments to a cam
2. Add polynomial segments to a reset cam
RetVal := _addpolynomialsegmenttocam(
cam, // Specification of the cam
polynomialcoefficients, // Array with coefficients ai
segmentbegin, // Start of segment
segmentend, // End of segment
campositionmode ); // Coordinate system? Offset?

om
2. Add segments to a reset cam
RetVal := _addsegmenttocam(
cam, // Specification of the cam
polynomialcoefficients, // Array with coefficients ai

l.c
sineamplitude, // Sine amplitude
sineperiod, // Sine period
sinephase, // Sine phase
segmentbegin, // Start of segment
segmentend, // End of segment

ai
campositionmode, // Coordinate system? Offset?
leadingrangestartpoint, // Start of master range
leadingrangeendpoint, // End of master range

SIMOTION
followingrangestartpoint,
followingrangeendpoint,

Siemens AG 2013. All rights reserved.


gm
// Start of slave range
// End of slave range
followingrangespecificationmode); // Min_Max?

Date:
File:
10.01.2013
MC-SMO-PRG_08.22
SITRAIN Training for
Automation and Drives
@
Adding segments There are two system calls in SIMOTION for adding segments:
• _addsegmenttocam()
• _addpolynomialsegementtocam()
er

The "_addsegmenttocam" function adds a segment f = f(t) consisting of a


polynomial of up to the 6th degree and a trigonometric component to a cam.
The polynomial parameters, amplitude, period, and phase of a sine function are
entered and the definition, master, and slave ranges are specified in the same
ez

way as in CamEdit. It is also possible to specify whether the master and slave
ranges reference the "basic" or "actual" system.
The definition range values of the cam must always be increasing, i.e. specified
in the positive direction.
r.s

The "_addPolynomialSegmentToCam" command creates a segment f = f(t)


consisting of a polynomial of up to the 6th degree. The polynomial parameters
are input in the real range (actual).

Note Once a cam has been entered, it can be read out of the target device and
ne

displayed in SIMOTION SCOUT (e.g. CamEdit).


In CamEdit, the basic form (basic coordinate system) is displayed in black;
offset and scaled cams are displayed in blue. The function to display offset and
scaled cams (in blue) must be enabled separately in CamEdit.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 Creating cams
Interpolating cams

3. Interpolate entered cam


RetVal := _interpolatecam (
cam, // Specification of the cam
campositionmode, // Coordinate system? Offset?
leadingrangestartpointtype, // From geometry?
leadingrangestartpoint, // Start of definition range

om
leadingrangeendpointtype, // From geometry
leadingrangeendpoint, // End of definition range
cammode, // Cyclic absolute, ...?
interpolationmode, // C spline, B spline?
nochangedifferenceleadingrange, // Min. distance master range
nochangedifferencefollowingrange,//Min. distance slave range

l.c
combinedifferenceleadingrange, // Max. distance master range
combinedifferencefollowingrange); // Max. distance slave range

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.23
SITRAIN Training for
Automation and Drives
@
Interpolating If the shape of the cam is described completely, interpolation is performed using
cams the "_interpolateCam" command.

This command runs a complete analysis and recalculation of the interpolation


er

points and segments entered. The interpolation type (C spline, Bezier spline,
linear), what happens at the end of a cam (non-cyclic, cyclic absolute, cyclic
relative), and the procedure for gaps between ethe individual segments are
particularly important components of the recalculation process.
This command requires that you specify wmhether interpolation is to take place
ez

in the basic coordinate system or the offset coordinate system. The information
about the definition range of the curve to be interpolated also references this
selection (basic or actual). For exaimple, if an interpolation point of the cam is
located outside the specified definsition range, it is not taken into account during
interpolation.
r.s

Following interpolation, alt@hough a cam can still be offset and scaled, it is no


longer possible to add any more points or segments or make changes. Attempts
to access an interpolat ed cam (with _addpointtocam, etc., for example) are
rejected with an eruror message.
ne

In this case, the caglm must be reset and recreated.


Note Once a caom has been interpolated, it can be read out of the target device and
displayed in SIMOTION SCOUT (e.g. CamEdit).
In CamEdit, the basic form (basic coordinate system) is displayed in black;
ca

offset and scaled cams are displayed in blue. The function to display offset and
scaled cams (in blue) must be enabled separately in CamEdit.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 Creating cams
Offsetting and scaling cams in MCC

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.24
SITRAIN Training for
Automation and Drives
@
Offsetting and The MCC command "Parameterize cam" is used to scale and offset a cam.
scaling In MCC, offset and scaling of a cam can be entered separately for the master
value and the following axis.
Scaling takes place over the complete cam or within a range defined by the start
er

and end points. Scaling of the complete cam is referred to below as basic
scaling; scaling of a range is referred to as range scaling. The definition range
and value range each have one basic scaling and two range scalings (compare
CamEdit).
ez

For basic scaling, the zero point of the coordinate axis becomes the scaling
point, while for range scaling the starting point of the specified scaling range is
used.
This command enables simultaneous specification of one offset and/or basic
r.s

scaling plus one range scaling each for the master and slave axes.
In the case of offset, it is also possible to specify whether the offset should be
calculated as an absolute or relative value:
• Absolute: The offset cam is achieved by offsetting the cam specified in the
basic system (basic form) by the specified offset, i.e. the new offset overrides
ne

the previous one


• Relative: The offset cam is achieved by offsetting the cam in the actual
system by the specified offset, i.e. the new offset value is added to the old
offset.
ca

Note This command can only be applied to cams that are not active. Accessing an
active cam stops the following axis.
The command can be used for both non-interpolated and interpolated cams.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 Creating cams
Offsetting and scaling cams in ST
Offset entered or interpolated cam
RetVal := _setcamoffset(
cam, // Specification of the cam
offsetrange, // Leading or following axis?
offsetmode, // Absolute or relative?
offset // Offset value

om
);

Offset entered or interpolated cam


RetVal := _setcamscale(

l.c
cam, // Specification of the cam
scalingrange, // Leading or following axis
scalingspecification, // Basic or range scaling
specificrangenumber, // 1st or 2nd range
specificrangestartpointtype,// Last progr. or direct?

ai
specificrangestartpoint, // Start of range
specificrangeendpointtype, // Last progr. or direct?
specificrangeendpoint, // End of range

SIMOTION
scalevalue,
);

Siemens AG 2013. All rights reserved.


//

gm
Date:
File:
10.01.2013
Scaling value

MC-SMO-PRG_08.25
SITRAIN Training for
Automation and Drives
@
Offsetting cams In In ST there are two separate system function calls for offsetting and scaling
non-activated cams.
The "_setcamoffset" call sets an offset for a non-activated cam. This call
requires that you specify both the range (master or slave) and the coordinate
er

system (basic, actual) in addition to the offset itself.


"Basic" corresponds to an offset of the basic form, i.e. the offset value calculated
is absolute. "Actual" corresponds to a relative offset of the cam.
ez

Scaling cams The _setcamscale call is used to scale a non-activated cam. This call requires
that the range (master or slave) and whether basic or range scaling is to be
performed are specified, along with the scaling factor.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 25 Creating cams
Commands for reading out function values

Read out function value of cam


RetVal := _getcamfollowingvalue(
cam, // Specification of the cam
leadingpositionmode, // Def. range: absolute or relative?
leadingposition, // Value in def. range

om
followingpositionmode, // Value range: absolute or relative?
);

Read out function value of reversal function of cam

l.c
RetVal := _getcamleadingvalue(
cam, // Specification of the cam
followingpositionmode, // Value range: absolute or relative?
followingposition, // Default position in value range
leadingpositionmode, // Def. range: absolute or relative?

ai
leadingapproachpositiontype // Direct entry of position
leadingapproachposition // Approach position in def. range
);

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.26
SITRAIN Training for
Automation and Drives
@
Reading out The "_getCamFollowingValue" command is used to read out the function value
function values of a cam. The call returns the cam value when a value in the definition range is
specified (master value).
The reference systems for the function can be specified as follows:
er

• Reference system for definition range: Offset and scaled/Not offset and not
scaled
• Reference system for value range: Offset and scaled/Not offset and not
ez

scaled

Reading out the For some applications, it is necessary to determine the master value for a
value of the defined slave value. The master value can be retrieved using
reversal function "_getCamLeadingValue".
r.s

This inverse mapping is only unique in the case of strictly monotone output
functions. In order to supply a master value for output functions that are not
strictly monotone, an x-value can be specified, and the nearest solution (in both
directions) is then sought for the specified x-value. If an x-value is not specified,
the search will begin from the starting point of the cam.
ne

The reference systems for the function can be specified as follows:


• Reference system for definition range: Offset and scaled/Not offset and
scaled
• Reference system for value range: Offset and scaled/Not offset and scaled
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 26 Creating cams
System variables for cams

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_08.27
SITRAIN Training for
Automation and Drives
@
System variables Like any other TO, a cam has system variables to reflect its state. In particular,
for cams the system variables contain information about the following properties:
userdefault: Information about the default settings for the coordinate systems
(basic, actual)
er

leadingrangesettings: Information about offsets, basic scaling, and the range


scalings of the definition range (master value)
followingrangesettings: Information about offsets, basic scaling, and the range
ez

scalings of the value range (slave value)


interpolation: Information about interpolation (yes, no), the interpolation type
(B spline, C spline, linear), and what happens at the end of cams (non-cyclic,
cyclic absolute, cyclic relative)
leadingrange: Information about the effective definition range (start position, end
r.s

position)
reset: Processing state of the reset command
error: Information about whether there is an error pending at the cam TO
activationmodechangedconfigdata: Information about activating changed
ne

configuration data
Restartactivation: Information about executing a TO restart
definitionstate: This variable indicates whether points or segments have been
inserted in this cam. Geometry elements can be inserted by means of a
ca

download or with cam commands. An empty cam is indicated by the value


'definitionState:=EMPTY'.
The variable is a read-only variable.
accessstate: This variable indicates read or write accesses made to the cam.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 27 Creating cams
Camming in SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Gearing in SIMOTION ....................................................................................................................... 3
Camming in SIMOTION ..................................................................................................................... 4
er

Creating a following axis .................................................................................................................... 5


Making an assignment to leading axes and cams ............................................................................. 6
Settings for synchronous operation ................................................................................................... 7
Default settings for camming ............................................................................................................. 8
ez

Enabling camming in MCC (1) ......................................................................................................... 9


Evaluation: Master (absolute) - Slave (absolute) .............................................................................. 10
Evaluation: Master (absolute) - Slave (relative) ................................................................................. 11
Evaluation: Master (relative) - Slave (absolute) ................................................................................. 12
Evaluation: Master (relative) - Slave (relative) ................................................................................... 13
r.s

Non-cyclic and cyclic processing ...................................................................................................... 14


Enabling camming in MCC (2) ........................................................................................................... 15
Leading axis synchronization and time-related synchronization ....................................................... 16
Start of synchronization ..................................................................................................................... 17
ne

Reference point for synchronization .................................................................................................. 18


Offset to cam starting point ................................................................................................................ 19
Enabling camming in MCC (3) ........................................................................................................... 20
Enabling camming in MCC (4) ........................................................................................................... 21
Disabling camming .............................................................................................................................22
ca

Enabling camming in ST .................................................................................................................... 23


Disabling camming in ST ................................................................................................................... 24
Set master setpoint (_setmaster) ....................................................................................................... 25
Set scaling on camming .................................................................................................................... 26

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 Camming
Camming in SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.2
SITRAIN Training for
Automation and Drives
@
Contents Page
Examples: Set scaling on synchronous object ................................................................................... 27
Set offset on camming ........................................................................................................................ 28
er

Examples: Set scaling and offset on synchronous object .................................................................. 29


Monitoring functions during synchronous operation ........................................................................... 30
Monitoring functions during synchronous operation .......................................................................... 31
ez

Synchronization with velocity reduction ............................................................................................. 32


Setpoint monitoring during synchronization ....................................................................................... 33
Reporting a synchronous operation error to the leading axis ............................................................ 34
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Camming
Gearing in SIMOTION

Master value
• Position axis External
• Following axis encoder
• Ext. encoder Virtual
• Virtual axis axis
Slave value

om
Leading
Synchro-
axis
nous
operation
Settings TO

l.c
• Master value Master value
• Gear ratio
• Synchronization and
desynchronization profile

ai
Buffer IPO Servo

• Limitations of use

SIMOTION
• Monitoring functions

Siemens AG 2013. All rights reserved.


gm
Following axis TO

Date:
File:
10.01.2013
MC-SMO-PRG_09.3
SITRAIN Training for
Automation and Drives
@
How synchronous The "synchronous operation" technology object is used to connect two or
operation is more axes to create a synchronous group.
structured A leading axis (master) generates a master value, which is processed by the
synchronous object according to specific criteria (gear ratio, scaling, cam, etc.)
er

and assigned to the following axis (slave) as a reference variable.


The master value source can be a position axise or a following axis, for
example, or an external encoder. As of SW3.0 SP 1, a setpoint or actual value
coupling can be selected as the master value sourmce for axes. With an actual
ez

value coupling, it is also possible to configure dead time compensation of the


master value.

The master and slave values arse coupled without physical conversion in the
relevant parameterized units. If the leading axis is a linear axis (unit mm), for
r.s

example, and the following axis is a rotary axis (unit degrees), then with a
conversion ratio of 1:1, one@ millimeter corresponds to one degree.
Mechanical Mechanically, the suynchronous object represents the gear with driving gear/
model driven gear or, inl conjunction with the "Cam" TO, the cam gear with the
ne

mechanical cam and sensor system. The model also includes a coupling for
enabling and dgisabling the following motion on-the-fly.

Coupling via The geaelr functionality is characterized by a constant ratio between master
gear value source and following axis. The ratio can either be programmed as a
rational gear factor or using a numerator/denominator ratio.
ca

The slave value is calculated from the programmed gear factor and the master
value and transferred to the gear axis. A following axis can be interconnected
with more than one master value by means of the synchronous object, but only
one of these is evaluated. At runtime, you can switch over the master value in
the user program.
When you select the gearing, you differentiate between absolute and relative
synchronous operation. You can also select from different types of
synchronization/desynchronization profile (related to master value or time).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Camming
Camming in SIMOTION

Master value
• Position axis External
• Following axis encoder
• Ext. encoder Virtual
• Virtual axis Cam_1
axis

om
Slave value
Leading Cam_2
axis TO Synchro-
nous
operation Cam_3
Settings
• Master value TO

l.c
• Cam
• Scalings Master value
• Synchronization and
desynchronization profile

ai
Buffer IPO Servo

• Limitations of use Following axis TO

SIMOTION
• Monitoring functions

Siemens AG 2013. All rights reserved.


Date:
File:
gm 10.01.2013
MC-SMO-PRG_09.4
SITRAIN Training for
Automation and Drives
@
Coupling via The cam gear functionality is characterized by a variable ratio between master
cam value source and following axis. The user can program it by using a cam. In
addition, the scaling and offset can be adapted for both the master value and the
slave value.
er

As of SW3.0 SP 1, both distributed and superimposed synchronous operation is


supported. With distributed synchronous operation, rather than being on the
same SIMOTION device, the leading axis, synchronous operation TO, and
following axis TO are distributed among several controllers. With superimposed
ez

synchronous operation, a following axis does not receive its position setpoints
from one synchronous operation TO but from two, i.e. the basic synchronous
operation TO and a superimposed synchronous operation TO.
Several cams can be used in camming. You can switch from one cam to
another in the user program during runtime.
r.s

Rules The following rules apply for interconnection in general:


• The synchronous object and the following axis are on the same runtime
system
ne

• The synchronous object and the following axis are permanently assigned to
one other in the configuration
• The master value object (position axis, virtual axis, following axis or external
encoder) can be interconnected with several synchronous objects
ca

• The synchronous object can be interconnected with several master values


and cams

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Camming
Creating a following axis

om
l.c
Synchronous operation

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.5
SITRAIN Training for
Automation and Drives
@
Create synchronous If the "synchronous operation" technology is selected when creating an axis in
object SIMOTION SCOUT, SIMOTION SCOUT will automatically create a
synchronous object belonging to the axis.
The synchronous object appears in the project navigator underneath the
er

corresponding axis. The object is automatically assigned the axis name and
suffixed with "_SYNCHRONOUS_OPERATION.

Assignments Master value and cam assignments are indicated in the SIMOTION SCOUT
ez

project navigator by links:


• The links to the master values (axes, external encoder) and cams are
displayed underneath the "synchronous object"
• The link to the synchronous object is displayed underneath the "cams" used
r.s

• The link to the synchronous object is displayed underneath the "master


values" (axes, external encoder)
These assignments are made in the "Interconnections" dialog (see next slide).
ne

IPO levels The interpolation for a TO (e.g. axis TO) can be assigned to the "IPO level" or to
"IPO level_2" in the execution system. This means that, in cases where axes do
not require a high time resolution to calculate reference variables, interpolation
can be placed in an IPO task with a longer cycle time, thereby requiring less
processing power.
ca

If this technology object has an interconnection with other technology objects,


the interconnected technology objects must all be on the same IPO level. If any
inconsistencies are identified during downloading, the are rejected with an error
message.

Note The required "IPO level" can be assigned to a TO via the expert list
(Configuration data -> Execution -> ExecutionLevel).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Camming
Making an assignment to leading axes and cams

• Setpoint coupling
• Actual value coupling
with extrapolation

om
l.c
• Assignment of
cams

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.6
SITRAIN Training for
Automation and Drives
@
Assignments Assignments between the synchronous object and possible leading axes and
cams are made in the "Interconnections" dialog. This dialog opens when you
double-click Interconnections under the <AxisName>_SYNCHRONOUS
OPERATION object in the project navigator.
er

In this dialog, the possible master values and cams are assigned to the
synchronous object of the following axis. The currently used master value/active
cam is defined during runtime using the appropriate functions.
ez

Setpoint and actual With real axes, you can also choose between setpoint and actual value
value coupling coupling. External encoders only support actual value coupling, virtual axes only
support setpoint coupling.
The reference value for the actual value coupling can be extrapolated for the
r.s

compensation of dead times. The extrapolation compensates for the local delays
that result from use of the actual value instead of the setpoint.

Notes Gearing or camming with a following axis is only possible if at least one master
value has been assigned to the associated synchronous object.
ne

To select camming, a cam must also be assigned.


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Camming
Settings for synchronous operation

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.7
SITRAIN Training for
Automation and Drives
@
Settings The most important configuration settings for synchronous operation can be
made in this dialog.

Direction-related Allowance for direction-dependent or direction-independent effect of the


er

dynamic parameters programmed dynamic values (syncingMotion.directionDynamic).


m

Abs. synchr. with For absolute synchronization, if "Yes" is set the jerk is taken into account.
consideration of jerk If "No" is set, the set jerk will be ignored in spite of velocity profile = SMOOTH
ez

being selected. Travel follows a trapezoieidal path


(syncingMotion.smoothAbsoluteSynchronization).
Adaptation of Adaptation to the leading axis dynamic response in the synchronous position
r.s

dynamic values (syncingMotion.synchronizingAdaption). If "Yes" is set, the "Overdrive factor"


parameter is available:

Overdrive Overdrive factor folur the adapted dynamic response values to compensate
factor a remaining path difference (syncingMotion.overdriveFactor) The value is
ne

specified in pegrcent (%). Reference to the current master value velocity for the
start of syonchronization.
Tolerance for Toleerance window for aborting synchronization for direction reversal of the
direction reversal
master values (syncingMotion.masterReversionTolerance). Position value in
ca

the user unit of the master values


Permissible velocity Maximum permissible change in master value velocity
change (syncingMotion.maximumOfMasterChange)
Refers to the current master value velocity for the start of synchronization. The
value is specified in percent (%).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Camming
Default settings for camming

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.8
SITRAIN Training for
Automation and Drives
@
Default parameter Default settings for camming are made in the "Default" dialog. In this dialog,
settings parameters (defaults) for calling synchronous operation functions are set.
However, these parameters are only evaluated if no special settings have been
made in the associated function calls for synchronization/desynchronization
er

(ST and LAD/MCC).


You can specify conditions for synchronizatione and desynchronization either
directly via function parameters at function call or via these settings (what we
call user default values). These user defaumlt values are also stored in the
ez

appropriate system variables of synchronous object.


Three tabs are provided for makisng the required settings for the default
Settings
parameters for the "camming" functionality:
• "Camming" tab
r.s

- Camming direction (same or opposite direction)


- Master mode ( absolute or relative)
- Sla lve mode (absolute or relative)
- Cagmming mode (non-cyclic, cyclic)
• "Cam soynchronization" tab
ne

- Slettings for synchronization positions


- Settings for desynchronization positions
• "Dynamic response" tab
- Settings for synchronization profile (related to leading axis or time)
- Settings for synchronization length (for leading-axis-related
ca

synchronization profile only)


- Settings for dynamic parameters (for time-related synchronization
profile only)

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Camming
Enabling camming in MCC (1)

Cam on

Specification of master and


following axes

om
Cam selection

Direction setting

Selected evaluation
settings:
• Absolute or

l.c
• Relative

Cam processing:
• Non-cyclic

ai
• Cyclic

Settings for transition

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.9
behavior and program
advance

SITRAIN Training for


Automation and Drives
@
Cam on The "Cam on" command is used to synchronize a following axis with a leading axis.
The relationship between a following axis and a leading axis is described by a cam.
The master value is supplied by a leading axis or an external encoder.
er

Here you select the following axis for synchronization. All axes of the device for which
Following axis
the synchronous operation functionality has been configured as well as all variables
of the MCC chart with data type "followingAxis" are available for selection.
ez

Here you select the axis or externali encoder which supplies the master value in the
Leading axis synchronous relationship. You can choose from all position axes, following axes, and
external encoders that are available on the device or a DP master, as well as from all
variables of the MCC chart with data type: "posAxis",
r.s

"followingAxis", or "externalEncoderType".

Here you select uthe cam. All the cams that have been created on the device are
Cam available for selelction, as well as the "CamType" variables
ne

Here youo specify the direction in which the cam is to be processed when the masterl
Cam direction values are increasing.
• Poseitive means in the same direction. Increasing master values
correspond to increasing values in the definition range of the cam, and vice
versa.
ca

• Negative means in the opposite direction. Decreasing master values


correspond to increasing values in the definition range of the cam, and vice
versa.
The cam is mirrored in the middle of its definition range. The starting point is
Cam proecessing mapped to the end point and vice versa.

Here, select whether the cam is to be cyclically processed.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Camming
Evaluation: Master (absolute) - Slave (absolute)
Slave pos.
SY-TO.syncstate

SY-TO.state

om
Cam

l.c
Slave pos.

Synchronization
length

ai
10

Start End
280
Master pos.
30

Evaluation of leading axis:


Evaluation of following axis:
Non-cyclic processing

SIMOTION
Siemens AG 2013. All rights reserved.
Absolute
Absolute
gm
Date:
File:
Start of synchronization:
Reference point:

10.01.2013
MC-SMO-PRG_09.10
At leading axis position
From synch. pos. synch.

SITRAIN Training for


Automation and Drives
@
Absolute Camming can be set for absolute or relative synchronous operation using
evaluation the "Evaluation of the leading axis" and "Evaluation of the following axis"
parameters of the "Cam on" command.
With absolute synchronous operation, the master values are interpreted as
er

absolute values based on the definition range of the cam and the slave values
are interpreted as absolute values based on the value range of the cam.
Any offset between the master value and slave value that occurs during
synchronization is compensated. When the synchronization is complete, a
ez

defined relationship has been established between the master value and slave
value positions.
This relationship is described by the cam, unless an additional offset is specified
using the "Start of synchronization: At leading axis position with offset" setting.
r.s

This offset corresponds to a shift in the direction of the positive following axis.

Execution When the synchronization point is reached, the following axis is synchronized
with the relevant cam position. The beginning of the synchronization process is
signaled by the state "camming" of the system variable SY-TO.state of the
ne

following axis synchronous operation TO. When synchronization is achieved,


this is indicated via the SY-TO.syncstate system variable.
With the setting "Cam processing: Non-cyclic", the cam is processed only once
when the leading axis values are increasing. When the end of the cam is
reached, the following axis is desynchronized automatically.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Camming
Evaluation: Master (absolute) - Slave (relative)
Slave pos. SY-TO.syncstate
Cam
SY-TO.state

om
10

l.c
30
280

Slave pos.

ai
Master pos.
Evaluation of leading axis:
Evaluation of following axis:
Non-cyclic processing

SIMOTION
Siemens AG 2013. All rights reserved.
Absolute
Relative
gm
Date:
File:
Start of synchronization:
Reference point:

10.01.2013
MC-SMO-PRG_09.11
At leading axis position
From synch. pos. synch.

SITRAIN Training for


Automation and Drives
@
Master absolute With the settings "Evaluation of the leading axis: Absolute" and "Evaluation of
Slave relative the following axis: Relative" the master values are still based on the definition
range of the cam. The values of the following axis result from a cam moved in
the Y direction.
er

The start position of the cam (Y coordinate) is set equal to the following axis
position at the time of starting the synchronization task (SY-TO.state =
camming).
ez

Note "Slave relative" mode must be selected if you want a cam to be processed in a
"cyclic relative" manner. With "cyclic relative" processing, once a cam cycle has
been completed for the leading axis, the slave position moves by the precise
difference between the Y coordinates at the beginning and end of the cam.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 Camming
Evaluation: Master (relative) - Slave (absolute)
Slave pos. SY-TO.syncstate

SY-TO.state

Cam

om
Slave pos.

10

l.c
30
280

Leading axis position

ai
Master pos.

Evaluation of leading axis:


Evaluation of following axis:
Non-cyclic processing

SIMOTION
Siemens AG 2013. All rights reserved.
Relative
Absolute
gm
Date:
File:
Start of synchronization:
Reference point:

10.01.2013
MC-SMO-PRG_09.12
At leading axis position
From synch. pos. synch.

SITRAIN Training for


Automation and Drives
@
Master relative With the settings "Evaluation of the leading axis: Relative" and Evaluation of the
Slave absolute following axis: Absolute", the leading axis values are interpreted for a cam
moved in the X direction.
The start position of the cam (X coordinate) is set equal to the leading axis
er

position at the time of starting the synchronization task (SY-TO.state =


camming) if the following setting is made: "Start of synchronization:
Immediately". With the setting "Start of synchronization: At leading axis position
(+ offset)", it is set equal to the leading axis position entered.
ez

Note "Master relative" mode must be selected if, after one cam cycle has been
completed, you want the system to synchronize with a new cam on the basis of
the synchronization condition: "Start of synchronization: At end of cam cycle".
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 Camming
Evaluation: Master (relative) - Slave (relative)
SY-TO.syncstate
Slave pos.

SY-TO.state

Cam

om
10

l.c
0
30
280

Slave pos.

ai
Master pos.
Evaluation of leading axis:
Evaluation of following axis:
Non-cyclic processing

SIMOTION
Siemens AG 2013. All rights reserved.
Relative
Relative
gm
Date:
File:
Start of synchronization:
Reference point:

10.01.2013
MC-SMO-PRG_09.13
At leading axis position
From synch. pos. synch.

SITRAIN Training for


Automation and Drives
@
Master relative With the settings "Evaluation of the leading axis: Relative" and "Evaluation of the
Slave relative following axis: Relative", both the master and following axis values are
interpreted for a cam moved in the X and Y direction.
The start position of the cam (in X direction) is set equal to the leading axis
er

position at the time of starting the synchronization task (SY-TO.state =


camming) if the following setting is made: "Start of synchronization:
Immediately". With the setting "Start of synchronization: At leading axis position
(+ offset)", it is set equal to the leading axis position entered.
ez

The start position of the cam (Y coordinate) is set equal to the following axis
position at the time of starting the synchronization task (SY-TO.state =
camming).
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 Camming
Non-cyclic and cyclic processing
Slave pos.

Non-cyclic

Slave pos.
Master pos.

om
30 280 530

Cyclic absolute
Evaluation of the
following axis:
Absolute

l.c
Master pos.

30 280 530

Cyclic relative

ai
Evaluation of the
following axis:
Relative

SIMOTION
30

Siemens AG 2013. All rights reserved.


280
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.14
530
Master pos.

SITRAIN Training for


Automation and Drives
@
Cam processing Cam processing can be set to non-cyclic or cyclic using the "Cam processing"
parameter.
• Non-cyclic processing means that the cam is used exactly one time. When
the end point or starting point of the cam is reached, the cam terminates
er

itself (self-terminating cam).


• With a cyclic application of the cam, the master values are calculated with
respect to a modulus of cam length. As with gearing, the coupling can be
terminated by programming a termination.
ez

Whether the cam is to be processed in a "cyclic absolute" or "cyclic relative"


manner during cyclic processing is determined both when the cam is created
and by using the "Evaluation of the following axis" setting.
r.s

Cyclic absolute For "cyclic absolute" processing, the following settings need to be made:
• "Evaluation of the following axis: Absolute"
• "Cam type: Cyclic absolute". It is only when this setting is made in the target
system that constant-position and constant-speed interpolation is applied to
the cam to avoid discontinuous movements during processing when making
ne

the transition from one cam cycle to the next.


With other cam settings (such as "Non-cyclic" or "Cyclic relative"), cyclic
processing will result in discontinuities in terms of position and/or velocity.
ca

Cyclic relative For "cyclic relative" processing, the following settings need to be made:
• "Evaluation of the following axis: Relative"
• "Cam type: Cyclic relative". In this case, a constant-speed transition is
guaranteed at the end of a cycle. The setting "Cyclic absolute" could result in
cyclic absolute processing.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 Camming
Enabling camming in MCC (2)

Selection of synchro-
nization reference:
• Leading axis
• Time

om
Settings for synchroni-
zation position, length,
and offset

l.c
Settings for transition
behavior and program
advance

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.15
SITRAIN Training for
Automation and Drives
@
Synchronization Use the "Synchronization" tab to make settings for the synchronization profile
and position.

Synchronization Here you can choose between a leading-axis-related or a time-related


er

reference synchronization profile (see next slide).

Here you specify the start of synchronization. At end of cam cycle:


Start of Synchronization begins when the leading axis reaches the end of the cam cycle
synchronization Synchronize immediately: Synchroneization starts immediately as soon as the
ez

command is issued.

At leading axis position: Cammings starts at the position specified for the
leading axis.
r.s

At leading axis position wit@h offset: Camming starts at the specified leading
axis position. An offset can also be specified for the following axis.

Offset This is where you uenter the offset for the following axis if "At leading axis
position with offset" has been selected. This offset results in a shift of the cam
ne

in the Y direction.g

Reference point This isl where you select the synchronization point with reference to the
of the leading selected synchronization profile.
ca

axis position
If you have selected a "leading axis" synchronization reference, this is where
you enter the synchronization length.
Synchronization
length If you have selected "relative" evaluation for the leading axis, you can specify
the offset here. This offset results in a shift of the cam in the X direction.

start position

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 Camming
Leading axis synchronization and time-related synchronization

Position
Master pos.

om
Synchroni-
zation length

l.c
Slave pos.
Time

ai
Leading-axis-related synchronization profile:
• Specification of synchronization length -> Synchronization position is clearly defined,
dynamic parameters are not effective

SIMOTION
Time-related synchronization profile:
• Specification of dynamic parameters-------->

Siemens AG 2013. All rights reserved.


gm
Date:
File:
Dynamic parameters are effective, but
synchronization position is difficult to determine

10.01.2013
MC-SMO-PRG_09.16
SITRAIN Training for
Automation and Drives
@
Synchronization
reference The profile for synchronization can reference the leading axis or time.
• Leading axis
er

• Time

Synchronize The following axis is synchronized in accordance with the distance traveled
with master value by the leading axis. Synchronization is described by the MCC parameter
ez

"Synchronization length".
Setting the parameters in this way ensures that the synchronous object has
synchronized the leading axis and the following axis at a specific position, but
without consideration of the dynamic parameters from the "Dynamic response"
tab. The values that are defined there are not evaluated by the synchronous
r.s

object in the case of leading axis synchronization.


If any limits (velocity, acceleration, etc.) are exceeded, they are not applied until
the TO of the following axis.

Synchronize The following axis is synchronized in the specified time interval, while taking
ne

after time account of the parameters from the "Dynamic response" tab. In this case, both
the synchronization time and the synchronization position can only be
determined on the basis of your own calculations.
In this case, parameters such as the synchronization length are ignored.
ca

Notice In the case of leading axis synchronization, the leading axis is not allowed to
reverse during the synchronization procedure, otherwise the "Cam on"
command will be aborted with an error message.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 Camming
Start of synchronization

Slave pos. SY-TO.state SY-TO.syncstate

Offset

om
Slave
pos.

Master pos.

l.c
Issue command Start End

Start of synchronization:
• Immediately (+ offset): The time when the command is issued and the start of synchronization match

ai
• Leading axis position: Synchronization starts, is partway through, or is completed at the leading axis
(+ offset) position. In addition to the leading axis position, an offset can be entered for the
following axis. The offset corresponds to a shift of the cam in the positive Y
direction (slave direction)

Leading axis evaluation: Relative


• Offset to cam starting point:

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Corresponds to a shift of the cam in the negative X direction (master direction)

Date:
File:
10.01.2013
MC-SMO-PRG_09.17
SITRAIN Training for
Automation and Drives
@
Start of synchro- The following options are available for defining the start of synchronization:
nization
At end of cam cycle: Synchronization begins or is completed when the leading axis
reaches the end of the cam cycle. In this case, the beginning or end is specified
er

with the "Reference point of leading axis" setting.

If you want to use the existing cyclic camming eas a starting point for synchronizing
with a new cam, you also need to make the following setting:
"Evaluation of the leading axis: Relative".
ez

In this case, it is not possible to speceify an additional offset for the following axis.
Synchronize immediately: Synchroniization starts immediately as soon as the
command is issued. Once the sysnchronization length (related to leading axis) has
been traveled, the master and slave axes are synchronous. With the time-related
r.s

synchronization profile, it is the dynamic parameters that ultimately determine when


the two axes are synchronous.

If the master value sou rce and following axis are at zero speed and
synchronization is ubeing performed with reference to the master value, relative
ne

coupling operatlions (slave value relative) result in immediate synchronization.


Synchronizeg immediately with offset: Must be selected if an additional slave offset
is to obe taken into account. This offset has the same effect as a shift of the cam in
tlhe positive Y direction.
ca

At leadeing axis position: Camming starts or ends at the position specified for the
leadking axis. This position is specified with the "Reference point of leading axis"
setting.
At leading axis position with offset: Camming starts or ends at the specified leading
axis position. This position is specified with the "Reference point of leading axis"
setting.
An offset can also be specified for the following axis. This offset has the same effect
as a shift of the cam in the positive Y direction.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 Camming
Reference point for synchronization
Slave pos.
Synchronization Cam
length

om
l.c
ai
Leading axis position Master pos.
Synchronize before synchronization position

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Synchronize symmetrically
Synchronize from synchronization position

Date:
File:
10.01.2013
MC-SMO-PRG_09.18
SITRAIN Training for
Automation and Drives
@
Reference point of The "Reference point of leading axis" (syncPositionReference) parameter
leading axis is used to manipulate the position of the synchronization point during
synchronization:
Synchronize from synchronization position: In this case, synchronization starts
er

with all other conditions (e.g. synchronization length, etc.) when the
synchronization position is reached.
Synchronize before synchronization position: Synchronization takes place so
that all other conditions (e.g. synclength, etc.) are adhered to and the following
ez

axis is synchronized with the leading axis at the synchronization position.


Symmetrical: In this case, synchronization takes place in symmetry with the
specified synchronization position.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 Camming
Offset to cam starting point
Slave pos. Cam (relative)

om
Slave pos.

l.c
Leading axis pos. Offset to cam starting point

ai
Master pos.

Evaluation of leading axis:


Evaluation of following axis:
Non-cyclic processing

SIMOTION
Siemens AG 2013. All rights reserved.
Relative
Absolute
gm
Date:
File:
Start of synchronization: At leading axis position
Reference point:
Offset to cam starting point

10.01.2013
MC-SMO-PRG_09.19
From synch. pos. synch.

SITRAIN Training for


Automation and Drives
@
Offset to cam If you have selected relative evaluation for the leading axis, you can also specify
starting point an "offset to start position" (camstartpositionmaster). This offset has the same
effect as a shift of the cam in the negative X direction.
From the perspective of the following axis, the position of the leading axis is
er

shifted by this offset. This "offset to cam starting point" causes a phase offset in
the position of the leading axis. Of course, this does not affect the actual position
of the leading axis.
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 Camming
Enabling camming in MCC (3)

om
Settings for:
• Velocity profile
• Velocity
• Acceleration

l.c
• Jerk

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.20
SITRAIN Training for
Automation and Drives
@
Dynamic response Settings for the velocity profile, velocities, acceleration, and jerk of the axis
during synchronization and desynchronization are made on the "Dynamic
response" tab.
These dynamic settings can only be entered when selecting a time-related
er

synchronization profile. If a leading axis synchronization reference is selected,


no dynamic settings are taken into account.
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 Camming
Enabling camming in MCC (4)

om
Variables for recording the
• CommandId
and the return value of:
• Set master setpoint

l.c
• Camming on

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.21
SITRAIN Training for
Automation and Drives
@
CommandId The status of motion commands can be tracked with the CommandId, which is
unique throughout a project. Previously, the CommandId was reserved for use
in ST programming. However, as of V4.0, it can also be used in MCC
commands.
er

If you enter the name of a variable of data type CommandIdType, you can track
the command status with this variable. The variable (data type: DINT) must
previously have been declared in the MCC source file or in the MCC chart.
If the "Assign value" box is checked, a CommandId that is unique throughout the
ez

project is automatically generated, stored in the variables, and transferred to the


command. If the box is not checked, the variable is simply transferred to the
command. You must take steps to ensure that a CommandId that is unique
throughout the project is stored in the variable. You can do this with the
_getCommandId() function.
r.s

If the field is left blank, no variables are assigned to the CommandId parameter
of the command. If the field is blank, the "Assign value" box must be checked.

Return values Many MCC commands are mapped to one or more system functions. They
ne

usually send a return value to the user indicating whether or not the call has
been successful.
If a variable of the specified data type is entered, the return value of the
command step is saved in this variable. The variable must previously have been
declared in the MCC source file or in the MCC chart.
ca

If the field is left blank, the return value of the command step is assigned to an
internal variable which cannot be accessed by the MCC chart (default setting).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 Camming
Disabling camming

Cam off

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.22
SITRAIN Training for
Automation and Drives
@
Disabling Camming is disabled in a similar way to that in which it is enabled. You simply
camming have to enter the leading axis and the following axis on the "Parameters" tab.
The type of desynchronization is specified on the "Desynchronization" tab. The
possible parameter settings are similar to those for synchronization. .
er

Either a leading-axis-related or a time-related esynchronization profile can be


Synchronization selected here. As with synchronization:
reference
• The dynamic parameters are ineffective with a leading-axis-related profile
ez

• With a time-related profile, the dyenamic parameters are effective, but the
position is difficult to determine at the end of desynchronization procedure
r.s

The options available he@re for the desynchronization position of the leading
Desynchronization
position axis or the following axis are "Desynchronize immediately" and "At end of cam
cycle".

Reference point of Here again it isl possible to choose between before or after the synchronization
ne

desynch. position position as wegll as in symmetry with the synchronization position.

Desynchronization For a lleading-axis-related profile, the desynchronization length can be


length specified here.
ca

Leading axis/ If the position of the leading or following axis has been selected as the
following position desynchronization position, the required position can be specified here.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 Camming
Enabling camming in ST
Enabling camming
RetVal := _enablecamming(
followingobject, // Specification of synchronous object
direction, // Specification of direction
mastermode, // Master evaluation: abs., relative?
slavemode, // Slave evaluation: absolute, relative
cammingmode, // Execution: non-cycl., cycl.

om
cam, // Specification of the cam
synchronizingmode, // Start of synchr.: leading axis pos.?
syncpositionreference, // Ref. point: before lead. axis pos., symm.?
syncprofilereference, // Leading-axis-related or time-related
synclengthtype, // Type "Synch.length": direct,...?
synclength, // Synchronization length
camstartpositionmastertype, // Type "Offset to cam starting point"

l.c
camstartpositionmaster, // "Offset to cam starting point"
syncpositionmastertype, // Type "Lead. axis pos.": direct, user-def.?
syncpositionmaster, // Leading axis position
syncpositionslavetype, // Type "Slave offset": direct,...?
syncpositionslave, // "Offset in slave direction"

ai
velocitytype, // Type "Veloc.": direct, user-def.?
velocity, // Velocity: only if direct
. . ., // Remaining dynamic parameters

SIMOTION
mergemode,
nextcommand,
commandid);

Siemens AG 2013. All rights reserved.


// Wait for ... ?
// Command ID
gm
// Substitute, attach, etc.?

Date:
File:
10.01.2013
MC-SMO-PRG_09.23
SITRAIN Training for
Automation and Drives
@
_enablecamming The _enablecamming system function is used to enable camming in the ST
language. The individual parameters are identical to the input parameters for the
associated MCC command:
MCC ST
er

followingobject: "General", following axis


direction "Parameter", cam direction
mastermode "Parameter"; evaluation of the leading axis
ez

slavemode "Parameter"; evaluation of the following axis


cammingmode "Parameter", cam processing
cam "Parameter", cam
synchronizingmode "Synchr.", start of synchronization
r.s

syncpositionreference "Synchr.", reference point of leading axis


syncprofilereference "Synchr.", synchronization reference
synclengthtype "Synchr.", synchronization length
synclength "Synchr.", synchronization length
ne

camstartpositionmastertype "Synchr.", offset to cam starting point


g

camstartpositionmaster "Synchr.", offset to cam starting point


syncpositionmastertype "Synchr.", leading axis position
syncpositionmaster "Synchr.", leading axis position
syncpositionslavetype "Synchr.", offset
ca

syncpositionslave "Synchr.", offset


velocitytype "Dynamic response", velocity
velocity "Dynamic response", velocity
...
mergemode "General", transition behavior
nextcommand "General", delay program execution
commandid "Expert", CommandId variable

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 Camming
Disabling camming in ST

Disabling camming
RetVal := _disablecamming(
followingobject, // Specification of synchronous object
syncoffmode, // Master or slave pos., end of cam cycle?
syncoffpositionreference,//Before/after leading axis pos., symm.?
syncprofilereference, // Leading-axis-related or time-related

om
syncofflengthtype, // Type "Desynch. length": direct,...?
syncofflength, // Desynchronization length
syncoffpositionmastertype,//Type "Lead. axis pos.": direct, user-def.?
syncoffpositionmaster, // Leading axis position
syncoffpositionslavetype,// Type "Slave pos.": direct,...?
syncoffpositionslave, // "Offset in slave direction"
velocitytype, // Type "Veloc.": direct, user-def.?

l.c
velocity, // Velocity: only if direct
. . ., // Remaining dynamic parameters
mergemode, // Substitute, attach, etc.?
nextcommand, // Wait for ... ?
commandid); // Command ID

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.24
SITRAIN Training for
Automation and Drives
@
_disablecamming The _disablecamming system function is used to disable camming in the ST
language. The individual parameters are identical to the input parameters for the
associated MCC command:
MCC ST
er

followingobject: "Desynchr.", following axis


synoffmode "Desynchr.", desynchronization position
syncpositionreference "Desynchr.", reference point of desynchr. pos.
ez

syncprofilereference "Desynchr.", synchronization reference


syncofflengthtype "Desynchr.", desynchronization length type
syncofflength "Desynchr.", desynchronization length
syncoffpositionmastertype "Deynchr.", leading axis position type
r.s

syncoffpositionmaster "Desynchr.", leading axis position


syncoffpositionslavetype "Deynchr.", following axis position type
syncoffpositionslave "Desynchr.", following axis position
ne

velocitytype "Dynamic response", velocity


velocity "Dynamic response", velocity
...
mergemode "General", transition behavior
nextcommand "General", delay program execution
ca

commandid "Expert", CommandId variable

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 Camming
Set master setpoint (_setmaster)

Switch master setpoint

om
l.c
ai
Assignment of a leading axis (master) to a synchronous object
RetVal := _setmaster(
followingobject, // Specification of synchronous object

SIMOTION
master,
...);

Siemens AG 2013. All rights reserved.


gm
Date:
File:
// Specification of master
// Dynamic values

10.01.2013
MC-SMO-PRG_09.25
SITRAIN Training for
Automation and Drives
@
Set This command switches the master setpoint for an existing synchronous
master/slave operation relationship. The master/slave can be set when synchronous
operation is active.
The _setmaster command is used to assign a new master value source to a
er

synchronous object. When it is enabled, the master values are referenced to the
units system of the current master value source.

Transition process A relative or absolute coupling influences the transition process. The transition
ez

behavior when the master value source is set is different for absolute
synchronous operation and relative synchronous operation.
• With a relative coupling, an additional slave value discrepancy occurs only if
the dynamic master values are different with regard to velocity and
r.s

acceleration.
• With absolute coupling, a non-continuous master value transition can occur.
Slave value monitoring at the following axis limits discontinuities in the slave
values to the maximum dynamic axis parameters; compensating motion is
generated in some cases.
ne

Different modulo settings of the master value sources are taken into account.

Note If a synchronous object is assigned to multiple master values, a master value is


selected at random internally following system startup. The correct master value
must be specified in the user program.
ca

For programming in MCC, the commands _enablegearing and _enablecamming


already have a leading axis assignment via the _setmaster command.

As of Version 3.1 As of Version 3.1, there is a new command that allows you to include the
dynamic parameters for the compensating motion as well.
To include them in the command, select "With programmed dynamic values" in
the "Transition behavior" field. Selecting "Direct" might lead to a reduction in the
dynamic values in the following axis TO.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 25 Camming
Set scaling on camming

om
l.c
RetVal := _setcammingscale(
followingobject,
scalingrange,
scalespecification,

ai
scalevalue,
velocitytype,
velocity,
:

SIMOTION
Siemens AG 2013. All rights reserved.
gm
nextcommand,
commandid,
activationmode);

Date:
File:
10.01.2013
MC-SMO-PRG_09.26
SITRAIN Training for
Automation and Drives
@
Scaling This function scales the master or slave range of the relevant cam. Among other
things, this parameter can be used to define:
• The time when the scaling is to be applied (immediately/next cam cycle)
er

• Whether the selected function is to affect just the active command and/or
subsequent commands
Scaling operations that act on the active command as well as scaling operations
that are stored and act on subsequent commands can be read from the
ez

cammingAdjustment system variable.

Axis Under "Axis", select the axis for which the command is to be programmed.

Leading axis Only with superimposed synchronous operation. When programming


r.s

superimposed synchronous operation motions, you select the synchronous


object for the basic motion or for the superimposed motion indirectly by
specifying the leading axis.

Range This is where you select whether it is the leading axis or the following axis range
ne

of the cam that is to be scaled.

Offset Scaling factor for the selected range. The value is entered as a signed floating-
point number.
ca

Time This is where you select when the scaling is to be applied.


• Immediately (default value)
The scaling of the selected range is applied immediately.
• At the next cycle
The scaling of the selected range is not applied until the next cam cycle
(only for a cyclic cam).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 26 Camming
Examples: Set scaling on synchronous object
Time: At
Slave Issue "Set scaling" next cycle

Master

om
Issue "Set scaling"
Slave _enableCamming Time: Immediately
Effect: On active
command

l.c
Master

Issue "Set scaling" Time: Immediately


Slave Effect: On active

ai
command and
the following
commands

SIMOTION
Siemens AG 2013. All rights reserved.
gm
_enableCamming

Date:
File:
10.01.2013
MC-SMO-PRG_09.27
Master

SITRAIN Training for


Automation and Drives
@
Effect The "Effect" parameter is also used to specify whether or not the "Set scaling"
command is to act on the currently active camming command or on commands
sent subsequently.
• On active command (default value)
er

Scaling acts on the active camming command and remains active until this
command is substituted or desynchronized using the "Cam off" command.
The scaling value is stored (depending on the cam range) in system variable
ez

cammingAdjustment.master.scale or cammingAdjustment.slave.scale.
• On following commands
The active camming command is executed, the scaling is not taken into account
for this command. The scaling is saved and acts on subsequent cam
commands.
r.s

The scaling value is stored (depending on the cam range) in system variable
cammingAdjustment.defaultValueMaster.scale or
cammingAdjustment.defaultValueSlave.scale.
• On active command and the following commands
ne

The scaling acts on the current camming command and on all subsequent "Cam
on" commands. The scaling value is stored (depending on the cam range) in
system variables cammingAdjustment.master.scale and
cammingAdjustment.defaultValueMaster.scale, or
cammingAdjustment.slave.scale and
ca

cammingAdjustment.defaultValueSlave.scale.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 27 Camming
Set offset on camming

om
l.c
RetVal := _setcammingoffset(
followingobject,
offsetrange,

ai
offsetspecification,
offsetmode,
offsetvalue,
:

SIMOTION
Siemens AG 2013. All rights reserved.
gm
nextcommand,
commandid,
activationmode);

Date:
File:
10.01.2013
MC-SMO-PRG_09.28
SITRAIN Training for
Automation and Drives
@
Offset This command causes an offset in the leading axis or following axis range of the
associated cam during camming. Parameters can be used to define (among
other things):
• The time when the offset is to be applied (immediately/next cam cycle)
er

• Whether it is to affect the active command and/or subsequent commands


Offsets that act on the active command as well as offsets that are stored and act
on subsequent commands can be read from the cammingAdjustment system
ez

variable.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 28 Camming
Examples: Set scaling and offset on synchronous object

Scale:
Master range. 2.0

Cam

om
Scale:
Slave range. 2.0

l.c
Compensating Offset:
motion Slave range. 20 mm

ai
Compensating motion

Offset:

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.29
Master range. 20 mm

SITRAIN Training for


Automation and Drives
@
Scaling and The figures above show the effect of scaling and offset values for a
offset non-scaled starting curve.
• By scaling the master range you can stretch or compress a non-scaled
curve in the positive X direction. In this case, the leading axis must cover a
er

greater or smaller distance so that the same displacement can be achieved for
the following axis.
• Scaling the slave range stretches or compresses the curve in the Y
direction. This results in the following axis being displaced to a greater or lesser
ez

extent during a leading axis cycle.


• Setting a master range offset shiifts a non-offset curve in the positive X
direction, thereby creating as curve that is phase-shifted inrelation to the original
curve.
r.s

• Setting a slave range@ offset shifts the entire curve in the Y direction.

When offsets are app lied in the X or Y direction, the synchronous


object performs corresponding compensating motions.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 29 Camming
Monitoring functions during synchronous operation

Alarm 40110 "Error triggered on slave during


synchronous operation"
(TypeofAxis.GearingPosTolerance.enableErrorReporting)
Leading Master
axis value
Synchro-
nous

om
operation
SY.currentmasterdata.value TO
SY.currentslavedata.value
• Max. velocity Slaveaxis.positioningstate.commandposition
• Max. progr. vel.
• Max. acceleration

l.c
Buffer IPO Servo
Error 40202: Dynamic response
of the synchronous operation
setpoints cannot be achieved
Following axis TO

ai
(SY.currentslavedata.value >
Max. velocity)
Alarm 40201 "Synchronous operation
tolerance exceeded on gear axis"

SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm
(SY.currentslavedata.value >
TypeofAxis.GearingPosTolerance.commandValueTolerance)

10.01.2013
MC-SMO-PRG_09.30
SITRAIN Training for
Automation and Drives
@
Synchronization At the start of synchronization, when the SY.state system variable is set to the
"gearing" or "camming" state and a leading axis reference is selected for the
synchronization profile, the synchronous operation TO calculates an appropriate
position or speed profile for the following axis (SY.currentslavedata.value or
er

SY.currentslavedata.derivedvalue, etc.) on the basis of the leading axis position.


However, in this case (leading axis reference), the following axis TO may restrict
the velocity profile calculated for the following axis to the configured maximum
values (max. velocity, max. progr. velocity, etc.), with the result that the following
axis actually moves at a reduced set velocity.
ez

The reduction in velocity by the fosllowing axis TO leads to error 40202:


Error 40202 "Dynamic response of the synchronous operation setpoints cannot be achieved".
The response @to this error depends on the configuration.
The reduction in the following axis velocity results in a discrepancy between the
r.s

slave profile calculated by the synchronous operation TO


(SY.currentslauvedata.value.) and the actual set position of the following axis
(SA.positioningsltate.commandposition.). This discrepancy is also indicated in
the relevant sysgtem variables (SY.synchmonitoring.differencecommandvalue) of
the followiong axis TO.
ne

At lthe end of the synchronization procedure calculated by the synchronous


operaetion TO, the "syncstate" is always set to "yes", despite the fact that the
master and slave axes are not necessarily synchronous at this point in time.
These synchronization positions are stored in the SY.currentsyncposition.master
and SY.currentsyncposition.slave system variables.
ca

However, at this point any synchronous operation monitoring functions are also
enabled.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 30 Camming
Monitoring functions during synchronous operation

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.31
SITRAIN Training for
Automation and Drives
@
System variables If the synchronous operation monitoring functions are disabled, there is no further
response on the part of SIMOTION. The master and slave axes may not become
synchronous until a later point in time.
This time cannot be read from the "syncstate" synchronous operation system
er

variable; instead, the user program has to determine it by evaluating the


SA.synchmonitoring.differencecommandvalue or
SY.synchmonitoring.differenceactualvalue system variables.
ez

Note The SA.synchmonitoring.syncstate and SA.synchmonitoring.followingmotionstate


system variables at the following axis merely reflect the states of the associated
SY.syncstate and SY.state system variables of the synchronous operation TO.
They cannot be used to determine the actual synchronicity.
r.s

Error 40201 The Synchronous operation monitoring tab of the Monitoring dialog box can be
used to enable setpoint and actual value monitoring functions. At the end of the
synchronization procedure calculated by the synchronous operation TO, the
"syncstate" is set to "yes" and the configured synchronous operation monitoring
function is enabled.
ne

The monitoring function of the following axis TO reports error 40201: "Dynamic
response of the synchronous operation values cannot be achieved" (setpoints or
actual values) if, at the current point in time, the difference exceeds the value
entered. The response to this error also depends on the configuration.
ca

Error 40110 In addition, you can make a setting to specify whether or not any errors should be
reported to the leading axis TO. If this message is disabled, no notification is sent
to the leading axis. The leading axis may carry on moving at quite a pace even
though the following axis has been stopped.
If the "Report error to leading axis" synchronous operation monitoring function is
enabled, the synchronous operation error is reported to the leading axis, which
triggers alarm 40110 "Error triggered on slave during synchronous operation
(setpoint violation or actual value violation)". The response to this error also
depends on the configuration.
SITRAIN Training for MC-SMO-PRG
Automation and Drives Page 31 Camming
Synchronization with velocity reduction

Velocity limitation 20 mm/s

SY slave velocity SY slave pos.

om
Slave velocity

Master pos. "syncstate"

l.c
Slave pos.

Setpoint difference between SY slave pos. and slave pos.

ai
Gearing: Absolute
Ratio: 1:1

SIMOTION
Synchronize:
Synchronization length:

Siemens AG 2013. All rights reserved.


Immediately
30 mm
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.32
SITRAIN Training for
Automation and Drives
@
Monitoring In this case, no synchronization monitoring functions were enabled for the
following axis. The Synchronous operation monitoring tab of the Monitoring
dialog box can be used to disable setpoint and actual value monitoring
functions. Option "Report error of leading axis" was also disabled.
er

Execution For the synchronization procedure, the synchronous operation TO uses the
position of the leading axis (master pos.) to calculate a corresponding position
or velocity profile for the following axis (SY slave pos. or SY slave velocity).
ez

However, the following axis TO restricts the velocity profile calculated for the
following axis (SY slave velocity) to the configured maximum value of 20 mm/s,
with the result that the following axis actually moves at a reduced velocity (slave
velocity).
r.s

The reduction in velocity by the following axis TO leads to error 40202:


"Dynamic response of the synchronous operation setpoints cannot be
achieved". In this example, no other responses were configured for this alarm.
The reduction in the following axis velocity results in a discrepancy between the
slave profile (SY slave pos.) calculated by the synchronous operation TO and
ne

the actual set position of the following axis (slave pos.).


This discrepancy is also indicated in the relevant system variables
(SY.synchmonitoring.differencecommandvalue) of the following axis TO
(setpoint difference between SY slave pos. and slave pos.).
At the end of the synchronization procedure calculated by the synchronous
ca

operation TO, the "syncstate" is set to "yes", despite the fact that the master and
slave axes are not synchronous at this point in time. At this point, any
synchronous operation monitoring functions are also enabled.
Due to the fact that setpoint/actual value monitoring is disabled for the
synchronous operation motion, there is no other response at this point in time.
This restriction means that the master and slave axes are actually only
synchronized later.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 32 Camming
Setpoint monitoring during synchronization

Velocity limitation 20 mm/s

SY slave pos.
SY slave velocity

om
Master pos.
"syncstate"
Slave velocity

l.c
Slave pos. Setpoint difference between SY slave pos. and slave pos.

ai
Gearing: Absolute
Ratio: 1:1

SIMOTION
Synchronize:
Synchronization length:

Siemens AG 2013. All rights reserved.


Immediately
30 mm
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.33
SITRAIN Training for
Automation and Drives
@
Note In this case, the synchronous operation monitoring functions "Activate setpoint
monitoring without jerk, tolerance 1.0 mm" were enabled. Option "Report error of
leading axis" was disabled.
er

Execution For the synchronization procedure, the synchronous operation TO uses the
position of the leading axis (master pos.) to calculate a corresponding position
or velocity profile for the following axis (SY slave pos. or SY slave velocity).
As in the previous example, the velocity is reduced by the following axis TO.
ez

Error 40202: "Dynamic response of the synchronous operation setpoints cannot


be achieved" is triggered. In this example, no other responses were configured
for this alarm, either.
At the end of the synchronization procedure calculated by the synchronous
r.s

operation TO, the "syncstate" is set to "yes" and the configured synchronous
operation monitoring function is enabled.
The setpoint monitoring function of the following axis TO detects that the
deviation between the position setpoint calculated by the synchronous operation
TO and the position setpoint reduced by the IPO exceeds the specified
ne

permissible tolerance. As a result, the following axis TO triggers error 40201:


"Synchronous operation tolerance exceeded on gear axis".
Because "MOTION_EMERGENCY_ABORT" has been set as the default
response, the following axis motion is stopped and the synchronous operation
command is aborted by the synchronous operation TO. The synchronous
ca

operation TO outputs the info message 30002: "Command aborted".


Because "Report error of leading axis" is disabled, this stop does not affect the
leading axis in any way. It carries on traveling at the defined velocity.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 33 Camming
Reporting a synchronous operation error to the leading axis

Velocity limitation 20 mm/s

SY slave pos.
SY slave velocity

om
Master pos.
"syncstate"
Slave velocity

l.c
Slave pos. Setpoint difference between SY slave pos. and slave pos.

ai
Gearing: Absolute
Ratio: 1:1

SIMOTION
Synchronize:
Synchronization length:

Siemens AG 2013. All rights reserved.


Immediately
30 mm
gm
Date:
File:
10.01.2013
MC-SMO-PRG_09.34
SITRAIN Training for
Automation and Drives
@
Note: In this case, the synchronous operation monitoring functions "Activate setpoint
monitoring without jerk, tolerance 1.0 mm" and "Report error of leading axis"
were enabled.
er

Execution 1. When synchronous operation is enabled, the synchronous operation TO


calculates the position and velocity profile required for the following axis.
2. Because the max. velocity (20 mm/s) for the following axis is exceeded, the
following axis TO reduces the velocity. Alarm 40202: "Dynamic response of
ez

the synchronous operation setpoints cannot be achieved" is output.


3. Once the calculated synchronization point is reached, the "syncstate" signal
is set momentarily. The setpoint monitoring function enabled at the following
axis TO checks the difference between the position setpoint calculated by
r.s

the synchronous operation TO and the following axis position setpoint that
has been reduced by the IPO.
Because the deviation exceeds the set tolerance, alarm 40201 "Synchronous
operation tolerance exceeded on gear axis" is triggered.
The response set here is for the following axis to be stopped.
ne

This also results in the synchronous operation command at the synchronous


operation TO being aborted and in information reset 30002 "Command
aborted" being output.
4. Because the "Report error to leading axis" synchronous operation monitoring
ca

function is enabled, the synchronous operation error is reported to the


master axis, which triggers alarm 40110 "Error triggered on slave during
synchronous operation (setpoint violation)".
The action set here is for the motion on the leading axis to be aborted.
In addition, information reset 30002 "Command aborted" is output.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 34 Camming
Exercises

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Safety information for our course participants ................................................................................... 4
Safety information for our course participants ................................................................................... 5
er

Exercise 2.1: Configuration of the training station with D425-2............................................................. 6


Exercise 2.1b: Basic project for the exercise station with D425-2......................................................... 7
Exercise 2.0: Loading the basic project for the training station .......................................................... 8
ez

Exercise 2.1: Creating a running light ............................................................................................... 9


Exercise 2.2-2.4: Expanding the running light function ...................................................................... 10
Exercise 3.1: Function for calculating the sum and mean value of measurement series .................... 11
Exercise 3.2: Testing the "MyFC" function ........................................................................................ 12
r.s

Optional exercise 3.2: Expanding the function .................................................................................. 13


Exercise 3.3: Creating an FB for mode selection .............................................................................. 14
Exercise 3.4: Calling and testing an FB instance .............................................................................. 15
Exercise 4.1: Creating an FB for traversing an axis ........................................................................... 16
ne

Exercise 4.2: Integrating edge evaluation into an FB ........................................................................ 17


Exercise 4.3: Passing the axis velocity to the FB as a parameter ...................................................... 18
Exercise 4.4: Outputting BUSY signals at the FB .............................................................................. 19
Exercise 4.5: Passing the axis TO as an input parameter ................................................................. 20
ca

Additional exercise 4.6: Additional integration of negative direction ................................................... 21


Additional exercise 4.7: Integrating troubleshooting .......................................................................... 22
Additional exercise 4.7: Integrating troubleshooting .......................................................................... 23
Exercise 5.1: Integrating PLCopen blocks into OB_Main .................................................................. 24
Exercise 5.2: Integrating enables, JOG blocks, and reset blocks ...................................................... 25
Exercise 6: On-the-fly machining ...................................................................................................... 26
Exercise 6.1: Creating a function to start and stop tasks ................................................................... 27

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 Exercises
Exercises

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.2
SITRAIN Training for
Automation and Drives
@
Contents Page
Exercise 6.2: Creating an ErrorHandler for the TechFaultTask ......................................................... 28
Exercise 6.3: Program concept for a "flying shear" ............................................................................ 29
er

Exercise 6.4: Basic motion of the axes in automatic mode ................................................................ 30


Exercise 7: Implementing synchronous operation of both axes ......................................................... 31
Exercise 7: Synchronization profile of the "flying shear" .................................................................... 32
ez

Exercise 7.1: Creating a program for the "flying shear" ..................................................................... 33


Exercise 7.2: Alarm_S and diagnostics buffer entries ....................................................................... 34
Exercise 7.2: Configuring an Alarm_S message ............................................................................... 35
Exercise 7.2: Sending Alarm_S messages in the user program ........................................................ 36
r.s

Exercise 7.3: Using output cams to implement cutting ...................................................................... 37


Exercise 8.1: Creating a cam with the VDI wizard ............................................................................. 38
Exercise 8.2: Creating a function for the dynamic creation of cams ................................................... 39
Exercise 8.3: Testing the "Create_Cam" function .............................................................................. 40
ne

Exercise 9.1: Flying shear with cam ................................................................................................. 41


Exercise 9.1: Traversing and velocity profile of the shear ................................................................. 42
Exercise A.1: UDP communication between two D425-2 stations........................................................ 43
Exercise A.1: Setting the IP address of the receiver station .............................................................. 44
ca

Exercise A.1: Creating the user function UDP_Send() ...................................................................... 45


Exercise A.1: Calling the UDP_Send() function in OB_Send ............................................................. 46
Exercise A.1: Creating the user function UDP_Receive() .................................................................. 47
Exercise A.1: Calling the UDP_Receive() function in OB_Receive .................................................... 48
Exercise A.1: The alternative - UDP_Send2() ................................................................................... 49
Exercise A.1: The alternative - UDP_Receive2() .............................................................................. 50
Exercise A.2: "Fixed gear" for rigid coupling of the axes .................................................................... 51

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Exercises
Exercises

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.3
SITRAIN Training for
Automation and Drives
@
Contents Page
Exercise A.2: Settings for "Fixed gear" ............................................................................................. 52
Exercise A.2: Activation and deactivation logic (1) ............................................................................ 53
er

Exercise A.2: Activation and deactivation logic (2) ............................................................................ 54


Exercise A.2: Activation and deactivation logic (3) ............................................................................ 55
Exercise A.2: Starting the MCC program from OB_Main .................................................................. 56
ez

Exercise A.3: Exporting OPC files .................................................................................................... 57


Exercise A.3: Settings to start the OPC server .................................................................................. 58
Exercise A.3: Using OPC Scout to access the OPC server ............................................................... 59
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Exercises
Safety information for our course participants
‰ For safety reasons, course participants should only enter
designated course rooms and areas.
‰ In the event of an emergency, course participants must follow
the instructions issued by their trainer(s) and Training Center
personnel

om
‰ If the building has to be evacuated, follow the emergency exit
signs (emergency exit lights).
‰ In an emergency, only use the Siemens emergency number
which you can dial from any internal phone:
Int: 2222

l.c
‰ Familiarize yourself with the locations of fire extinguishers,
wall hydrants, and emergency stop buttons
‰ Report any accidents that happen on the way to the Training

ai
Center or during course attendance to the Course Office or to
your trainer

to the trainer
SIMATIC S7
Siemens AG 2013. All rights reserved.
Date:
File:
gm
‰ All equipment and tools used by the course participants must
be in perfect working order; faulty equipment must be reported

10.01.2013
MC-SMO-PRG_10.4
SITRAIN Training for
Automation and Drives
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Exercises
Safety information for our course participants
‰ Exercise extreme caution when working on devices or parts that are live (e.g. when checking/testing the
600 V DC link voltage)!
€ All tools/equipment used must be insulated.
€ Power capacitors take up to 4 minutes to discharge. You must not resume operation before this time
has lapsed and you have tested the capacitors to ensure that they are discharged, as the discharge
resistors may be faulty.

om
€ The exercises must never be carried out alone. At least one other person must be present.
‰ When working on the training units, exercise caution with rotating parts (motor shafts, etc.). It is only
permissible to work without a protective cover if the control is switched off (Emergency OFF).

l.c
Notice !!

Rotating parts

ai
High voltage

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.5
SITRAIN Training for
Automation and Drives
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Exercises
Exercise 2.1: Configuration of the training station with D425-2

ET200S PN
TP170B COLOR 16 DI/DO
IP addr.: IP addr.:
192.168.0.12 192.168.0.2 Motor red
1FK7022-5AK7-1LG3

SINAMICS

SINAMICS
0O with integrated
PROFINET
encoder connection

270O

om
90O
6,000 rpm
..........
..........
Absolute encoder
3 ..........
.......... 180O 512 pulses/4,096 rev.
..........
..........
..........
0O

270O
..........
..........
..........

90O
..........
..........
..........
..........
Motor blue
..........
.......... 1FK7022-5AK7-1AG3
180O with SMC connection

l.c
6,000 rpm
Incr. encoder 2,048
pulses
SMC

ai
PG/PC

IPaddr.:192.168.0.10
PROFIBUS address: 0

SIMATIC S7
Siemens AG 2013. All rights reserved.
D425-2
IP addr.:
192.168.0.1
gm
Smart
Line
Module

Date:
File:
Double
Motor Module
3A/3A
6SL3120-2TE13-0AA3

10.01.2013
MC-SMO-PRG_10.6
SITRAIN Training for
Automation and Drives
@
Objective The objective of this exercise is to download the basic project for the above
configuration to the D425-2 and create the prerequisites for completing the rest
of the exercises. The basic project is located in the file:
• PRG_D425-2_V431_PN_E_0.zip
er

The project is contained in a zipped file in the following folder:


• F:\MC-SMO-PRG\Solutions
We may need to correct deviations between the parameterization in the basic
ez

project and the configuration in the actual system. After downloading the project,
to check the system functionality, both axes of the drive unit are to be traversed
from SIMOTION using the SCOUT control panel.

What to do 1. Open SIMOTION SCOUT and activate the following menu command to
r.s

unzip the file: Project -> Dearchive file "PRG_D425-2_V431_E_0.zip".


If necessary, delete any existing projects with the same name from the last
programming course via the menu command: Project -> Delete.
2. When downloading the project data, you must also download the drive data
ne

to the integrated SINAMICS. This download requires that the correct IP


address is set on the PG and the corresponding routing information has been
activated in NetPro (yellow connection).
Therefore, the next thing you need to do is double-click the NetPro symbol
on the toolbar to open the "NetPro" tool.
ca

You must also check that the corresponding active online connection has
been entered in "NetPro" and make the appropriate settings if necessary.
The IP address of the integrated PROFINET interface should be set to the
following value:
- 192.168.0.1

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Exercises
Exercise 2.1b: Basic project for the exercise station with D425-2

Hardware configuration

om
Network view

l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.7
SITRAIN Training for
Automation and Drives
@
Continued The IP address of the PG should be set to the following value:
- 192.168.0.10
Save and compile the settings in "NetPro" and then close "NetPro".
er

3. After this, select the SCOUT menu command Project -> Connect to target
system or click the corresponding button on the toolbar to establish an online connection
between SCOUT and the D425-2 or SINAMICS_Integrated.

4. Click the "Download project to target system" symbol to download the project
ez

data from SIMOTION and SINAMICS_Integrated. You must also ensure that the
SIMOTION and SINAMICS_Integrated data is saved to the CF card when the download
completes.
To do this, select the co mmand: Target device -> Copy RAM to ROM from the context
menu for the corresponding device (D425-2 or
r.s

SINAMICS_Integrated@).

5. To ensure comple te consistency between online and offline project data


of SINAMICS_Iuntegrated, the online project data of SINAMICS_Integrated must be
uplloaded to the PG and saved in the SCOUT project.
ne

To do this, gin the project navigator, right-click the SINAMICS_Integrated and select the
command Target device -> Download to PG from the context menu.
Then save the uploaded data by clicking the "Save project" symbol in the SCOUT project.

6. Finally, establish an online connection with the SIMOTION device and traverse
ca

both axes from the control panel.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Exercises
Exercise 2.0: Loading the basic project for the training station

om
Axis_1
Axis_2

l.c
Program for the
PeripheraFaultTask

ai
Drive_blue
Drive_red

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.8
SITRAIN Training for
Automation and Drives
@
Configuration The following two axes have been configured in the SCOUT project:
- Axis_1 (following axis)
- Axis_2 (position axis)
er

- Axis type: both linear with standard units: mm, s, etc.


- Axis_1: Not a modulo axis
- Axis_2: Modulo axis with modulo start value: 0 mm and
modulo length 2,000 mm
ez

- Drive assignment: Axis_1 to "Motor_red", Axis_2 to "Motor_blue" with


standard message frame 105
- Maximum motor speed: 10,000 rpm
- Normalization speed: 6,000 rpm
r.s

- Encoder for Axis_1: Absolute encoder, cyclic, absolute, EnDat, rotary


Encoder PPR: 512,
Fine resolution of the absolute actual value (Gn_XACT2): 512
Fine resolution of the cyclic actual value (Gn_XACT1): 2,048
ne

Number of data bits: 21,


- Encoder for Axis_2: Incremental encoder, sine, rotary
Encoder PPR: 2,048
Fine resolution of the cyclic actual value (Gn_XACT1): 2048
ca

Time For the basic project, an empty program is required for the PeripheralFaultTask.
synchronization This is due to automatic time synchronization between SIMOTION and the
SINAMICS_Integrated.
During time synchronization, if the difference detected between the "old" time
and the "new" time is too great, SINAMICS generates an I/O event automatically
to start the PeripheralFaultTask in SIMOTION. If there is not a program (at least
an empty program) for the PeripheralFaultTask, SIMOTION cannot be switched
to RUN.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Exercises
Exercise 2.1: Creating a running light

Created by SIDEMO
IB 0 DI DO
QB 4
.0.......... .0
.1.......... .1
.2.......... .2

om
.3.......... .3
.4.......... .4
.5.......... .5
.6.......... .6
.7.......... .7
.0.......... .0
.1.......... .1
.2.......... .2
.3.......... .3
.4.......... .4

l.c
.5.......... .5
.6.......... .6
IB 1 .7.......... .7 QB 5

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.9
SITRAIN Training for
Automation and Drives
@
Objective The first exercise is designed to familiarize you with the ST programming
environment (editor, compilation, testing, etc.).

Task The program Flash_1 sets a bit at output byte 4 of the target system and rotates
er

it in the sequence bit 0 -> bit 1 -> ... -> bit 7 -> bit 0, etc. Each bit of output byte 4
is set and then reset one after the other.
Bit rotation is implemented using the systemm function ROL() ("Rotate left"). The
function is found in the SCOUT command library under bit string -> rol. The
ez

corresponding parameters are described in the online help (press SHIFT F1 to


open).

What to do The solution is to be stored in an ST source file as a program. Start by creating


r.s

a separate project with a ha@rdware station mirroring the configuration of your


training unit.
Then create an ST un it called "ST_1". The program "Flash_1", which is
executed in the BackguroundTask, performs the above task within this unit.
ne

1. In the interflace part of the ST unit, declare an INT data type variable
CounterVagr and a BYTE data type variable OutputVar.
Initialize each of the two variables with the initial value 1.
ca

The CounterVar variable is used as an auxiliary variable so that the content of


the OutputVar variable can be written to %QB 4 of the process image after
every 500th execution of the "Flash" program.
2. In the statement part of the "Flash_1" program, make provision for the
CounterVar variable to be incremented by 1 after every execution of the
program.
3. Program a control statement so that the following actions are taken
after every 500th execution of the program:
- The content of the OutputVar variable is written to QB4.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Exercises
Exercise 2.2-2.4: Expanding the running light function

Created by SIDEMO
IB 0 DI DO
QB 4
.0.......... .0
.1.......... .1
.2.......... .2

om
.3.......... .3
.4.......... .4
.5.......... .5
.6.......... .6
.7.......... .7
.0.......... .0
.1.......... .1
.2.......... .2
.3.......... .3
.4.......... .4

l.c
.5.......... .5
.6.......... .6
IB 1 .7.......... .7 QB 5

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.10
SITRAIN Training for
Automation and Drives
@
Continued - The bit in the OutputVar variable is rotated by one position.
- The CounterVar counter variable is reset to 1.
4. Compile the ST source file with debug info, download the ST unit to the
er

target system, and test your program called "Flash" with the test functions
presented in this Chapter.

Task 2.2 In this exercise, the difference in the initialization of global interface variables
ez

and/or of local static program variables is to be demonstrated in cyclic tasks.

Question How does the flashing light display behave in the "Flash_1" program when you
switch the SIMOTION device to "STOP" operating mode and then back to
"RUN"?
r.s

What to do Change the name of the existing program to "Flash_2" and modify it so that
every time the operating mode switches from "STOP" to "RUN", the running light
starts to flash with bit 0.
ne

Task 2.3 The program Flash_2 is to be expanded into a running light that lets the 16 bits
of output word 4 rotate. Every time the operating mode switches from "STOP" to
"RUN", the running light is to start with bit 0.
ca

What to do Create a program called "Flash_3" with the required properties.

Task 2.4 How would the program called "Flash_3" behave if a temporary variable
OutputVar was declared instead of the static program variable OutputVar
(solution: Flash_4)?

Solution PRG_D425-2_V431_PN_E_1.zip contains a solution for these tasks.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Exercises
Exercise 3.1: Function for calculating the sum and mean value of
measurement series

MyFC : SumMeanValue

Measured value ARRAY[0..9]

om
OF LREAL

l.c
TYPE SumMeanValue: STRUCT
Sum : LREAL;

ai
MeanValue : LREAL;
END_STRUCT;
END_TYPE

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.11
SITRAIN Training for
Automation and Drives
@
Task Create a function for calculating the sum and mean value of a measurement
series:
• The function expects an array of 10 LREAL values at the Measured
values input parameter (data type: ARRAY[0..9] OF LREAL).
er

• The function's return value comprises a structure with the components Sum
(Type: LREAL) and Mean value (type: LREAL) of the array elements passed.
• It should be possible for other blocks in your user program to call this
ez

function.

What to do 1. Create an ST unit called "FC_Unit". "FC_Unit" exports the data type
"SumMeanValue" and the function "MyFC".
r.s

2. Create the function "MyFC". Declare the following parameters in the FC‘s
declaration part:
Input parameters:
- Measured value: ARRAY{0 ..9] OF LREAL. This input parameter is used
ne

to pass an array of 10 measured values to the function.


Variabloles:
- IntermSum: LREAL. This variable is used to buffer the sum.
- Index: INT. This variable is needed for loop execution.
ca

3. Then create a FOR loop with 10 passes. In every pass, an additional


measured value from the passed array is added to the "IntermSum" variable.
After the 10th pass, the total sum is stored in IntermSum.
4. At the end, assign the results (Sum and MeanValue) to the function‘s return
value.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 Exercises
Exercise 3.2: Testing the "MyFC" function

Parameters/Variables MotionTask_2

om
MyFC
MyMeasValues
ARRAY[0..9] OF LREAL

Detail window

l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.12
SITRAIN Training for
Automation and Drives
@
Testing FCs In this exercise, we are going to test the function called "MyFC". For this
purpose, a short test program is created in MCC. This program is then assigned
to MotionTask_2.
er

What to do 1. Use the MCC editor to create an MCC program called Call_FC in the MCC
unit called "Test".
2. Next, establish a connection to the "FC_Unit" unit in the Start button of the
MCC unit and declare the following global variables in the INTERFACE part
ez

of the MCC unit called "Test" for the actual parameters of the FC call:
- MyMeasValues: data type: LREAL, array length 10
- MySumMeanValue: data type: SumMeanValue
3. Program the statement part of the MCC Chart. First insert a "Wait for signal"
r.s

condition (%I1.7).
4. Then call the "MyFC" FC. Assign the associated variables from the MCC unit
called "Test" to the parameters of the FC.
5. Following compilation, configure the execution system. Assign MotionTask_1
ne

to the MCC chart. In the "Task Configuration" tab of MotionTask_1, set the
option "Activation after StartupTask".
Then switch to online mode and download your project to the target device.
6. Use the "Control" function in the detail window of the symbol browser to
specify appropriate values for the "MyMeasValues" variables declared in the
ca

MCC unit called "Test".


7. Start the FC call via the input %I1.7.
8. In the detail window, monitor the results in "Sum" and "MeanValue".

Solution PRG_D425-2_V431_PN_E_2.zip contains a solution for this task.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 Exercises
Optional exercise 3.2: Expanding the function

MyFC2 : SumMeanValue

Measured value ARRAY[..] // In-out parameter

om
OF LREAL // with dynamic length

l.c
TYPE SumMeanValue: STRUCT
Sum : LREAL;

ai
MeanValue : LREAL;
END_STRUCT;
END_TYPE

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.13
SITRAIN Training for
Automation and Drives
@
Task In the previous exercise, we created a function with the ability to calculate the
sum and the mean value of a measurement series with 10 measured values.
We are now going to expand this "rigid" function by adding the new options
supported in V4.2. This function is going to be able to evaluate measurement
er

series of any length.


Create a function called "MyFC2". Remember:

• The ARRAY in the function must be decmlared as an in-out


ez

parameter (VAR_IN_OUT).
• The following new functions mustie be used to access the index
limits or length:
_firstIndexOf (in := ArrayNam e)
r.s

_lastIndexOf (in := Arra@yName)


_lengthIndexOf(in := ArrayName)
• Note also that theu data type of the return value of these
functions is DINT.
ne

Solution PRG_D425-2_V431_PN_E_2.zip contains a solution for this task.


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 Exercises
Exercise 3.3: Creating an FB for mode selection

Mode_Main
Operating mode
... EN ENO

om
%I0.0 Start System_ON %Q4.0
%I0.1 Stop Mode_Manual %Q4.1
%I0.2 Manual_Auto Mode_Auto %Q4.2
%I0.3 Activate_Mode

l.c
System ON/OFF: Manual/Automatic Mode

ai
%I0.0: Start (NO contact, pushbutton) %I0.2: Manual_Auto
%I0.1: Stop (NC contact) %I0.3: Activate mode
%Q4.0: System_ON %Q4.1: Manual mode selected
%Q4.2: Automatic mode selected

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.14
SITRAIN Training for
Automation and Drives
@
Task A system is to be automated. First, an FB called "OP_Mode" is to be created to
switch the system on and off and to select the mode. An instance of this function
block is called in the next exercise in the BackgroundTask and assigned the
actual parameters indicated in the slide above.
er

The "OP_Mode" FB provides the following functionality:


• Switching on and off: The system can be switched on with the "Start" input
(1-active) and switched off with the "Stop" input (0-active).
The system state is output in the output parameter "System_ON".
ez

After every ramp-up (mode transition "STOP" -> "START"), the state of
the system must be switched off.
• Selection of operating mode: Immediately after the system is switched on, no
mode is active. From this state, either "Manual" or "Automatic" mode can be
r.s

selected when the system is switched on.


The desired mode is first preselected by setting the "Manual_Auto" switch
("Manual": "Manual_Auto" = 0, "Automatic": "Manual_Auto" = 1). It is
activated with a pulse at the "Activate_Mode" input. The active mode is
output at the respective outputs "Mode_Manual" or "Mode_Automatic".
ne

If the "Manual_Auto" input changes state, any mode that is active is


deactivated. When the system is switched off, the selected mode is also
deactivated.
• Reusability: It must be possible to call several instances of the "OP_Mode"
ca

FB in a user program.

What to do 1. Create an ST unit called "ST_Main".


2. The "ST_Main" unit exports the "Mode" function block.
3. Implement the "Mode" FB with the required properties.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 Exercises
Exercise 3.4: Calling and testing an FB instance

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.15
SITRAIN Training for
Automation and Drives
@
Testing an In this exercise, an FB instance is to be called in the BackgroundTask and
FB instance tested. For this purpose, a small program called "OB_Main" is first created using
the LAD editor. Within this program, the FB instance is then called.
After this, the "Mode" FB can be tested.
er

What to do 1. Use the LAD editor to create a LAD/FBD unit called "LAD_Main".
2. Then add the "OB_Main" program to the "LAD_Main" unit.
ez

3. Next, establish a connection to the "ST_Main" unit in the declaration part


of the LAD/FBD unit.
4. Also, declare a program-local (VAR ... END_VAR) instance "Mode_Main"
of the "Mode" FB in the declaration part. (Why program-local? Which
requirement would be violated by a declaration in VAR_GLOBAL of the
r.s

"LAD_Main" unit?)
5. Insert a network in the LAD program and call the FB-Instance "Mode_Main".
4. Assign the actual operands listed on the previous page to the input and
output parameters of the block
ne

5. Compile the program and assign it to the BackgroundTask in the


execution system. Download the blocks to the SIMOTION target system.
6. Test the "Mode" FB. Open the ST source file called "ST_Main" and click the
corresponding button to activate the "Program status".
ca

7. Make any necessary changes in the "Mode" FB and download the


modifications to the target device in "RUN" mode.
You must first enable the "Download in RUN" function in the SCOUT
interface via the dialog: Options -> Settings -> CPU download.
After this, you can download modified programs via the context menu of the
SIMOTION device: Target system -> Download. A download in RUN is only
possible if no changes have been made in the declaration part or in the
INTERFACE part.

Solution PRG_D425-2_V431_PN_E_2.zip contains a solution for this task.


SITRAIN Training for MC-SMO-PRG
Automation and Drives Page 15 Exercises
Exercise 4.1: Creating an FB for traversing an axis

Move_Axis_A1
Move_Axis
... EN ENO

om
%I0.4 JOG_Pos

l.c
Static motion of a defined axis

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.16
SITRAIN Training for
Automation and Drives
@
Task The "Move_Axis" function block is created for position-controlled motion of an
axis. In the cyclic program "OB_Main", an instance "Move_Axis_A1" is then
called.
er

What to do 1. Insert an ST source file called "UNIT_POS". In the local settings, select
"Permit status". The function block is to be eintegrated into this unit.
2. Write the "Move_Axis" FB with the following properties:
• The FB has an input parameter camlled "JOG_Pos“
ez

• When the input parameter is eset, a _move command for one axis
(velocity: 100 mm/s) is calledi.
Since the FB is to be dessigned for a cyclic runtime environment, the
parameters at the _mov e command are first set in such a way that a call aborts
the old mo@vement and starts the new movement.
r.s

3. The FB is to be called from the higher-level program "OB_Main".


Declare a program-local inst ance "Move_Axis_A1" of the FB in "OB_Main".
The input paraumeter "JOG_Pos" of the FB instance is supplied with input%I0.4
of the simullator.
4. Since the ogld motion is always aborted by the cyclic call of the move
ne

coommand, this leads to the call of the TechnologicalfaultTask.


To plrevent the SIMOTION device from going into STOP, use the
e"FaultProgram" in the "FaultUnit" assign it to the TechnologicalfaultTask.
5. Before the axis can be started, it must be enabled. Write an MCC
program "En_Axes" that enables the two axes. Assign this program to
ca

MotionTask_2. This task is to start automatically after the StartupTask.


Alternative solution: Use the "MC_Power" FB from the PLCopen sub-library of
the SIMOTION command library. Call up two instances of that FB in the
"OB_Main" program in order to enable "Axis_1" and "Axis_2". This is described
in detail in exercise 5.1.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 Exercises
Exercise 4.2: Integrating edge evaluation into an FB

Move_Axis_A1
Move_Axis
... EN ENO

om
%I0.4 JOG_Pos

l.c
ai
Edge evaluation for the "JOG_Pos" parameter

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.17
SITRAIN Training for
Automation and Drives
@
Task The "Move_Axis" FB is to be expanded. The axis is now to be started by the
positive edge at the "JOG_Pos" input and stopped by the negative edge.

What to do 1. For edge evaluation, integrate one instance of the system FB for
er

evaluation of a positive edge (R_TRIG) and one instance for evaluation of a


negative edge (F_TRIG) into the FB.
2. The _move command is only called on a positive edge. On a negative
edge, a stop command _stop is called. The smtop command aborts both basic
ez

and superimposed motions.


r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 Exercises
Exercise 4.3: Passing the axis velocity to the FB as a parameter

Move_Axis_A1
Move_Axis
... EN ENO

om
%I0.4 JOG_Pos
Act_Velocity Velocity

l.c
ai
Passing the axis velocity

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.18
SITRAIN Training for
Automation and Drives
@
Task Make it possible to specify the velocity of the axis using another parameter.

What to do 1. In the FB, insert an additional input parameter of the LREAL data type
called "Velocity".
er

This parameter is used with the MOVE command for specifying the velocity.
2. Create a global variable called "Act_Velocity" (LREAL type) with an
initialization value of 100.0 in the INTERFACE part of "UNIT_POS". When the
FB instance is called in "OB_iMain", the "Velocity" parameter is supplied with
ez

this variable.
Since the "Act_Velocity" variable is created as a global variable, its value can
be monitored and modified with the symbol browser.
3. Test the program by changing the value of the "Act_Velocity" variable
with the symbol browser
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 Exercises
Exercise 4.4: Outputting BUSY signals at the FB

Move_Axis_A1
Move_Axis
... EN ENO ...
%Q4.4

om
%I0.4 JOG_Pos BUSY
Act_Velocity Velocity

l.c
ai
Evaluating the busy signal

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.19
SITRAIN Training for
Automation and Drives
@
Task The "Move_Axis" FB is to report back whether the axis is in motion.

What to do 1. In the FB, insert an output parameter called "BUSY_Pos" of the BOOL
data type.
er

2. Analyze the state of the axis with the motionstatedata.motionstate


system variable.
When the axis moves, the "BUSY_Pos" signal is set to TRUE.
When the axis is stationary, the "BUSY_Pos" signal is set to FALSE.
ez

3. Assign the "BUSY_Pos" output paraemeter to the %Q4.4 output at the


simulator.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 Exercises
Exercise 4.5: Passing the axis TO as an input parameter

Move_Axis_A1
Move_Axis
... EN ENO ...
%I0.4 JOG_Pos BUSY_Pos %Q4.4
Axis_1 Axis

om
Act_Velocity Velocity

Move_Axis_A2
Move_Axis

l.c
... EN ENO ...
%I0.6 JOG_Pos BUSY_Pos %Q4.6
Axis_2 Axis

ai
Act_Velocity Velocity

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.20
SITRAIN Training for
Automation and Drives
@
Task In the "Move_Axis" FB, an axis object is to be passed in an additional input
parameter called "Axis". This makes for flexibility when implementing the
selection of the required axis.
er

What to do 1. In the "Move_Axis" FB, insert an additional input parameter called


"Axis" of the posAxis TO data type.
2. Change the commands within the FB som that any axis of your project
can be passed as the input parameter.
ez

3. Change the "OB_Main" prograim so that Axis_1 can be set in motion


with input %I0.4 and Axis_2 can sbe set in motion with input %I0.6.
Simulator output %Q4.4 is to indicate whether Axis_1 is moving in the positive
direction and @output %Q4.6 is to indicate whether Axis_2 is moving in this
r.s

direction.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 Exercises
Additional exercise 4.6: Additional integration of negative direction
Move_Axis_A1
Move_Axis
... EN ENO ...
%I0.4 JOG_Pos BUSY_Pos %Q4.4
%I0.5 JOG_Neg BUSY_Neg %Q4.5

om
Axis_1 Axis
Act_Velocity Velocity

Move_Axis_A2
Move_Axis

l.c
... EN ENO ...
%I0.6 JOG_Pos BUSY_Pos %Q4.6
%I0.7 JOG_Neg BUSY_Neg %Q4.7

ai
Axis_2 Axis
Act_Velocity Velocity

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Additional negative direction with "JOG_Neg"

Date:
File:
10.01.2013
MC-SMO-PRG_10.21
SITRAIN Training for
Automation and Drives
@
Task Make it possible to select the negative travel direction with an additional input
parameter called "JOG_Neg". Moreover, the output parameter "BUSY_Pos" or
"BUSY_Neg" is to output whether the axis is in motion in a positive or negative
direction.
er

Within the FB, the following properties are also to be implemented:


• A traversing command can only be selected if no traversing command in the
other direction is active
ez

• If both JOG input parameters are set simultaneously, then a traversing


command is not issued

What to do 1. In the FB, insert an input parameter called "JOG_neg" and an output
parameter called "BUSY_Neg" of the "BOOL" data type.
r.s

2. In the declaration part, insert two new static variables "Pos_Command" and
"Neg_Command" of the BOOL data type so that traversing commands
issued in each direction can be stored.
3. Only issue a traversing command in the respective direction if:
ne

- A traversing command in the other direction is not activated at the same


time
- A traversing command in the other direction is not already active
4. Only stop the axis movement if a traversing command is active in the
direction in which a corresponding negative edge has also been detected.
ca

With the stop, also reset the variables for storing the traversing commands.
5. Then assign the corresponding TRUE values to the BUSY signals when
the axis is moving (motionstatedata.motionstate <> standstill) and
the actual velocity in the respective direction is greater than "0".

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 Exercises
Additional exercise 4.7: Integrating troubleshooting
Move_Axis_A1
Move_Axis
... EN ENO ...
%I0.4 JOG_Pos BUSY_Pos %Q4.4
%I0.5 JOG_Neg BUSY_Neg %Q4.5
%Q5.4

om
Axis_1 Axis Error
Act_Velocity Velocity CommandAborted %Q5.5

Move_Axis_A2
Move_Axis

l.c
... EN ENO ...
%I0.6 JOG_Pos BUSY_Pos %Q4.6
%I0.7 JOG_Neg BUSY_Neg %Q4.7
%Q5.6

ai
Axis_2 Axis Error
Act_Velocity Velocity CommandAborted %Q5.7

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Additional output parameters: "Error" and "CommandAborted"

Date:
File:
10.01.2013
MC-SMO-PRG_10.22
SITRAIN Training for
Automation and Drives
@
Task Up until now, no troubleshooting has been performed in the "Move_Axis" FB. An
implicit assumption has been made that the "Axis" input parameter actually
pointed to a valid axis object when the command was issued and that the
issuing of the motion command was always successful.
er

If either of the two conditions is not fulfilled, the "Error" output parameter is set to
TRUE (synchronous with the activation). The "Error" parameter is then reset
when the associated input parameter is reset.
Neither was the fact that axis motion can be stopped from elsewhere in the user
ez

program or aborted when a TO error occurs taken into account. This state can
only be detected by tracking the command status of the issued motion
command using the CommandId (asynchsronous to issuing the job).
If the motion command is abor ted "externally", then the "CommandAborted"
r.s

output parameter is set to@ TRUE. The "CommandAborted" parameter is also


reset when the associated input parameter is reset.
Step 1
1. Start by insertingu the required output parameters "Error" and
ne

"CommandAlborted" into the declaration part of the "Move_Axis" FB.


2. Then start sgynchronous error evaluation. In this case, no additional
auxiliary variableos have to be included in the declaration.
3. Befolre calling the respective _move command, check whether the
"Axis" input parameter refers to a valid TO. If it does not or if the return value is
not equal to 0, set the "Error" output parameter to TRUE.
ca

4. Also remember that you may only access system variables of an axis
TO if the axis parameter refers to a valid axis TO.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 Exercises
Additional exercise 4.7: Integrating troubleshooting
Move_Axis_A1
Move_Axis
... EN ENO ...
%I0.4 JOG_Pos BUSY_Pos %Q4.4
%I0.5 JOG_Neg BUSY_Neg %Q4.5
%Q5.1

om
Axis_1 Axis Error
Act_Velocity Velocity CommandAborted %Q5.2

Move_Axis_A2
Move_Axis

l.c
... EN ENO ...
%I0.6 JOG_Pos BUSY_Pos %Q4.6
%I0.7 JOG_Neg BUSY_Neg %Q4.7
%Q5.3

ai
Axis_2 Axis Error
Act_Velocity Velocity CommandAborted %Q5.4

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Additional output parameters: "Error" and "CommandAborted"

Date:
File:
10.01.2013
MC-SMO-PRG_10.23
SITRAIN Training for
Automation and Drives
@
Step 2 In the next step, integrate asynchronous error evaluation.
1. Create a global variable of the commandidtype type.
2. Assign a CommandId to this variable (with _getcommandid()).
er

3. Issue the _bufferaxiscommandid() command to buffer the variable.


3. Assign this ID to the _move command.
4. The _getstateofaxiscommand() command can be issued to evaluate
the state of the axis command even after command execution has been
ez

completed.
Create a further global variabsile of the structretcommandstate type that is
used as the return value of the structretcommandstate function.
Call the _getstateofaxiscommand function and evaluate the return value
r.s

accordingly.
Following evalua tion and completion of the command, issue
_removebufferuedaxiscommandid)= to delete the buffered CommandId.
5. Download andl test the program. Pay particular attention to the
"Error" and g"CommandAborted" outputs.
ne

Solution PRG_D425-2_V431_PN_E_2.zip contains a solution for this task and the


previous tasks.
l
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 Exercises
Exercise 5.1: Integrating PLCopen blocks into OB_Main

VAR

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.24
SITRAIN Training for
Automation and Drives
@
Task In this exercise, PLCopen blocks from the command library are to be integrated
into the project. Along with the block for mode selection, the blocks for enabling
the axes, for JOG mode, and for resetting the axes (i.e. axis error
acknowledgment) are integrated in the "OB-Main" LAD program.
er

The enables for the axes are only to be set if either "Manual" or "Automatic"
operation is selected. Traversing of the axes using the appropriate direction
pushbuttons is only possible if "Manual" mode is selected. The axis can be reset
regardless of the selected operating mode and system state.
ez

What to do 1. In the "OB_Main" program, delete the declaration of the instances and the
calls of the "Move_Axis" FB so that only the declaration of the instance and
the call of the "Mode" FB remain.
r.s

2. Open the command library and drag the "_mc_power" function block
(enable axes) from the command library to the "OB_Main" program.
If necessary, select the command: Display -> All parameters from the
context menu of the LAD/FBD editor to display all parameters of the block.
3. Then enter the name "Enable_Axis_1" as the name of the instance for the
ne

first call of the "MC_Power" block. The dialog box for declaring variables
opens.
4. Make sure that the instance is created as a variable type VAR, i.e. as a
program-local instance (why?) and confirm the dialog with "OK".
The instance is entered in the declaration part of OB_Main.
ca

5. Assign the associated actual parameters to the input parameter of the FB


call. In particular, select the following entries for "mode" and "stopmode":
- mode := ALL
- stopmode := WITH_MAXIMAL_DECELERATION

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 Exercises
Exercise 5.2: Integrating enables, JOG blocks, and reset blocks

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.25
SITRAIN Training for
Automation and Drives
@
Continued 6. Insert the corresponding logic for the enable input so that the axis is only
enabled if automatic or manual mode is active.
7. Insert another instance of "_mc_power" to enable Axis_2.
er

8. Insert two instances of the "_mc_jog" FB called "Jog_Axis_1", "Jog_Axis_2"


and two instances of the "_mc_reset" FB called "Reset_Axis_1",
"Reset_Axis_2".
9. Interconnect the inputs and outputs with the corresponding input and output
ez

signals at the simulator. The "Axis_<n>_error" output is only to be set


to "1" if the Axis_<n>.Error system variable signals an error.
Using the Jog pushbuttons to set the axes in motion is only permitted if
"Mode_Manual" mode is active. Select a velocity of 20 mm/s for Jog mode
and explicitly assign the value "-1.0" to the "acceleration" input parameter.
r.s

The activation of an axis reset and thus the acknowledgment of an axis


error is always possible, regardless of the operating mode and the system
state.
10. Integrate the appropriate statements to set the %Q4.3 variable according to
the "Status" outputs of both FBs for enabling the axes.
ne

11. IF used, delete the "En_axes" program from the task configuration.
12. Compile, download, and test your user program. For test purposes,
the output parameters of the FBs should be assigned "dummy" variables.
ca

Solution PRG_D425-2_V431_PN_E_3.zip contains a solution for this task.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 25 Exercises
Exercise 6: On-the-fly machining

Technical data:
Speed of the belt: 0 - 200 mm/s
Cut-off length: Acquired by sensor

om
Initial
Sensor position Synchronous

100 mm 100 mm
Axis_1

l.c
ai
Axis_2
0.0 mm 100 mm 200 mm

SIMATIC S7
Siemens AG 2013. All rights reserved.
Date:
File:
gm 10.01.2013
MC-SMO-PRG_10.26
SITRAIN Training for
Automation and Drives
@
Task The material (e.g. sheet metal) driven by the feed (Axis_2) must be cut on-the-
fly at the synchronization marks. The synchronization mark sensor detects the
cut-off point on the product and must synchronize the shear with this position
(on-the-fly actual-value setting).
er

The sensor is simulated via input PI 1.3.


The velocity of Axis_2 can be varied during operation by means of the velocity
override function.
ez

The following sequence of operations must be programmed to perform this task:


1. When automatic mode commences, if absolute encoder adjustment has not
previously been executed, Axis_1 must be homed by issuing the "Home axis
- Set actual value to 100" command.
2. The shear is moved to its initial position (position = 100 mm, velocity
r.s

400 mm/s). The shear (linear axis) waits in this position until the sensor
detects the synchronization mark.
3. The material feed (Axis_2) is then activated. It transports the bar material
into the working range of the shear at a velocity of 200 mm/s.
ne

4 When a synchronization mark is detected, synchronization of Axis_1 (shear)


begins. Axis_1 (shear) must be synchronized with the synchronization mark
on the material when position 200 mm is reached.
5. Once the shear has been synchronized with the cut-off point, the cutting
process is initiated via the "cut-off" output. This output dwells at "1" for
ca

3 seconds, by which time the material has been cut off.


The "cut-off" output is controlled by "Output_Cam_1" of Axis_1.
6. Once the material has been cut, Axis_1 returns to its initial position and waits
for the next synchronization mark.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 26 Exercises
Exercise 6.1: Creating a function to start and stop tasks

Function "TaskStartStop" TaskStartStop


Start Out
Stop

om
TaskId

l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.27
SITRAIN Training for
Automation and Drives
@
Task In the first part of this exercise, we are going to create the "TaskStartStop"
auxiliary function for traversing axes in automatic mode. Once we have created
the function, we will call it in OB_Main and start/stop MotionTask_3.
The "TaskStartStop" function is implemented in the "ST_Main" unit.
er

"TaskStartStop" The "TaskStartStop" function has the following properties:


• The "TaskStartStop" has the two optional input parameters "Start" (BOOL)
ez

and "Stop" (BOOL) as well as the mandatory parameter TaskId


(StructTaskId). "Start" and "Stop" are preset to "FALSE".
The function's return value (BOOL) contains information about the current
task state.
• If the "Start" input parameter is set to "1" and "Stop" is set to "0", and the
r.s

selected task is not already in state TASK_STATE_RUNNING, it is started


via _restartTaskId().
• If the "Stop" input parameter is set to "1" and "Start" is set to any value, and
the selected task is in state TASK_STATE_RUNNING, it is stopped via
_resetTaskId() .
ne

• In all cases, i.e. regardless of "Start" and "Stop", the function's return
value (BOOL) contains information about TASK_STATE_RUNNING.
The return value of the function is TRUE if the return value of
_getStateOfTaskId() contains the part TASK_STATE_RUNNING; otherwise
ca

it is FALSE

What to do Create the "TaskStartStop" function in the "ST_Main" unit with the required
properties.

Solution You will find the solution in the project: PRG_D425-2_V431_PN_E_4.zip.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 27 Exercises
Exercise 6.2: Creating an ErrorHandler for the TechFaultTask

"ErrorHandlerTechFault" program

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.28
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to create a simple ErrorHandler for the
TechnologicalFaultTask. The ErrorHandler will acknowledge alarms relating to
axes, i.e. alarms that do not represent errors from the programmer's point of
view (e.g. alarm 30002). In this case, an alarm message frame is not sent to
er

OCM devices and the axis TO does not switch to the error state (<TO>.error =
yes). The ErrorHandler evaluates the "TaskStartInfo" to identify the TO
triggering the alarm and the error number.
In the following exercises, we are going to add more alarm numbers and TOs
ez

(synchronous operation TO) to the acknowledgment mechanism.

What to do 1. Create an ST unit called "ErrorHnd" with the "ErrorHandlerTechFault"


program. In the INTERFACE part, make sure that the necessary technology
packages are imported and the program is exported for the assignment in
r.s

the execution system.


3. Declare the local variable "MyDriveAxis" ("driveAxis" data type) and a
"MyRetDInt" variable (DINT type) to accept return values. The "MyDriveAxis"
variable is then used to address the TO when acknowledging the axis error
with the system function _resetAxisError(axis = MyDriveAxis,...).
ne

4. Next, in the TaskStartInfo, evaluate the information about the TO triggering


the alarm. Use the ANYOBJECT_TO_OBJECT function to copy the
TS#toInst entry to the "MyDriveAxis" variable.
5. Then check whether the conversion was successful. If it was, acknowledge
ca

alarm 30002 in a CASE query by evaluating the entry TSI#alarmNumber


from the TaskStartInfo at the start of the CASE statement.
6. Following creation, replace the original program for the
TechnologicalFaultTask in the execution system with the new program. Then
download the project to the target system and test it.

Solution You will find the solution in the project: PRG_D425-2_V431_PN_E_4.zip.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 28 Exercises
Exercise 6.3: Program concept for a "flying shear"

LAD/FBD: Operating mode, JOG, Reset


Background Motion Task 3
LAD/FBD (RunAuto)
Automatic mode

om
Motion Task 4
User Interrupt LAD/FBD (Cutting)
Synchronous operation

l.c
"Automatic" mode
Move to "start position"
Axis_1

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
Axis_2

gm
Date:
File:
Endless motion

10.01.2013
MC-SMO-PRG_10.29
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to integrate the function call of "TaskStartStop"
into OB_Main. The associated program part in OB_Main evaluates the state of
the variable "Mode_Auto" and starts or stops the related MotionTask_3.
. When MotionTask_3 is stopped, possible traversing movements invoked from
er

MotionTask_3 must also be stopped. This is achieved with two instances of the
PLCopen block "_mc_stop".

What to do 1. The "TaskStartStop" function switches MotionTask_3 to the


ez

TS_RUNNING state if "Mode_Auto" mode is selected.


Deselecting "Mode_Auto" mode will stop MotionTask_3. Also display the state of
MotionTask_3 in % Q5.2 (TRUE: MotionTask_3 is running, FALSE:
MotionTask_3 is stopped).
r.s

2. Stopping MotionTask_3@will not stop possible movements of the two


axes. For this purpose, in tegrate two instances ("Stop_Axis_1" and
"Stop_Axis_2") of the PLCopen block "_mc_stop" into the cyclic program
"OB_main".
With a descending edge of the signal "mode_main.auto_,mode", the two
ne

instances of the "_mc_stop" FB should be called for both axes.


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 29 Exercises
Exercise 6.4: Basic motion of the axes in automatic mode

om
Move Axis_1 to
start position

l.c
Start and stop
Axis_2

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.30
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to create the MCC program for MotionTask_3.
This program moves Axis_1 (shear) to its start position in automatic mode and
then starts the belt running for Axis_2 (material feed).
er

What to do 1. Create an MCC unit called "MCC_Auto".


2. Add an MCC program "RunAuto" to mthe MCC unit. The following
actions are carried out in the "RunAuto" program.
- Move Axis_1 to the "100" poseition at a velocity of 400 mm/s
ez

- Position-controlled endlesssi movement of Axis_2 at variable velocity


- For this purpose, create the interface variable
"Velocity_Axis_2" (LREAL data type) with an initial value of 100 mm/s in the
MCC unit called
r.s

"MCC_Auto" and @assign these variables to the velocity parameter of the MCC
command "Start axis position-controlled"
- The input siugnal %I1.2 (toggle) can be used to stop and restart the belt
movelment of Axis_2 in automatic mode.
2. Compile gthe program called "RunAuto" and assign it to MotionTask_3
ne

in the executioon system. MotionTask_3 is not started automatically after the


StarltupTask.
3. Deownload and test the user program.
ca

Solution You will find the solution in: PRG_D425-2_V431_PN_E_4.zip.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 30 Exercises
Exercise 7: Implementing synchronous operation of both axes
Axis_1
gearing off
850 mm

position axis
gearing on

om
100 mm
0 mm 200 mm 850 950 Synchronization mark

l.c
Initial
Sensor position Synchronous

100 mm 100 mm
Axis_1

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
Axis_2 gm
0 mm

Date:
File:
100 mm

10.01.2013
MC-SMO-PRG_10.31
200 mm

SITRAIN Training for


Automation and Drives
@
Machine sequence When automatic mode is activated, the shear is moved to the start position 100 and
the belt starts to move so that material can be fed in.
When a synchronization mark reaches the sensor (PI 1.3), the shear is to be
synchronized as gently as possible from the point of view of the machine, i.e.
er

smoothly without an overshoot in velocity. From position 200 mm onwards, the


shear is to move in synchronism with the mark on the bar material. Synchronization
and the cutting process should run without errors even if the velocity of the material
(Axis_2) changes during active operation.
ez

These conditions can only be achieved with a leading time-related synchronization


strategy with "adjustment of dynamic response values".

Synchronize For this strategy, you must start by entering the following settings in the "Settings"
r.s

dialog for the synchronous object:


• "Adjustment of the dynamic response values during synchronization": Activate
• "Override factor for dynamic response values": 100.001%
• "Permissible change in velocity":= 20%
ne

The following settings must then be made in the synchronous operation command:
• Reference point: "Gearing takes place relative to axis zero"
• Synchronization reference: "Time"
• Start of synchronization: "At leading axis position"
ca

• Reference point of the leading axis position: "Synchronize before leading axis
position"
• Leading axis position: "200 mm"
• Synchronization direction: "Positive"
• Velocity profile: "Smooth"
• Velocity: "Some value < = 10 mm/s"
• Acceleration: "500 mm/s2"
• Jerk: "2,000 mm/s3"

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 31 Exercises
Exercise 7: Synchronization profile of the "flying shear"

Start of Axes
synchronization synchronized

om
l.c
ai
"Shear" velocity

SIMATIC S7
"Shear" position

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
Position of the
"material feed"

MC-SMO-PRG_10.32
SITRAIN Training for
Automation and Drives
@
Desynchronization The axes traverse the next 650 mm in synchronism and the actual cutting
process can take place.
When position 850 mm is reached, the shear is desynchronized. After the shear
has stopped, it returns to its start position at a velocity of 400 mm/s and waits for
er

the next synchronization mark.


A leading-axis-specific desynchronization profile with the following settings must
be selected for the desynchronization process:
m
ez

• Synchronization reference: "Leadeing axis"


• Desynchronization position: "Wiith following axis value"
• Reference point of desynchrsonization position: "Stop from
desynchronization position"
• Desynchronization leng@th: "100 mm"
r.s

• Following axis pos ition: "850 mm"


• Synchronization duirection: "Positive"

When a new sgynchronization mark is detected, the whole cycle begins


ne

New cycle
again if the previous cutting process has completely finished. Otherwise, an
error message is looutput.
Tkhe actual cycle for synchronization and desynchronization is implemented
in the "Cutting" program (MotionTask_4). Detection of the synchronization
Program and mark, evaluation of whether the previous cycle has finished, the setting of the
actual value for the material feed, and the start of MotionTask_4 are all
ca

task assignment implemented in the "GearOn" program (UserInterruptTask_1).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 32 Exercises
Exercise 7.1: Creating a program for the "flying shear"

StartGearing

om
Cutting

l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.33
SITRAIN Training for
Automation and Drives
@
What to do 1. Create the "StartGearing" program in the "LAD_Auto" unit to start the
synchronization process.
2. Next, use the "TaskStartStop" function to check whether MotionTask_4,
i.e. the task for the cutting process, is still active.
er

3. If MotionTask_4 is not active, set the actual value system of Axis_2 to the
value 0.0 and then start MotionTask_4. In the _redefinePosition() command,
make sure that "WHEN_COMMAND_mDONE" has been selected for the step
enabling condition "nextCommand".
However, if MotionTask_4 is acetive, the call _alarmSQId() is used to issue an
ez

Alarm_S message requiring siacknowledgment.


The relevant block for send ing the Alarm_S message must be called twice in this
instance as the UserInterruptTask is executed only once. The first call generates
an "incom@ing" message, the second an "outgoing" message (see the following
slides).
r.s

4. Assign this proguram to UserInterruptTask_1. Specify the response of


sensor PI1.3 (symbollically) as the start condition. Integrate the symbol "Sensor"
with PI1.3 into the address list.
5. Create an MCC program called "Cutting" in the MCC unit called
"MCC_Auto". Implement the actual synchronization process and the return of the
ne

shear to the start position in this program.


The time-related synchronization profile is used for synchronization.
The leading-axis-related profile is used for desynchronization.
The shear must then return to its start position 0 mm at a velocity of 400 mm/s.
6. Assign the "Cutting" program to MotionTask_4. MotionTask_4 is not
ca

started automatically after the StartupTask.


7. Download and test your user program and use the Trace function to trace
the relevant data, i.e. the positions and velocities of the two axes.

Solution You will find the solution in: PRG_D425-2_V431_PN_E_5.zip.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 33 Exercises
Exercise 7.2: Alarm_S and diagnostics buffer entries

Alarm_S Diagnostics buffer entries

om
l.c
Messages -> Configure

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.34
SITRAIN Training for
Automation and Drives
@
Message Messages are mainly used to display machine errors/machine states or
configuration unexpected control/user program states on HMI systems. SIMOTION supports
both these options by means of the following two message procedures:
• Alarm_S message procedure (machine error/states)
er

• Diagnostics buffer entries (user program errors and/or states)

Alarm_S Alarm_S is a more recent procedure for configuring and displaying message
ez

texts on OCM devices. The specific advantages of the Alarm_S message


procedure as compared to older systems (bit messaging) are as follows:
• Alarm_S messages are generated by the SIMOTION device and sent
to the logged-on OCM equipment with a corresponding time stamp. Even
after a message "flood", therefore, the order in which individual messages
r.s

were generated is clearly identifiable (initial and subsequent messages).


• Alarm_S messages can be assigned to a display class (0 ...15). As a result,
settings can be made on individual networked OCM units (local device or
control room) to determine which messages (display classes) must be
displayed and which can be ignored.
ne

• The complete message text configuration, including foreign-language


translations, is integrated in SIMOTION Scout rather than in the configuration
of individual OCM devices. Therefore, a text for a specific event only has to
be output once. When OCM devices are configured, texts are simply
transferred from the SIMOTION database.
ca

Diagnostics In exactly the same way as the operating system, the user is able to enter
buffer entries messages in the diagnostics buffer of a SIMOTION device. Messages stored in
the SIMOTION device diagnostics buffer (which can hold up to 100 entries) can
be used subsequently by experts for troubleshooting. The messages can also
be sent to other OCM equipment on the network.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 34 Exercises
Exercise 7.2: Configuring an Alarm_S message

Symbol (helps to identify message when called)

om
l.c
New message

ai
Fault message (must be acknowledged)

Operating message (does not have to be acknowledged)

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.35
SITRAIN Training for
Automation and Drives
@
Configuring a You can open the window for configuring an Alarm_S message by selecting:
new message Target system -> Configure messages.
• If the "Alarm_S" option is activated, the screen will display an overview of all
configured Alarm_S messages
er

• If diagnostics buffer entries are activated, the screen will display an


overview of all diagnostics buffer messages configured by the user
When the "Alarm_S" option is activated, you can open the dialog for configuring
ez

a new message via the "New" button. The following entries are mandatory in this
dialog:
Symbol Under "Symbol", enter the name of the new message which is to be created.
Permitted characters A-Z, a-z, 0-9, underscore (_). The first character must not
be a digit; multiple underscores must not be placed one after the other.
r.s

No. Enter the number of the created message here or accept the number suggested
automatically. The number must be unique for the configured message.
Message text Under "Message text", enter the text which should be displayed when the
message is called. It is displayed in the detail view on the Alarms tab or on the
HMI device.
ne

Infotext Under "Infotext", enter comments for the message. This text is displayed as help
text when the message occurs.
Message type Under "Message type", select a type for the configured message. Fault
messages and operating messages are acknowledged in different ways on the
ca

display device.
Display class Select a "display class" between 0 and 15. The display class is required if a
definite choice of specific messages is requested for an operator panel during
the configuration of the display (e.g. ProTool).
Printout (at OP) Check this box if you want the incoming message to be forwarded to and
displayed on the HMI equipment. This setting is irrelevant for SIMOTION
SCOUT.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 35 Exercises
Exercise 7.2: Sending Alarm_S messages in the user program

Incoming message
Meaning of the input
parameter "sig":
Outgoing message

_alarmSId

om
Message does EN ENO
not require BOOL sig OUT DWORD
acknowledgment StructAlarmdD ev_id
ANY_NUM sd

l.c
Interconnection of input
e.g.: _alarm.cutting_active
parameter "ev_id":

_alarmSQId

ai
Message requires EN ENO
acknowledgment BOOL sig OUT DWORD

SIMATIC S7
Siemens AG 2013. All rights reserved.
StructAlarmdD
ANY_NUM
gm
Date:
File:
ev_id
sd

10.01.2013
MC-SMO-PRG_10.36
SITRAIN Training for
Automation and Drives
@
Sending You can send freely configured messages to and/or check the status
messages of logged-on display devices. Specifically, you can:
• Send a message that does not require acknowledgment (alarmS, alarmSId)
er

• Send a message that does require acknowledgment (alarmSQ, alarmSQId)


• Check the state of a message and its acknowledgment
(alarmSC, alrmSCId)
Two functions (e.g. alarmS, alarmSId) are available for each of these tasks.
ez

These differ according to the method of identification selected for the message:
• The message is specified by means of a unique AlarmId (e.g. alarmSId).
These functions are available with version V3.1 or later of the SIMOTION
Kernel and can also be used in libraries and in LAD/FBD programs
(like the system functions for task handling).
r.s

You can obtain the AlarmId for a configured message name in the following
way: alarm.name, where name is the message identifier configured in
SIMOTION SCOUT under the "Symbol entry".
• The message is identified by its "Symbol" (e.g. alarmS). These functions
ne

are available in all versions of the SIMOTION Kernel, but can only be used in
ST. They cannot be used in LAD/FBD programs or in libraries.
The message is identified by its "symbol" at input "Al_Name".

Input parameter If the signal has a positive edge in relation to the last call with this message ID,
ca

Sig (BOOL) an incoming message is generated. An incoming message is also generated if


the signal state is TRUE on the first call with this message name.
If the signal represents a negative edge in relation to the last call with this
message ID, an outgoing message is generated.

Sd (ANY_NUM) Auxiliary value: Elementary data type variables are permitted.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 36 Exercises
Exercise 7.3: Using output cams to implement cutting

"Output cam"

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.37
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to implement the actual cutting process, i.e.
control the shear, using an output cam output. For this purpose, we are going to
set up a time-based output cam for the axis "Axis_1".
Once "Axis_1" has synchronized with the synchronization mark, the cutting
er

process will be initiated via an output cam. It will commence at position 200 mm
and take 5 seconds to complete.
On the D425-2, the output cam is set up as a fast output cam of the bidirectional
inputs/outputs at the connector X142 of the D425-2. The cutting process is also
ez

to be indicated via the "Cutting_active" LED (%Q5.3) on the simulator.

Procedure 1. Open the screen form with the parameterization of the bidirectional
inputs/outputs at the connector X142 of the D425-2.
r.s

2. Select the "Channel 0 – 7" tab, and parameterize the DI/DO3 as "output
cam".
3. Below the axis "Axis_1" in the folder "Cams", insert a output cam TO with
the name "Cutter".
ne

4. Open the configuration dialog by double-clicking on the entry: "Cutter ->


Configuration".
5. Parameterize the cam as "Time cam", and select the option "Activate output"
with the cam output option: "Cam output (CAM) ".
6. Using the parameterizing dialog for assigning the output, select the entry
ca

"D425-2 -> CAM_3 [INOUT 3, X142.7]".


Via this assignment, the cam output is connected to the DO9 of the
SINAMICS operator panel.

Solution You will find the solution in: PRG_D425-2_V431_PN_E_6.zip.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 37 Exercises
Exercise 8.1: Creating a cam with the VDI wizard

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.38
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to create a cam (Name: Cutting) with the help of
the VDI wizard in the "CamEdit" tool. This cam will then be used to provide an
alternative gearing solution for synchronizing the following axis (Axis_1) with the
leading axis (Axis_2).
er

The cam consists of the following three segments:


Segment 1 : The following axis "Axis_1" accelerates from the 100 mm position
(dwell) to constant velocity (45° straight line). The constant velocity is reached at
the 200 mm leading axis position. The synchronization length, i.e. the distance
ez

travelled by the leading axis, is 200 mm.


This motion section describes the synchronization of the following axis "Axis_1"
with the leading axis "Axis_2".
Segment 2 : Axis_1 moves in synchronism with "Axis_2". This corresponds to a
r.s

section at constant velocity. It starts at the 200 mm position and finishes at 850
mm.
This motion section describes the synchronous motion of the following axis
"Filler" in relation to the leading axis "Conveyor belt" and it is during this section
that the actual cutting operation takes place.
ne

Segment 3 : The axis moves at constant velocity back to the initial position. The
initial position should be reached at the 1500 mm position of the leading axis.
Essentially, this motion describes desynchronization and ramp-down.
ca

What to do 1. First, use CamEdit to create a cam.


2. Select the "Polynomial" type in the dialog that opens.
3. Click the "VDI Wizard" button to open the VDI wizard.
4. Create the three segments:
- Segment 1: Dwell to constant velocity
- Segment 2: Constant velocity
- Segment 3: Constant velocity to dwell

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 38 Exercises
Exercise 8.2: Creating a function for the dynamic creation of cams

FC: Create_Cam

Interpolation points ARRAY[..]

om
OF InterpolationPoint
IPO_Type
enumcaminterpolationmode
Cam_TYPE enumcammode

Cam

l.c
CamType

ai
TYPE Interpolation point : STRUCT
X_pos : LREAL;
Y_pos : LREAL;
END_STRUCT;

SIMATIC S7
END_TYPE

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.39
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to create a function called "Create_Cam" for the
dynamic creation of a cam based on interpolation points. The function creates a
cam in the definition range 0 to 100. The cam is then read out of the target
device and displayed with the help of CamEdit.
er

What to do 1. In CamEdit, first create an "empty" cam called "MyCam" and download it to
the target device.
2. Create an ST unit called "Cam_Unit". "Cam_Unit" exports the data type
ez

"InterpolationPoint" and the function "Create_Cam".


3. Create an FC called "Create_Cam". Declare the following parameters in the
FC's declaration part.
Input parameters:
r.s

- Cam: CamType. The cam is passed here.


- - IPO_Type:enumcaminterpolationmode The interpolation type for the
cam is specified here. It is used to control the interpolation type (C spline,
B spline, linear) for the cam.
ne

- Cam_Type: enumcammode. The behavior at the limits (non-cyclic, cyclic


absolute, cyclic relative) of the cam can be controlled with this parameter.
In-out parameters:
- Interpolation points: ARRAY{ ..] OF InterpolationPoint. This parameter is
used to pass an array with any number of interpolation points to the
ca

function.
4. Next, reset the cam in the statement part of the function. Then create a loop
with the corresponding passes. In each pass, another interpolation point from
the array passed is added to the cam. At the end, interpolate the completed
cam. The function is to work exclusively in the "Actual" coordinate system.
The definition range (master range) is fixed from 0 to 100.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 39 Exercises
Exercise 8.3: Testing the "Create_Cam" function

Parameters/Variables
MotionTask_5

om
Interpolation FC: Create_Cam
Detail window _Point
ARRAY[0..9]
IPO_Type OF InterpolationPoint
enumcaminterpolationmode
CAM_TYPE

l.c
enumcammode
Act_Cam
CamType

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.40
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to test the function called "Create_Cam". The test
is carried out using a small MMC program called "Test_Cam" (MotionTask_5) in
the "Test" unit.
er

What to do 1. Use the MCC editor to create a program called "Test_Cam" in the unit
called "Test".
2. Next, establish a connection to the "Cam_Unit" unit in the "Test" unit.
For the actual parameters of the FC call, also declare the following global
ez

variables in the "Test" unit:


- MyInterpolationPoints: dasta type: InterpolationPoint, array length 10
- MyIPO_Type: data type : enumcaminterpolationmode
- MyCam_Type: data @type: enumcammode
3. Program the statement part of the MCC Chart. Then, in the "Test_Cam"
r.s

program, add an end less While loop followed by "Wait for signal (%I1.7)
condition".
4. Then call thel "Create_Cam" FC. Assign the associated variables from
the "Test" unit gto the parameters of the FC. The "MyCam"cam is assigned to
the Cam input oparameter.
5. Clonfigure the execution system. Assign the "Test_Cam" program to
ne

MotionTask_5. MotionTask_5 is to start automatically after the StartupTask.


Then switch to online mode and download your project to the target device.
6. Use the "Control" function in the detail window of the symbol browser to
specify appropriate values for the variables (MyInterpolationPoints,
MyIPO_Type, MyCam_Type) declared in the unit called "Test".
ca

7. Start the FC call via the input %I1.7.


8. Use "CamEdit" to read out the "MyCam" cam you have created from the
controller and display the result on the PG.

Solution You will find the solution in: PRG_D425-2_V431_PN_E_7.zip.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 40 Exercises
Exercise 9.1: Flying shear with cam

Cut2

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.41
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to replace the existing program "Cutting" for the
synchronization of both axes and the cutting process with another program
"Cut_2". This program utilizes the cam created in exercise 8.1.
er

What to do 1. Create a program called "Cut_2" in the unit called "MCC_Auto". In this
program, both "synchronization" and the return of the shear to its start
position are implemented with camming.
Start the synchronization process with a leading-axis-related synchronization
ez

profile. Select the following parameter settings:


• Evaluation of the leading axis: "Absolute"
• Evaluation of the following axis: "Absolute"
• Cam processing: "Non-cyclic"
r.s

• Synchronization reference: "Leading axis"


• Start of synchronization: "Synchronize immediately"
• Synchronization length: "5 mm"
ne

• Synchronization direction: "Positive"


Remember that program execution and thus the task state of MotionTask_4
must be delayed until Axis_1 has returned to its start position.
2. For this reason, insert another "Wait for condition" command which uses the
"Axis_1_Synch.Oper.state" variable to evaluate the end ofthe synchronous
ca

operation relationship and thus the end of axis motion.


Without this condition, MotionTask_4 would be terminated even though the
cutting process was still active. As a consequence, another cutting operation
could be started via the "StartGearing" program even though the previous
cutting operation was not finished.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 41 Exercises
Exercise 9.1: Traversing and velocity profile of the shear

Start of Shear synchronized with


synchronization cam

om
"Shear" velocity

l.c
ai
SIMATIC S7
"Shear" position

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
Position of the
"material feed"

MC-SMO-PRG_10.42
"Shear" position

SITRAIN Training for


Automation and Drives
@
3. Delete the "Cutting" program from the assignment to MotionTask_4
and assign the "Cut_2" program in its place. MotionTask_4 is not started
automatically after the StartupTask.
4. Download and test your user program. Use the Trace function to trace the
er

relevant data (positions, velocities, etc.) of the two axes.


You will find the solution in PRG_D425-2_Vm431_PN_E_7.zip.
Solution
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 42 Exercises
Exercise A.1: UDP communication between two D425-2 stations

Receiver
Sender
IP addr.: 192.168.2.2
IP addr.: 192.168.2.1

SINAMICS

SINAMICS
Subnet: 255.255.255.0

270O
0O
Subnet: 255.255.255.0

90O

om
Port: 2222
Port: 2222 180O
0O

270O

SINAMICS

SINAMICS
90O

270O
0O

90O
180O

180O
0O

270O
90O
SMC
180O

l.c
SMC

ai
cyclic

SIMATIC S7
Siemens AG 2013. All rights reserved.
16
Bytes

Date:
File:
gm
Axis_1.positioningstate.commandposition
Axis_1.motionstatedata.commandvelocity

10.01.2013
MC-SMO-PRG_10.43
SITRAIN Training for
Automation and Drives
@
Objective In the following exercise, we are going to establish UDP communication
between two D425-2 devices. For this purpose, two neighboring training stations
are connected via an additional Ethernet cable (see slide).
The sender station sends status information about its own Axis_1 (position,
er

velocity) cyclically to the second station. The partner station receives the data
and displays the information in user variables.
One group creates a user function UDP_Send() in which the two system
variables "Axis_1.postioningstate.commandposition" and
ez

"Axis_1.motionstatedata.commandvelocity" are packed into a array of 16 bytes


and sent to the receiver station with the system function _udpSend(..).
After this, the UDP_Send() function is called in the "OB_Send" program, which
is started cyclically by the sender station's TimerinteruptTask_1.
r.s

The second group creates the corresponding receive function. For this purpose,
the user function UDP_Receive() is created. It receives data with the system
function _udpreceive() and unpacks the information into two user variables.
This function is also called cyclically by the receiver station's
TimerinterruptTask_2 in another program, "OB_Receive".
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 43 Exercises
Exercise A.1: Setting the IP address of the receiver station
5. Download

1. Double-click

om
2. Properties

3. Enter IP address
192.168.2.2

l.c
ai
SIMATIC S7
4. Confirm with "OK"

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.44
SITRAIN Training for
Automation and Drives
@
What to do Before the two stations are connected by an Ethernet cable, in the receiver
station, the IP address setting of the PNxIE-NET interface must be changed
from the default address 192.168.2.1 to the new address 192.168.2.2 Proceed
as follows:
er

1. Double-click the D425-2 symbol in the SCOUT project window to open the
HW Config tool and double-click the PNxIE-NET entry in the D425-2 station.
The properties dialog for the Ethernet interface PNxIE-NET opens.
ez

2. Click "Properties". Another properties dialog for parameterizing the


PNxIE-NET interface opens.
3. Enter the address: 192.168.2.2 in the "IP address" input field. Leave the
entry for the subnet mask set to the value 255.255.255.0.
4. Click "OK" in each of the properties dialogs to confirm your entries.
r.s

5. Save your entries and download the new settings to the receiver station by
clicking the Download button on the HW Config toolbar.
6. Once the D425-2 station has restarted, check the new IP address using the
online function: Target device -> Device Diagnostics.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 44 Exercises
Exercise A.1: Creating the user function UDP_Send()
INTERFACE
USEPACKAGE CAM;
VAR_GLOBAL
myRetDINT: DINT; //Return value for sending
DataSend : ARRAY[0..15] OF BYTE; //Send buffer
ReceiverAddress : ARRAY[0..3] OF USINT := [192,168,214,2]; //Address of receiver
END_VAR
FUNCTION UDP_Send;

om
END_INTERFACE

IMPLEMENTATION
FUNCTION UDP_Send : VOID
DataSend := ANYTYPE_TO_LITTLEBYTEARRAY(
anydata := Axis_1.positioningstate.commandposition,
offset:=0);

l.c
DataSend := ANYTYPE_TO_LITTLEBYTEARRAY(
anydata := Axis_1.motionstatedata.commandvelocity,
offset:=8);
myRetDINT := _udpSend(sourceport := 2222,
destinationaddress := ReceiverAddress,

ai
destinationport := 2222,
communicationmode := DO_NOT_CLOSE_ON_EXIT,
datalength := 16,
data := DataSend);
END_FUNCTION
END_IMPLEMENTATION

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.45
SITRAIN Training for
Automation and Drives
@
What to do In the sender station, data transmission is implemented with a simple user
function called "UDP_Send". Following data transmission, this function is called
in the LAD program "OB_Send". The OB_Send program is assigned to
TimerinterruptTask_1.
er

1. In your project, create an ST unit called "ST_Send".


2. Import the "CAM_ext" package into the INTERFACE part. The "CAM" or
"CAM_ext" package is necessary to access the system variables of the axis
TO "Axis_1".
ez

3. In the INTERFACE part, declare a "myRetDINT" variable to store the return


value of the system function _udpSend(), a "RemoteAddress" variable of
type: ARRAY[0..3] OF USINT to store the receiver's IP address, and the
"DataSend" send buffer of type ARRAY[0..15] OF BYTE.
r.s

The variables should be declared as global variables to make it easier to


monitor content subsequently via the symbol browser in the event of an
error.
4. In addition, publish the user function "UDP_send()" in the INTERFACE
part of the user function. It is called later from the "LAD_Main" unit.
ne

5. Implement the user function "UDP_Send()" in the IMPLEMENTATION part


without parameters or a return value.
6. Next, use the the ANYTYPE_TO_LITTLEBYTEARRAY() function to pack the
"position" and the "velocity" of Axis_1 in the send buffer.
ca

In this case, the function ANYTYPE_TO_BIGBYTEARRAY could also be


used. The only requirement is to ensure that the appropriate function is used
to unpack the data on the receiver side.
7. Use the system function _udpSend() to send the the send buffer. Use port
number 2222 for both the local and the remote port. Specify the value
DO_NOT_CLOSE_ON_EXIT for the communicationmode parameter.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 45 Exercises
Exercise A.1: Calling the UDP_Send() function in OB_Send

OB_Send Execution system

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.46
SITRAIN Training for
Automation and Drives
@
What to do In the last step, the function created is called in a separate LAD program,
"OB_Send". This LAD program is then assigned to TimerinterruptTask_1 in the
execution system. TimerinteruptTask_1 is called every 24 ms.
1. In the "LAD_Main" unit, establish a connection to the ST unit called
er

"ST_Send".
2. In the "LAD_Main" unit, create a program caelled "OB_Send".
3. In the first network, call the user function "UDP_Send". Also, link
the EN input of the function to the simulator input signal %I1.5.
ez

4. In the execution system, assign ethe "OB_Send" program to


TimerinterruptTask_1. Specifyi a call interval of 24 ms for this task.
5. Save, compile, and download syour project to the D425-2 sender
station.
r.s

6. Test your project.

Solution You will find the solution in PRG_D425-2_V431_PN_E_8_send.zip.


ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 46 Exercises
Exercise A.1: Creating the user function UDP_Receive()

INTERFACE
VAR_GLOBAL
myRetStructRetUdpReceive : StructRetUdpReceive; //Return structure for receiving
DataReceived : ARRAY[0..15] OF BYTE; //Receive buffer
MyPosition : LREAL;
MyVelocity : LREAL;
END_VAR

om
FUNCTION UDP_Receive;
END_INTERFACE

IMPLEMENTATION
FUNCTION UDP_Receive : VOID
MyRetStructRetUdpReceive :=_udpReceive(port := 2222,
communicationmode := DO_NOT_CLOSE_ON_EXIT,
nextcommand := IMMEDIATELY,

l.c
receivevariable := DataReceived);

IF MyRetStructRetUdpReceive.functionresult = 0 THEN
MyPosition := LITTLEBYTEARRAY_TO_ANYTYPE(DataReceived, 0);
MyVelocity := LITTLEBYTEARRAY_TO_ANYTYPE(DataReceived, 8);

ai
END_IF;
END_FUNCTION
END_IMPLEMENTATION

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.47
SITRAIN Training for
Automation and Drives
@
What to do In the receiver station, the actual receipt of the data is implemented with the
simple user function "UDP_Receive". Following data receipt, the function is
called in the LAD program OB_Receive. The "OB_Receive" program is
assigned to TimerinterruptTask_2, which is called every 28 ms.
er

1. In your project, create an ST unit called "ST_Recv".


2. In the INTERFACE part, declare a "myRetStructRetUdpReceive" variable for
storing the return value of the _udpReceive() system function, the
"DataReceived" receive buffer of type ARRAY[0..15] OF BYTE, and the two
ez

variables "MyPosition" and MyVelocity" of type LREAL for storing the


unpacked data from the receive buffer.
The variables should be declared as global variables to make it easier to
monitor content subsequently via the symbol browser in the event of an
r.s

error.
In addition, publish the user function "UDP_send()" in the INTERFACE
part of the user function. It is called later from the "LAD_Main" unit.
3 Implement the user function "UDP_Receive()" in the IMPLEMENTATION
part without parameters or a return value.
ne

6. Next, issue the receive call _udpReceive() for port 2222. Remember that this
call is executed subsequently in a cyclic program. Therefore, you must pass
the value IMMEDIATELY for the nextcommand parameter.
In the return structure, the functionResult entry indicates whether new data
ca

has actually been received and copied to the "DataReceived" receive buffer.
Only unpack the data from receive buffer and write it to the two user
variables "MyPosition" and "MyVelocity" if new data has been received and
copied to the receive buffer.
Use the LITTLEBYTEARRAY_TO_ANYTYPE function to unpack the data.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 47 Exercises
Exercise A.1: Calling the UDP_Receive() function in OB_Receive

OB_Receive Execution system

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.48
SITRAIN Training for
Automation and Drives
@
What to do In the last step, the function created is called in a separate LAD program,
"OB_Receive". In the execution system, this LAD program is assigned to
TimerinterruptTask_2, which is called every 28 ms.
1. In the "LAD_Main" unit, establish a connection to the ST unit called
er

"ST_Recv".
2. In the "LAD_Main" unit, create a program called "OB_Receive".
3. In the first network, call the user functionm "UDP_Receive".
Also, link the EN input of the funcetion to the simulator input signal %I1.5.
ez

4. In the execution system, assign ithe "OB_Receive" program to


TimerinterruptTask_2. Specifsy a call interval of 28 ms for this task.
5. Save, compile, and downl oad your project to the D425-2 receiver
station.
r.s

6. Test your project.

Solution You will find the solution inu PRG_D425-2_V431_PN_E_8_recv.zip.


ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 48 Exercises
Exercise A.1: The alternative - UDP_Send2()
INTERFACE
USEPACKAGE CAM_ext;
TYPE
MyDataStruct : STRUCT
Position : LREAL;
Velocity : LREAL;
END_STRUCT;
END_TYPE
VAR_GLOBAL
myRetDINT: DINT; //Return value for sending

om
MySendData : MyDataStruct;
DataSend : ARRAY[0.._sizeof(in := MyDataStruct) -1] OF BYTE; //Send buffer
ReceiverAddress : ARRAY[0..3] OF USINT := [192,168,214,2]; //Address of receiver
END_VAR
FUNCTION UDP_SEND;
END_INTERFACE

IMPLEMENTATION
FUNCTION UDP_SEND : VOID

l.c
MySendData.Position := Axis_1.positioningstate.commandposition;
MySendData.Velocity := Axis_1.motionstatedata.commandvelocity;

DataSend := ANYTYPE_TO_LITTLEBYTEARRAY(
anydata := MySenderData,
offset:=0);

ai
myRetDINT := _udpsend(sourceport := 2222,
destinationaddress := ReceiverAddress,
destinationport := 2222,
communicationmode := DO_NOT_CLOSE_ON_EXIT,
datalength := dint_to_udint(_sizeof(in := MyDataStruct)),

SIMATIC S7
END_FUNCTION
END_IMPLEMENTATION

Siemens AG 2013. All rights reserved.


data := DataSend);

gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.49
SITRAIN Training for
Automation and Drives
@
UDP_Send2() In this case, the user structure of the data to be transmitted must be defined
prior to transmission. A structure "MyDataStruct" with the individual data types
to be transmitted is defined in the TYPE section.
Next, a user variable "MySendData" with type "MyDataStruct" is created, along
er

with the send buffer with type ARRAY OF BYTE. The length in BYTES of the
send buffer is determined using the system function _sizeof(), with the
"MyDataStruct" structure being passed in the "in" parameter.
In the statement part of the function, the required information about position and
ez

velocity is first copied to the structure variable "MySendData" before being


copied to the send buffer "DataSend" when the packing function
ANY_TYPE_TO_LITTLEBYTEARRAY is called. 0 must be entered as the offset
for the packing function.
r.s

Finally, the system function _udpsend() is called. The number of bytes to be


transmitted is also determined with _sizeof(), although in this case, the return
value must also be converted from DINT to UDINT.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 49 Exercises
Exercise A.1: The alternative - UDP_Receive2()

INTERFACE
TYPE
MyDataStruct : STRUCT // Structure of receive data following unpacking
Position : LREAL;
Velocity : LREAL;
END_STRUCT;
END_TYPE

om
VAR_GLOBAL
myRetStructRetUdpReceive : StructRetUdpReceive; //Return structure for receiving
DataReceived : ARRAY[0.._sizeof(in := MyDataStruct) -1] OF BYTE; //Receive buffer
MyReceivedData : MyDataStruct; // Structure variable for unpacked data
END_VAR
FUNCTION UDP_Receive2;
END_INTERFACE

l.c
IMPLEMENTATION
FUNCTION UDP_Receive2 : VOID
MyRetStructRetUdpReceive :=_udpreceive(port := 2222,
communicationmode := DO_NOT_CLOSE_ON_EXIT,
nextcommand := IMMEDIATELY,

ai
receivevariable := DataReceived);

IF MyRetStructRetUdpReceive.functionresult = 0 THEN
MyReceivedData := LITTLEBYTEARRAY_TO_ANYTYPE(DataReceived, 0);
END_IF;
END_FUNCTION
END_IMPLEMENTATION

SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.50
SITRAIN Training for
Automation and Drives
@
UDP_Receive2() In this case, the user structure of the data to be received must be defined prior
to receipt. This structure must be the same, i.e. have the same data types (not
necessarily the same names) as that used when sending data. A structure
called "MyDataStruct" with the individual data types is therefore defined in the
TYPE section.
Next, a user variable called "MyReceiveData" ewith type "MyDataStruct" as
er

well as the receive buffer with type ARRAY OF BYTE is created. The length in
BYTES of the receive buffer is determinedm using the system function
_sizeof(), with the "MyDataStruct" structure beeing passed in the "in"
parameter.
Then the system function _udpreceiive is called in the statement part of the
function. If there is new data in the receive buffer, it can be unpacked to the
ez

"MyReceivedData" structure variable by calling


LITTLEBYTE_ARRAY_TO_ANYTYPE. 0 must be entered as the offset for the
unpacking function.
The individual elements of the structure can be further processed from here.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 50 Exercises
Exercise A.2: "Fixed gear" for rigid coupling of the axes

"Fixed gear" TO

%I1.6

om
Initial
Sensor position

l.c
Slave value
Axis_1

ai
SIMATIC S7
Axis_2

Siemens AG 2013. All rights reserved.


gm
Date:
File:
Master value

10.01.2013
MC-SMO-PRG_10.51
SITRAIN Training for
Automation and Drives
@
Objective In this exercise, a rigid coupling of both axes is to be achieved using a "Fixed
gear" TO so that both axes can be traversed when coupled. The axes are
coupled using a relative position synchronous operation with a gear ratio of 1:1.
Gearing is activated and deactivated in manual mode via switch %I1.6.
er

Axis_2 provides the master values, Axis_1 implements the following axis.
In addition, synchronous operation is to be executed in the superimposed
coordinate system of Axis_1.
The actual logic for activating and deactivating the coupling is implemented in
ez

MotionTask_6 with the help of the MCC program "ActivateDeactivateCoupling".


MotionTask_6 is started from OB_Miain in manual mode with switch %I1.6.
Activation of the "Fixed gear" is dsisplayed in output %Q5.6.
To achieve synchronous op@eration, an expanded "Fixed gear" TO must first
r.s

What to do be created and configured.


1. Start by opening the "Technology" folder in the project navigator
window.
2. Next, double-clulick the "Fixed gear" entry to insert a "Fixed gear"
TO.
ne

3. In the propegrties dialog that opens, enter the TO name


"A2_A1_Coupling".
4. Seleoct the following settings in the configuration dialog that is
displayed:
ca

- Ilgnore position: "Deselected". Gearing is based on the position,


not the velocity
- Configuration: Linear axis
- Processing cycle clock: IPO
- The following is used for an active but invalid value: Last valid value

- Activate modulo: Deselected

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 51 Exercises
Exercise A.2: Settings for "Fixed gear"
Configuration: A2_A1_Coupling

Default: A2_A1_Coupling

om
Interconnections: A2_A1_Coupling

l.c
Axis_2 - Sepoint
Interconnections: Axis_1

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
"D425-2" – A2_A1_Coupling – Motion output

Date:
File:
10.01.2013
MC-SMO-PRG_10.52
SITRAIN Training for
Automation and Drives
@
Continued 5. Enter the following settings in the "Default" dialog:
- Direction: Same direction
- Gear type: Relative gear
er

- Gear ratio mode: Gear ratio as numerator denominator ratio


- Numerator:: 1
- Denominator: 1
ez

- Activation: Effective immediately


- Deactivation: Effective immediately
6. In the "Interconnections" dialog for the motion input of the "Fixed gear",
select Axis_2 with setpoint coupling.
r.s

7. In the "Interconnections" dialog for the motion input of Axis_1, select the
motion output of the "A2_A1_Coupling" TO.
8. Also, change the default behavior of the feedback of the superimposed
coordinate system to the basic coordinate system.
Open the expert list of Axis_1 and change the following configuration data:
ne

- Axis_1.typeOfAxis.decodingConfig.transferSuperimposedPosition =
TRANSFER_RESET
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 52 Exercises
Exercise A.2: Activation and deactivation logic (1)

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.53
SITRAIN Training for
Automation and Drives
@
Objective In the next step, we are going to create the MCC program "ActivateCoupling".
This program is started from the LAD program "OB_Main" and implements the
activation and deactivation logic for the "Fixed gear" and for the motion input of
Axis_1.
er

When the program starts, the fixed gear is activated. After this, the motion input
for the superimposed coordinate system at Axis_1 ise activated.
The program then waits for deactivation so that it can first stop Axis_1 in the
superimposed coordinate system and tmhen deactivate the gear. Deactivation
ez

can be activated via switch %I1.6, by deselecting "Manual" mode, or by


deactivating the "MotionIn" interface using some oether means.

What to do 1. Create an MCC unit called "MCC_Man".


r.s

2. Add an MCC program "ActivateCoupling" to the MCC unit called


"MCC_Man".
3. In the declaration part of the program, insert the temporary variable
"MyRetVal" ofu type DINT. This variable stores the return values of all system
functionsl which are called in this program.
ne

4. Use the sygstem function call to add the system function


_setFixedGearMaster() as the first command. Select the following settings for
the individual parameters:
- fixedGear : A2_A1_Coupling
- master: Axis_2
ca

- nextCommand: WHEN_COMMAND_DONE

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 53 Exercises
Exercise A.2: Activation and deactivation logic (2)

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.54
SITRAIN Training for
Automation and Drives
@
Continued 5. Then use the system function _enableFixedGear() to activate the "Fixed
gear". As all relevant settings have already been made in the Default dialog,
only the following entries have to be made explicitly in this command:
- fixedGear: A2_A1_Coupling
er

- nextCommand: WHEN_GEARING_START
6. Before you activate the motion input at Axis_2, remember:
Motion via the MotionIn interface is executed in the superimposed coordinate
ez

system.
To prevent compensating motion when the motion input is activated due to
differences in the values of the motion output of "Fixed gear" and the
instantaneous position of Axis_1 in the superimposed coordinate system, the
current superimposed position of Axis_1 must be calculated with the motion
r.s

output of the "Fixed gear".


This is achieved with the _setFixedGearingOffset() system function and the
following parameter settings:
- fixedGear: A2_A1_Coupling
ne

- offsetRange: SLAVE_RANGE
- offsetMode: ABSOLUTE
- offsetValue: Axis_1.superimposedmotion.position
- activationMode: ACTUAL_VALUE
ca

- nextCommand: WHEN_COMMAND_DONE

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 54 Exercises
Exercise A.2: Activation and deactivation logic (3)

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.55
SITRAIN Training for
Automation and Drives
@
Continued 7. In the next step, the motion input of the MotionIn interface of Axis_1 can now
be activated with the _runPositionBasedMotionIn() command:
- axis: Axis_1
er

- reference: A2_A1_Coupling
- megeMode: SUPERIMPOSED_MOTION_MERGE
- nextCommand: AT_MOTION_START
8. The above settings activate the MotionIn interface with coupling to
ez

"Fixed gear". The MCC program is now waiting for the following conditions
to be fulfilled so that it can then execute the corresponding deactivation
logic for Axis_1 and the "Fixed gear":
- %I1.6 changes state to FALSE
r.s

- Manual mode is deactivated (%Q4.1 = FALSE)


- MotionIn interface is deactivated from other side (e.g. with _resetAxis())
Insert a "Wait for condition" command with the above conditions.
Whether the MotionIn interface is active with respect to the superimposed
ne

coordinate system can be checked with the following system variable:


- Axis_1.positionbasedmotionincommand.motioninstate
9. In the next step, stop motion in the superimposed coordinate system by
sending the "Stop axis" command. Make sure that motion with respect to the
MotionIn interface is aborted.
ca

10. Use the system function _disableFixedGearing() to deactivate the "Fixed


gear". Make sure that the output value is "0".
- fixedGear: A2_A1_Coupling
- disableMode: IMMEDIATELY
- nextCommand: WHEN_MOTION_DONE
- motionOutBehaviourMode: ZERO_VALUE

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 55 Exercises
Exercise A.2: Starting the MCC program from OB_Main

OB_Main

om
l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.56
SITRAIN Training for
Automation and Drives
@
Objective In the last step, the "ActivateCoupling" program is assigned to MotionTask_6 in
the execution system and the start logic for MotionTask_6 is integrated into
OB_Main.
MotionTask_6 is started with the "TaskStartStop" function based on the
er

operating mode "Mode_Main.Mode_Manual" and the state of switch %I1.6. The


output of the function is interconnected to output %Q5.6.

1. In the execution system, assign the "ActivateCoupling" program to


ez

What to do
MotionTask_6. MotionTask_6 is noet started automatically after the
StartupTask.
2. Open the LAD program "OB_sMain" and enter a new network at
the end.
r.s

2. Insert a call to the function "TaskStartStop".


3. Interconnect the "Start@" input of the function with the AND logic
operation of the "Mode_Main. Mode_Manual" signals and %I1.6.
4. Interconnect the reuturn value of the function with output %Q5.6.
5. Compile, downlload, and test your project.
ne

Solution You will find tohe solution in PRG_D425-2_V431_PN_E_9.zip.


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 56 Exercises
Exercise A.3: Exporting OPC files
2. Version of SIMATIC NET

1. Export OPC files

om
For Data Access

For Alarms&Events

l.c
4. Enter interface 3. Enter path

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Drive:\Documents and Settings\All Users\Anwendungsdaten\
Siemens\SIMATIC.NET\opc2\binS7\simotion\xml\

Date:
File:
10.01.2013
MC-SMO-PRG_10.57
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to perform an OPC data export. We will then use
OPC Scout to test whether the OPC server on the programming device is
functioning correctly. As a first step, we will export the required files from
SIMOTION SCOUT and store them in the OPC server directory.
er

What to do 1. Switch SIMOTION SCOUT to offline mode if it is not already offline. Then
select menu command: Options -> Export OPCe data...
The dialog "Setting the Data for Expormt" opens.
ez

2. Activate "SIMATIC NET V8.1.1" foer the version of the OPC server and
the global export option for controillers (not drives).
Under Use, check all of the bosxes (i.e. "OPC data", "Arrays with single
elements", and "OPC alar m/event"). Then confirm your selection with "OK".
3. Next, the "OPC Export@" dialog opens in which you must enter the
r.s

target directory for the export files. In our case, the OPC server runs on the same
platform as SI MOTION SCOUT. Therefore, we can specify the directory
expected by the OuPC server when the system starts up as the target directory:
D:\Dokumgente und Einstellungen\AllUsers\Anwendungsdaten\ Siemens
\SIMATIC.NEoT\opc2\binS7\simotion\xml".
ne

Clickl "OK" to close the dialog.


4. Ine the next dialog, "Parameterize Interface", we must specify the
interface via which the OPC server accesses the SIMOTION device data at
runtime. Select the "TCP/IP" protocol and the X150 interface (PROFINET
PNxIO). for the D425-2.
The export operation then starts. You can monitor the export on the progress
ca

indicator that is displayed on the screen.


5. The dialog for configuring gateways opens when the export operation is
complete. Click "No" to close this dialog.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 57 Exercises
Exercise A.3: Settings to start the OPC server
Start -> SIMATIC -> SIMATIC NET -> Configuration Console

OPC Settings -> Protocol Selection: S7 Protocol

om
OPC Settings -> Symbols: Select *.sti File

l.c
Advanced symbols

ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.58
TCP/IP ->Intel ...

SITRAIN Training for


Automation and Drives
@
Task In this exercise, we are going to make the settings required to ensure that the
OPC server starts correctly. This essentially involves defining the correct
protocol, the selected symbol file with the process variables of the device, and
the interface for OPC server access.
er

What to do 1. Start by opening the Windows Start menu on your PG and select:
Start -> SIMATIC -> SIMATIC NET -> Comnfiguration Console
to open the "Configuration Consolee" tool.
ez

2. In the navigation window, selecit "PC Station" -> SIMATIC NET


Configuration -> Applicationss -> OPC Settings.
Under OPC Settings, selec t "Select OPC protocol" and check whether the S7
protocol is select@ed in the working area. Check the box for the S7 protocol if
r.s

necessary.
3. In the navigation w indow, select "Symbols". Click the "Edit list" button
to open the "Manage suymbol files" dialog.
In this dialog, click the "Browse" button and select the exported *.sti file from our
SIMOTION project.
ne

After you have selected the symbol file, close the "Edit list" dialog by clicking
"OK". The selected symbol file is displayed in the "Active symbol files" list.
4. The last step is to open the "Advanced Symbols" dialog by clicking the
"Advanced Symbols" button. In this box, select the interface via which the OPC
server will access the SIMOTION device.
ca

To do this, select "TCP/IP . . ." in the "SIMOTION module" selection box.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 58 Exercises
Exercise A.3: Using OPC Scout to access the OPC server

Start -> SIMATIC -> SIMATIC NET -> OPC SCOUT


Step 2: Enter a group name
Step 1: Double-click OPC-SimaticNet (create OPC group)
(establish a connection to the OPC server)

om
Step 3: Add items to the group and
monitor

l.c
ai
SIMATIC S7
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_10.59
SITRAIN Training for
Automation and Drives
@
Task In this exercise, we are going to test the accessibility and correct functioning of
the OPC server. To do this, we will start the OPC client application OPC Scout
and check whether OPC server variables can be accessed.
er

What to do 1. Start OPC Scout via the Windows Start menu:


Start -> SIMATIC -> SIMATIC NET -> OPC Scout.
2. Double-click "OPC.SimaticNET" to establish a connection to the OPC server.
ez

Once the OPC server is running, the "Add Group" dialog opens.
3. Enter a group name of your choice and click "OK" to confirm your entry
and close the dialog. The new group is displayed in the navigation window of
OPC Scout.
4. The next step is to add the desired process variables to the new group.
r.s

To do this, double-click the new group in the navigation window.


The OPC navigator opens. The folders containing the process variables
of the SIMOTION device are listed arranged in a hierarchy under the "Sym"
entry in the navigation window of the OPC navigator.
ne

5. Select the folder of your choice in the navigation window; the process
variables (items) it contains will be displayed in the "Leaves" window.
Select the desired process variables in the "Leaves" window and click the
" -> " button. The selected process variable is added to the OPC group and
displayed in the right-hand window.
ca

6. Repeat the selection made in Step 5 until you have added all the required
process variables to the OPC group. Then confirm your selections by clicking
"OK".
The OPC navigator closes. The selected process variables and their current
values are now visible in the OPC Scout window.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 59 Exercises
Solutions for the exercises

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_11.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Exercise 2.1: Flash_1 ....................................................................................................................... 3
Exercise 2.2: Flash_2 ....................................................................................................................... 4
er

Exercise 2.3: Flash_3 ....................................................................................................................... 5


Exercise 2.4: Flash_4 ....................................................................................................................... 6
Exercise 3.1: "FC_Unit" .................................................................................................................... 7
ez

Exercise 3.2: The FC call ................................................................................................................. 8


Exercise 3.3: "ST2_UNIT" ................................................................................................................ 9
Exercise 3.3: The UNIT: "ST_Main" .................................................................................................. 10
Exercise 3.4: FB instance call ........................................................................................................... 11
r.s

Exercise 4.1: Static motion of an axis ............................................................................................... 12


Exercise 4.2: Integration of edge evaluation ..................................................................................... 13
Exercise 4.3: Passing the velocity .................................................................................................... 14
Exercise 4.4: Output of the BUSY signal (1) ..................................................................................... 15
ne

Exercise 4.4: Output of the BUSY signal (2) ..................................................................................... 16


Exercise 4.5: Passing the axis TO as an input parameter (1) ............................................................ 17
Exercise 4.5: Passing the axis TO as an input parameter (2) ............................................................ 18
Exercise 4.6: Integrating negative direction (1) ................................................................................. 19
ca

Exercise 4.6: Integrating negative direction (2) ................................................................................. 20


Exercise 4.7: Integrating troubleshooting (1) ..................................................................................... 21
Exercise 4.7: Integrating troubleshooting (2) ..................................................................................... 22
Exercise 4.7: Integrating troubleshooting (3) ..................................................................................... 23
Exercise 4.7: Integrating troubleshooting (4) ..................................................................................... 24
Exercise 4.7: FB calls ....................................................................................................................... 25
Exercise 5.2: OB_Main (1) .............................................................................................................. 26

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 Solutions
Solutions for the exercises

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PROG_11.2
SITRAIN Training for
Automation and Drives
@
Contents Page
Exercise 5.2: OB_Main (2) .............................................................................................................. 27
Exercise 6.1: Creating the "TaskStartStop" function ......................................................................... 28
er

Exercise 6.2: Creating an "ErrorHandler" for TechFaultTask ............................................................ 29


Exercise 6.3: Integrating automatic mode in OB_Main (1) ................................................................ 30
Exercise 6.3: Integrating automatic mode in OB_Main (2) ................................................................ 31
Exercise 6.3: Integrating automatic mode in OB_Main (3) ................................................................ 32
ez

Exercise 6.4: Integrating automatic mode with "RunAuto" ................................................................ 33


Exercise 7.1: Start of synchronization "StartGearing" ....................................................................... 34
Exercise 7.1: Start of synchronization "Cutting" ................................................................................ 35
Exercise 7.2: Configuring the Alarm_S message .............................................................................. 36
Exercise 7.3: Integrating the output cam (1) ...................................................................................... 37
r.s

Exercise 7.3: Integrating the output cam (2) ...................................................................................... 38


Exercise 8.2: The "Cam_Unit" UNIT ................................................................................................. 39
Exercise 8.2: Calling the FC in "Test_Cam" ...................................................................................... 40
Exercise 8.2: Testing the cam in "Test_Cam" ................................................................................... 41
ne

Exercise 9.1: Flying shear with cam ................................................................................................. 42


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Solutions
Exercise 2.1: Flash_1

om
UNIT ST1;
INTERFACE
VAR_GLOBAL
CounterVar : INT := 1;
OutputVar : BYTE := 1;

l.c
END_VAR

PROGRAM Flash_1;

ai
END_INTERFACE

IMPLEMENTATION

PROGRAM Flash_1

IF CounterVar <= 500 THEN


gm
CounterVar := CounterVar + 1;
@
ELSE
%QB4 := OutputVar;
OutputVar := ROL(OutputVar,1);
er

CounterVar := 1;
END_IF;
ez

END_PROGRAM

END_IMPLEMENTATION
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Solutions
Exercise 2.2: Flash_2

om
UNIT ST1;
INTERFACE

PROGRAM Flash_2;

l.c
END_INTERFACE

IMPLEMENTATION

ai
PROGRAM Flash_2

VAR
CounterVar : INT := 1;
OutputVar : BYTE := 1;
END_VAR
gm
IF CounterVar <= 500 THEN
@
CounterVar := CounterVar + 1;
ELSE
%QB4 := OutputVar;
er

OutputVar := ROL(OutputVar,1);
CounterVar := 1;
END_IF;
ez

END_PROGRAM

END_IMPLEMENTATION
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Solutions
Exercise 2.3: Flash_3

om
UNIT ST1;
INTERFACE

PROGRAM Flash_3;

l.c
END_INTERFACE

IMPLEMENTATION

ai
PROGRAM Flash_3

VAR
CounterVar : INT := 1;
OutputVar : WORD := 256;
END_VAR
gm
IF CounterVar <= 500 THEN
@
CounterVar := CounterVar + 1;
ELSE
%QW4 := OutputVar;
er

OutputVar := ROL(OutputVar,1);
CounterVar := 1;
END_IF;
ez

END_PROGRAM

END_IMPLEMENTATION
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Solutions
Exercise 2.4: Flash_4

om
UNIT ST1;
INTERFACE

PROGRAM Flash_4;

l.c
END_INTERFACE

IMPLEMENTATION

ai
PROGRAM Flash_4

VAR_TEMP
OutputVar : WORD := 256;
END_VAR
VAR
CounterVar : INT := 1;
gm
END_VAR
@
IF CounterVar <= 500 THEN
CounterVar := CounterVar + 1;
er

ELSE
%QW4 := OutputVar;
OutputVar := ROL(OutputVar,1);
ez

CounterVar := 1;
END_IF;

END_PROGRAM
r.s

END_IMPLEMENTATION
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Solutions
Exercise 3.1: "FC_UNIT"

UNIT FC_UNIT;
INTERFACE

om
TYPE SumMeanValue : STRUCT
Sum : LREAL;
MeanValue : LREAL;
END_STRUCT;
END_TYPE

l.c
FUNCTION MyFC;

END_INTERFACE

ai
IMPLEMENTATION

FUNCTION MyFC : SumMeanValue


VAR_INPUT gm
MeasValue: ARRAY[0..9] OF LREAL;
END_VAR
@
VAR
Index : INT;
IntermSum : LREAL;
er

END_VAR

FOR Index := 0 TO 9 BY 1 DO
ez

IntermSum := IntermSum + MeasValue[Index];


END_FOR;

MyFC.Sum := IntermSum;
r.s

MyFC.MeanValue := IntermSum / 10;

END_FUNCTION
ne

END_IMPLEMENTATION
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Solutions
Exercise 3.2: The FC call

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Solutions
Exercise 3.3: "MyFC2"

INTERFACE
TYPE SumMeanValue : STRUCT
Sum : LREAL;

om
MeanValue : LREAL;
END_STRUCT;
END_TYPE
FUNCTION MyFC;
FUNCTION MyFC2;

l.c
END_INTERFACE

IMPLEMENTATION
FUNCTION MyFC : SumMeanValue

ai
VAR_INPUT
MeasValue: ARRAY[0..9] OF LREAL;
END_VAR
VAR
Index : INT;
IntermSum : LREAL;
END_VAR
FOR Index := 0 TO 9 BY 1 DO
gm
@
IntermSum := IntermSum + MeasValue[Index];
END_FOR;
MyFC.Sum := IntermSum;
MyFC.MeanValue := IntermSum / 10;
er

END_FUNCTION

FUNCTION MyFC2 : SumMeanValue


VAR_IN_OUT
ez

MeasValue : ARRAY [..] OF LREAL;


END_VAR
VAR
r.s

i : DINT;
IntermSum : LREAL;
END_VAR
ne

FOR i := _firstIndexOf(in := MeasValue) TO _lastIndexOf(in := MeasValue)

DO
IntermSum := IntermSumo+ MeasValue[i];
END_FOR;
ca

MyFC2.Sum := IntermSum;
MyFC2.MeanValue := IntermSumk /_lengthIndexOf(in:= MeasValue);
END_FUNCTION
END_IMPLEMENTATION

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Solutions
Exercise 3.3: The UNIT: "ST_Main"
INTERFACE

FUNCTION_BLOCK OP_Mode;

om
END_INTERFACE

IMPLEMENTATION

FUNCTION_BLOCK OP_Mode

l.c
VAR_INPUT
Start: BOOL;
Stop: BOOL;

ai
Manual_Auto : BOOL;
Activate_Mode : BOOL;
END_VAR

VAR_OUTPUT
System_ON : BOOL;
Mode_Manual : BOOL;
Mode_Auto : BOOL;
END_VAR
gm
@
// Two "networks" for switching on and off
IF Start THEN System_ON := TRUE; END_IF;
IF NOT Stop THEN System_ON := FALSE; END_IF;
er

// Two "networks" for activating/deactivating manual mode


IF System_ON AND NOT Manual_Auto AND Activate_Mode
THEN Mode_Manual := TRUE; END_IF;
IF NOT System_ON OR Manual_Auto THEN Mode_Manual := FALSE; END_IF;
ez

// Two "networks" for activating/deactivating automatic modei

IF System_ON AND Manual_Auto ANDsActivate_Mode


THEN Mode_Auto := TRUE; END_IF;
r.s

IF NOT System_ON OR NOT Manual_Auto@THEN Mode_Auto := FALSE; END_IF;

END_FUNCTION_BLOCK
ne

END_IMPLEMENTATION
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Solutions
Exercise 3.4: FB instance call

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 Solutions
Exercise 4.1: Static motion

UNIT Unit_Pos;
INTERFACE
USEPACKAGE CAM; //Select technology package

om
FUNCTION_BLOCK Move_Axis;

END_INTERFACE

IMPLEMENTATION

l.c
FUNCTION_BLOCK Move_Axis

VAR_INPUT

ai
JOG_Pos: BOOL; //Start axis motion
END_VAR

VAR_TEMP
Ret_Val: DINT;
END_VAR

IF JOG_Pos THEN
gm
//Variable for storing the return value

ret_val:=_move(
@
axis:=Axis_1,
direction:=positive,
velocitytype:=USER_DEFAULT,
velocity:=100,
er

velocityprofile:=USER_DEFAULT,
mergemode:=immediately,
nextcommand:=IMMEDIATELY, //Advance immediately
commandid:=_getcommandid(),
ez

movingmode:=POSITION_CONTROLLED);
END_IF;

END_FUNCTION_BLOCK
r.s

END_IMPLEMENTATION
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 Solutions
Exercise 4.2: Integration of edge evaluation

UNIT Unit_Pos;
INTERFACE
USEPACKAGE CAM; //Select technology package

om
FUNCTION_BLOCK Move_Axis;

END_INTERFACE

IMPLEMENTATION

l.c
FUNCTION_BLOCK Move_Axis

VAR_INPUT
JOG_Pos: BOOL; //Start axis motion

ai
END_VAR
VAR
r_trig_1 : r_trig; //Instance for R_TRIG FB
f_trig_1: f_trig;
END_VAR

VAR_TEMP
Ret_Val: DINT;
gm
//Instance for F_TRIG FB

//Variable for return value


END_VAR
@
r_trig_1(clk:=JOG_Pos); //Call R_TRIG FB using instance
f_trig_1 (clk:=JOG_Pos); //Call F_TRIG FB using instance
er

IF r_trig_1.q THEN //On positive edge


ret_val:=_move( //Call move command
axis := Axis_1,
direction:=positive,
ez

velocitytype:=USER_DEFAULT,
velocity:=100,
velocityprofile:=USER_DEFAULT,
mergemode:=immediately,
nextcommand := IMMEDIATELY,
r.s

commandid:=_getcommandid(),
movingmode:=POSITION_CONTROLLED);
END_IF;
ne

IF f_trig_1.q THEN //On negative edge


ret_val :=_stop( //Call stop command
axis := Axis_1,
stopmode:=STOP_and_ABORT,
stopspecification:=ALL_AXIS_MOTION,
ca

stopid:=_getcommandid (),
mergemode:=IMMEDIATELY,
nextcommand := IMMEDIATELY,
commandid:=_getcommandid());
END_IF;

END_FUNCTION_BLOCK
END_IMPLEMENTATION

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 Solutions
Exercise 4.3: Passing the velocity

UNIT Unit_Pos;
INTERFACE
USEPACKAGE CAM; //Select technology package

om
FUNCTION_BLOCK Move_Axis;
VAR_GLOBAL
Act_Velocity: LREAL := 100;
END_VAR
END_INTERFACE

l.c
IMPLEMENTATION

FUNCTION_BLOCK Move_Axis
VAR_INPUT

ai
JOG_Pos: BOOL; //Start axis motion
Velocity: LREAL; //Passing of velocity
END_VAR
VAR
r_trig_1 : r_trig;
f_trig_1: f_trig;
END_VAR
gm
//Instance for R_TRIG FB
//Instance for F_TRIG FB

VAR_TEMP
@
Ret_Val: DINT; //Variable for return value
END_VAR

r_trig_1(clk:=JOG_Pos); //Call R_TRIG FB using instance


er

f_trig_1 (clk:=JOG_Pos); //Call F_TRIG FB using instance

IF r_trig_1.q THEN //On positive edge


ret_val:=_move( //Call move command
ez

axis := Axis_1,
direction:=positive,
velocitytype:=USER_DEFAULT,
velocity:=Velocity,
velocityprofile:=USER_DEFAULT,
r.s

mergemode:=immediately,
nextcommand := IMMEDIATELY,
commandid:=_getcommandid(),
movingmode:=POSITION_CONTROLLED);
ne

END_IF;

IF f_trig_1.q THEN //On negative edge


ret_val :=_stop( //Call stop command
axis := Axis_1,
ca

stopmode:=STOP_and_ABORT,
stopspecification:=ALL_AXIS_MOTION,
stopid:=_getcommandid (),
mergemode:=IMMEDIATELY,
nextcommand := IMMEDIATELY,
commandid:=_getcommandid());
END_IF;
END_FUNCTION_BLOCK
END_IMPLEMENTATION

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 Solutions
Exercise 4.4: Output of the BUSY signal (1)

UNIT Unit_Pos;
INTERFACE
USEPACKAGE CAM; //Select technology package

om
FUNCTION_BLOCK Move_Axis;
VAR_GLOBAL
Act_Velocity: LREAL := 100;
END_VAR
END_INTERFACE
IMPLEMENTATION

l.c
FUNCTION_BLOCK Move_Axis

VAR_INPUT
JOG_Pos: BOOL; //Start axis motion

ai
Velocity: LREAL; //Passing of velocity
END_VAR
VAR_OUTPUT

VAR
BUSY_Pos: BOOL;
END_VAR

r_trig_1 : r_trig;
f_trig_1: f_trig;
gm
// Status of axis motion

//Instance for R_TRIG FB


//Instance for F_TRIG FB
END_VAR
@
VAR_TEMP
Ret_Val: DINT; //Variable for return value
END_VAR
er

r_trig_1(clk:=JOG_Pos); //Call R_TRIG FB using instance


f_trig_1 (clk:=JOG_Pos); //Call F_TRIG FB using instance
ez

IF r_trig_1.q THEN //On positive edge


ret_val:=_move( //Call move command
axis := Axis_1,
direction:=positive,
velocitytype:=USER_DEFAULT,
r.s

velocity:=Velocity,
velocityprofile:=USER_DEFAULT,
mergemode:=immediately,
nextcommand := IMMEDIATELY,
ne

commandid:=_getcommandid(),
movingmode:=POSITION_CONTROLLED);
END_IF;

IF f_trig_1.q THEN //On negative edge


ca

ret_val :=_stop( //Call stop command


axis := Axis_1,
stopmode:=STOP_and_ABORT,
stopspecification:=ALL_AXIS_MOTION,
stopid:=_getcommandid (),
mergemode:=IMMEDIATELY,
nextcommand := IMMEDIATELY,
commandid:=_getcommandid());
END_IF; //Continued on next page

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 Solutions
Exercise 4.4: Output of the BUSY signal (2)

IF NOT (Axis_1.motionstatedata.motionstate = standstill) THEN


BUSY_Pos:= TRUE; //Busy signal evaluation

om
ELSE
BUSY_Pos:= FALSE;
END_IF;

END_FUNCTION_BLOCK
END_IMPLEMENTATION

l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 Solutions
Exercise 4.5: Passing the axis TO as an input
parameter (1)

UNIT Unit_Pos;

om
INTERFACE
USEPACKAGE CAM; //Select technology package
FUNCTION_BLOCK Move_Axis;
VAR_GLOBAL
Act_Velocity: LREAL := 100;
END_VAR

l.c
END_INTERFACE
IMPLEMENTATION
FUNCTION_BLOCK Move_Axis

VAR_INPUT

ai
JOG_Pos: BOOL; //Start axis motion
Axis : posAxis; //Selected axis
Velocity: LREAL; //Passing of velocity
END_VAR
VAR_OUTPUT
BUSY_Pos: BOOL;
END_VAR
VAR
gm
// Status of axis motion

r_trig_1 : r_trig; //Instance for R_TRIG FB


@
f_trig_1: f_trig; //Instance for F_TRIG FB
END_VAR

VAR_TEMP
er

Ret_Val: DINT; //Variable for return value


END_VAR

r_trig_1(clk:=JOG_Pos); //Call R_TRIG FB using instance


ez

f_trig_1 (clk:=JOG_Pos); //Call F_TRIG FB using instance


IF r_trig_1.q THEN //On positive edge
ret_val:=_move( //Call move command
axis:=Axis,
r.s

direction:=positive,
velocitytype:=USER_DEFAULT,
velocity:=Velocity,
velocityprofile:=USER_DEFAULT,
mergemode:=immediately,
ne

nextcommand := IMMEDIATELY,
commandid:=_getcommandid(),
movingmode:=POSITION_CONTROLLED);
END_IF;
IF f_trig_1.q THEN //On negative edge
ca

ret_val :=_stop( //Call stop command


axis:=Axis,
stopmode:=STOP_and_ABORT,
stopspecification:=ALL_AXIS_MOTION,
stopid:=_getcommandid (),
mergemode:=IMMEDIATELY,
nextcommand := IMMEDIATELY,
commandid:=_getcommandid());
END_IF; //Continued on next page
SITRAIN Training for MC-SMO-PRG
Automation and Drives Page 17 Solutions
Exercise 4.5: Passing the axis TO as an input
parameter (2)

om
IF NOT (Axis.motionstatedata.motionstate = standstill) THEN
BUSY_Pos:= TRUE; //Busy signal evaluation
ELSE
BUSY_Pos:= FALSE;
END_IF;

l.c
END_FUNCTION_BLOCK
END_IMPLEMENTATION

ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 Solutions
Exercise 4.6: Integrating negative direction (1)
UNIT Unit_Pos;
INTERFACE
USEPACKAGE CAM; //Select technology package
FUNCTION_BLOCK Move_Axis;

om
VAR_GLOBAL
Act_Velocity: LREAL := 100;
END_VAR
END_INTERFACE

IMPLEMENTATION

l.c
FUNCTION_BLOCK Move_Axis

VAR_INPUT
JOG_pos: BOOL; //Start axis motion
JOG_neg: BOOL;

ai
Axis : posAxis; //Selected axis
Velocity: LREAL; //Passing of velocity
END_VAR

VAR_OUTPUT
BUSY_POS: BOOL;
BUSY_NEG: BOOL;
END_VAR
gm
// Status of axis motion
@
VAR
r_trig_1 : r_trig; //Instance_JOG_Pos for R_TRIG FB
f_trig_1: f_trig; //Instance_JOG_Pos for F_TRIG FB
r_trig_2: r_trig; //Instance_JOG_Neg for R_TRIG FB
er

f_trig_2: f_trig; //Instance_JOG_Neg for F_TRIG FB


Pos_Command: BOOL;
Neg_Command: BOOL;
END_VAR
ez

VAR_TEMP
Ret_Val: DINT; //Variable for return value
END_VAR
r.s

r_trig_1(clk:=JOG_pos); //Rising edge positive direction


f_trig_1(clk:=JOG_pos); //Falling edge negative direction
r_trig_2(clk:=JOG_neg); //Rising edge negative direction
f_trig_2(clk:=JOG_neg); //Falling edge negative direction
ne

//On a pos. edge at JOG_pos if a pos. edge is not pending


//simultaneously at JOG_neg and a neg. motion command is not pending,
//then ...
IF r_trig_1.q AND NOT r_trig_2.q AND NOT Neg_Command THEN
ca

ret_val:=_move(axis:=Axis,
direction:=positive, velocitytype:=USER_DEFAULT,
velocity:=Velocity,
velocityprofile:=USER_DEFAULT,
mergemode:=immediately,
nextcommand := IMMEDIATELY,
commandid:=_getcommandid(),
movingmode:=POSITION_CONTROLLED); //Next page

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 Solutions
Exercise 4.6: Integrating negative direction (2)
Pos_Command := TRUE;

END_IF;
//On a positive edge at JOG_neg if a pos. edge is not pending

om
//simultaneously at JOG_pos and a pos. motion command is not pending,
//then ...
IF r_trig_2.q AND NOT r_trig_1.q AND NOT Pos_Command THEN
ret_val:=_move(axis:=Axis,
direction:=negative,
velocitytype:=USER_DEFAULT,

l.c
velocity:=Velocity,
velocityprofile:=USER_DEFAULT,
mergemode:=immediately,
nextcommand := IMMEDIATELY,
commandid:=_getcommandid(),

ai
movingmode:=POSITION_CONTROLLED);
Neg_Command := TRUE;
END_IF;

gm
//On a negative edge with associated traversing command
IF (f_trig_1.q AND Pos_Command) OR (f_trig_2.q AND Neg_Command) THEN
ret_val :=_stop(
@
axis:=Axis,
er

stopmode:=STOP_and_ABORT, stopspecification:=ALL_AXIS_MOTION,
stopid:=_getcommandid (), mergemode:=IMMEDIATELY, nextcommand :=
IMMEDIATELY, commandid:=_getcommandid());

Pos_Command := FALSE;
ez

Neg_Command := FALSE;
END_IF; //Busy signal evaluation
IF NOT (Axis.motionstatedata.motionstate=standstill) i AND
(Axis.motionstatedata.actualVelocitys >= 0) THEN BUSY_POS:= TRUE;
r.s

BUSY_NEG:= FALSE; END_IF;


IF NOT u(Axis.motionstatedata.motionstate=standstill) AND
l(Axis.motionstatedata.actualVelocity<= 0)THEN BUSY_Neg:= TRUE;
BUSY_POS:= FALSEo; END_IF;
IF kAxis.motionstatedata.motionstate=standstill THEN
ne

BUSY_Neg:= .FALSE; BUSY_Pos:= c FALSE; //Busy signal evaluation


END_IF;
END_FUNCTION_BLOCKi dEND_IMPLEMENTATION
//Busy signal evaluation
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 Solutions
Exercise 4.7: Integrating troubleshooting (1)

FUNCTION_BLOCK Move_Axis_7

VAR_INPUT

om
JOG_pos: BOOL; //Start axis motion
JOG_neg: BOOL ;
Axis : posAxis; //Selected axis
Velocity : LREAL; //Passing of velocity
END_VAR

l.c
VAR_OUTPUT
BUSY_POS: BOOL; // Status of axis motion
BUSY_NEG: BOOL ;
Error: BOOL; // Synchronous error

ai
CommandAborted: BOOL; // Asynchronous error
END_VAR

VAR

r_trig_2: r_trig;
f_trig_2: f_trig;
gm
r_trig_1 : r_trig; //Instance_JOG_Pos for the R_TRIG FB
f_trig_1: f_trig; //Instance_JOG_Pos for the F_TRIG FB
//Instance_JOG_Neg for the R_TRIG FB
//Instance_JOG_Neg for the F_TRIG FB
Pos_Command: BOOL ;
@
Neg_Command: BOOL ;
ret_val_id: STRUCTretcommandstate; //Stores the RetVal of
_getstate...
myid: commandidtype; //CommandID
er

END_VAR

VAR_TEMP
Ret_Val_1: DINT; //Variables for return value
ez

Ret_Val_2: DINT;
RetVal : DINT;
END_VAR

r_trig_1(clk:=JOG_pos); //Rising edge positive direction


r.s

f_trig_1(clk:=JOG_pos); //Falling edge negative direction


r_trig_2(clk:=JOG_neg); //Rising edge negative direction
f_trig_2(clk:=JOG_neg); //Falling edge negative direction
ne

//Continued on next page


//On a positive edge at JOG_pos if a pos. edge is not pending
simultaneously
//at JOG_neg and a neg. motion command is not pending,
//then...
ca

IF r_trig_1.q AND NOT r_trig_2.q AND NOT Neg_Command THEN


Ret_Val_1 := -1; //Set ret_val to error
RET_Val_2 := -1;
IF NOT (Axis = TO#NIL) THEN
myid:=_getcommandid (); //commandid assignment
Ret_Val_1 := _bufferaxiscommandid( // Buffer CommandId in TO
axis, myid);
IDCounter := IDCounter + 1; // For test purposes
//Next page
SITRAIN Training for MC-SMO-PRG
Automation and Drives Page 21 Solutions
Exercise 4.7: Integrating troubleshooting (2)
IF Ret_Val_1 = 0 THEN //Call only if CommandId buffered
Ret_Val_2:=_move(
axis:=Axis,

om
direction:=positive,
velocitytype:=DIRECT,
velocity:=Velocity,
velocityprofile:=USER_DEFAULT,
mergemode:=immediately,
nextcommand := IMMEDIATELY,

l.c
commandid:=myid,
movingmode:=POSITION_CONTROLLED);

IF Ret_Val_2 <> 0 THEN


RetVal := _removebufferedaxiscommandid( // Delete CommandId

ai
axis := Axis, // Axis
removemode := SPECIFIC_ID, // Specific
commandid := myID);

END_IF;
// Ret_Val_2
// Ret_Val_1
gm
IDCounter := IDCounter - 1;
END_IF;

IF Ret_Val_1 = 0 AND RET_VAL_2 = 0 THEN Error := FALSE;


ELSE Error:= TRUE;
@
END_IF; //
Pos_Command := TRUE;
ELSE Error := TRUE; //Else branch to axis = TO#NIL
END_IF; //Axis = TO#NIL
er

END_IF; //Edge detection

IF r_trig_2.q AND NOT r_trig_1.q AND NOT Pos_Command THEN


Ret_Val_1 := -1; //Set ret_val to error
ez

Ret_Val_2 := -1;
IF NOT (Axis = TO#NIL) THEN
myid:=_getcommandid (); //commandid assignment
Ret_Val_1 := _bufferaxiscommandid( // Buffer CommandId in TO
r.s

axis:=Axis,
commandid := myid);

IDCounter := IDCounter + 1; // For test purposes


ne

IF Ret_Val_1 = 0 THEN //Call only if CommandId buffered


Ret_Val_2:=_move(
axis:=Axis,
direction:=negative,
velocitytype:=DIRECT,
ca

velocity:=Velocity,
velocityprofile:=USER_DEFAULT,
mergemode:=immediately,
nextcommand := IMMEDIATELY,
commandid:=myid,
movingmode:=POSITION_CONTROLLED);

//Next page

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 Solutions
Exercise 4.7: Integrating troubleshooting (3)
IF Ret_Val_2 <> 0 THEN
RetVal := _removebufferedaxiscommandid( // Delete CommandId
axis := Axis, // Axis

om
removemode := SPECIFIC_ID, // Specific
commandid := myID);
IDCounter := IDCounter - 1;
END_IF; // Ret_Val_2
END_IF; // Ret_Val_1

l.c
IF Ret_Val_1 = 0 AND RET_VAL_2 = 0
THEN Error := FALSE;
ELSE Error:= TRUE;
END_IF; //
Neg_Command := TRUE;

ai
ELSE Error := TRUE; //Else branch to axis = TO#NIL
END_IF; //Axis = TO#NIL
END_IF; //Edge detection

Ret_Val_2 :=_stop(
axis:=Axis,
gm
IF (f_trig_1.q AND Pos_Command) OR (f_trig_2.q AND Neg_Command) THEN
IF NOT (Axis = TO#NIL) THEN //On negative edge
//Access only with valid pointer

stopmode:=STOP_and_ABORT,
@
stopspecification:=ALL_AXIS_MOTION,
stopid:=_getcommandid (),
mergemode:=IMMEDIATELY,
nextcommand := IMMEDIATELY,
er

commandid:=_getcommandid());

RetVal := _removebufferedaxiscommandid( // Delete CommandId


axis := Axis, // Axis
ez

removemode := SPECIFIC_ID, // Specific


commandid := myID);
IDCounter := IDCounter - 1;
END_IF; //Axis = TO#NIL
r.s

Pos_Command := FALSE;
Neg_Command := FALSE;
Error := FALSE;
CommandAborted := FALSE;
END_IF; //Edge evaluation;u
ne

IF NOT (Axis = TO#NIL) THEN //Access only with valid pointer


oIF NOT (Axis.motionstatedata.motionstate= standstill) AND
l(Axis.motionstatedata.actualVelocity>= 0) THEN BUSY_POS:= TRUE;
BUSY_NEG:= FALSE;k END_IF;
nIF NOT (Axis.motionstatedata.motionstate= standstill) AND
ca

//Busy signal evaluation

(Axis.motionstatedata.actualVelocity <= 0)THEN BUSY_Neg:= TRUE;

BUSY_POS:= FALSE; //Busy signal evaluation


END_IF;
//Next page
SITRAIN Training for MC-SMO-PRG
Automation and Drives Page 23 Solutions
Exercise 4.7: Integrating troubleshooting (4)
IF Axis.motionstatedata.motionstate = standstill THEN
BUSY_Neg:= FALSE;
BUSY_Pos:= FALSE; //Busy signal evaluation

om
END_IF;

// Asynchronous error evaluation


ret_val_id:=_getstateofaxiscommand(axis:= Axis,
commandid := myid);
// If the CommandId reports ABORTED and the traversing command

l.c
// has not been aborted with _stop(), another command
// or state must have caused motion to be aborted

IF (ret_val_id.commandidstate = ABORTED)
THEN CommandAborted :=TRUE;

ai
ELSE CommandAborted := FALSE;
END_IF; // ret_val_id ... ABORTED
END_IF; //Axis = TO#NIL

Error := FALSE;
CommandAborted := FALSE;
END_IF;
gm
IF JOG_pos = FALSE AND JOG_neg = FALSE THEN // Reset outputs
@
END_FUNCTION_BLOCK
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 Solutions
Exercise 4.7: FB calls

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 25 Solutions
Exercise 5.2: Integrating blocks in OB_Main (1)

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 26 Solutions
Exercise 5.2: Integrating blocks (2)

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 27 Solutions
Exercise 6.1: Creating the "TaskStartStop" function

FUNCTION TaskStartStop : BOOL

VAR_INPUT

om
Start: BOOL := FALSE;
Stop: BOOL := FALSE;
TaskID : StructTaskId;
END_VAR

VAR

l.c
MyTaskState : DWORD;
END_VAR

IF (Start AND NOT Stop) AND (_getStateOfTaskId(TaskID) AND

ai
TASK_STATE_RUNNING) = 0
THEN
MyTaskState := _restartTaskId(TaskId);
END_IF;

THEN
gm
IF Stop AND (_getStateOfTaskId(TaskID) AND TASK_STATE_RUNNING) <> 0

MyTaskState := _resetTaskId(TaskId);
END_IF;
@
TaskStartStop:=(_getStateOfTaskID(TaskId) AND TASK_STATE_RUNNING)<>0;

END_FUNCTION
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 28 Solutions
Exercise 6.2: Creating an "ErrorHandler" for
TechFaultTask

INTERFACE
USEPACKAGE CAM;

om
PROGRAM ErrorHandlerTechFault;
END_INTERFACE

IMPLEMENTATION
PROGRAM ErrorHandlerTechFault

l.c
VAR
MyDriveAxis : driveAxis;
myRetDINT : DINT;
END_VAR

ai
MyDriveAxis := ANYOBJECT_TO_OBJECT(TSI#toInst);
IF MyDriveAxis <> TO#Nil THEN

CASE TSI#alarmNumber OF
30002,
40021,
12345,
54321:
gm
// Command aborted
// StopEmergency ommand abort ...
// 1. Fantasiealarm
// 2. Fantasiealarm
@
myRetDINT := _resetAxisError(axis := MyDriveAxis,
errorresetmode := SPECIFIC_ERROR,
errornumber := TSI#alarmNumber,
nextcommand := IMMEDIATELY);
er

END_CASE;
END_IF; // END_IF DriveAxis

END_PROGRAM
ez

END_IMPLEMENTATION
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 29 Solutions
Exercise 6.3: Integrating automatic mode in OB_Main (1)

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 30 Solutions
Exercise 6.3: Integrating automatic mode in OB_Main (2)

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 31 Solutions
Exercise 6.3: Integrating automatic mode in OB_Main (3)

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 32 Solutions
Exercise 6.4: Integrating automatic mode with "RunAuto"

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 33 Solutions
Exercise 7.1: Start of synchronization "StartGearing"

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 34 Solutions
Exercise 7.1: Start of synchronization "Cutting"

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 35 Solutions
Exercise 7.2: Configuring the Alarm_S message

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 36 Solutions
Exercise 7.3: Integrating the output cam (1)

RunAuto

om
l.c
ai
gm
@
er

Switch on output cam


ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 37 Solutions
Exercise 7.3: Integrating the output cam

OB_Main: Output of output cam signal and deactivation


of output cam

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 38 Solutions
Exercise 8.2: The "Cam_Unit" UNIT

UNIT Cam_Unit;
INTERFACE
USEPACKAGE CAM;

om
TYPE Interpolation point: STRUCT
X_pos : LREAL;
Y_pos : LREAL;
END_STRUCT;
END_TYPE
FUNCTION Create_Cam;

l.c
END_INTERFACE

IMPLEMENTATION

ai
FUNCTION Create_Cam : VOID
VAR_INPUT
Interpolation points: ARRAY[0..9] OF interpolation point;
IPO_Type: enumcaminterpolationmode;
CAM_Type: enumcammode;
Cam: CamType;
END_VAR

VAR
gm
index : INT;
@
Error_number : DINT;
END_VAR

Error number := _resetCam(


Cam := Cam); // Specification of the cam
er

FOR index := 0 TO 9 BY 1 DO

Error_number := _addPointToCam(
ez

cam := Cam), //Specification from input parameter


ie

camPositionMode := ACTUAL, //Scaled, offset range


leadingRangePosition := Interpolation points[index].X_pos,
followingRangePosition := Interpolation
points[index].Y_pos);
r.s

END_FOR;

Error_number := _interpolateCam(
cam := cam, //Specification of the cam
camPositionMode := ACTUAL, //Scaled range
ne

leadingrangestartpointtype := LEADING_RANGE_START,
// From starting point
leadingRangeStartPoint := 0.0, //Start value
leadingrangeendpointtype := LEADING_RANGE_END,
// From end point
leadingRangeEndPoint := 100.0, //End value
ca

camMode := CAM_Type,
interpolationMode := IPO_Type);

END_FUNCTION

END_IMPLEMENTATION
r

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 39 Solutions
Exercise 8.2: The call in "Test_Cam"

Unit "Test"

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 40 Solutions
Exercise 8.2: Creating the cam in "Test_Cam"

1. Select "Test"

om
3. Enter inter-
polation points

l.c
2. Open the symbol
browser

ai
gm 4. Interpolation points
@
"Control"
er

5. Call FC with
%I1.7
ez

5. Upload "My_Cam"
to CamEdit
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 41 Solutions
Exercise 9.1: The "Cut2" program

om
l.c
ai
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 42 Solutions
Communication with SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Communication networks in TIA ........................................................................................................ 3
Communication services for SIMOTION ........................................................................................... 4
er

How communication works ............................................................................................................... 5


Packing data in ARRAY OF BYTES .................................................................................................. 6
Unpacking data from ARRAY OF BYTES .......................................................................................... 7
ez

Using the _sizeof() system function to pack data .............................................................................. 8


Using the _sizeof() system function to unpack data ......................................................................... 9
Setting, resetting, and toggling bits in bit data types ......................................................................... 10
Combining 8 bits in a byte .................................................................................................................. 11
r.s

Reading the states of individual bits from bit data types ................................................................... 12
Splitting a byte into 8 bits ................................................................................................................... 13
_Xsend(), _Xreceive() (S7 basic communication) ............................................................................. 14
Sending data via PROFIBUS/MPI: _Xsend() ..................................................................................... 15
ne

Receiving data via PROFIBUS/MPI: _Xreceive() .............................................................................. 16


Determining the status of an X job: _GetStateOfXCommand() ......................................................... 17
Communication via Industrial Ethernet .............................................................................................. 18
The TCP/IP protocol family ................................................................................................................ 19
ca

Communication via UDP (User Datagram Protocol) ......................................................................... 20


IP addresses and IP classes ............................................................................................................. 21
Sending data via UDP: _udpSend() ................................................................................................... 22
Receiving data via UDP: _udpReceive() ........................................................................................... 23
Communication via TCP (Transmission Control Protocol) ................................................................ 24
How communication works with TCP ................................................................................................ 25
Timeout behavior with TCP/IP ........................................................................................................... 26

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 Communication with SIMOTION
Communication with SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.2
SITRAIN Training for
Automation and Drives
@
Contents Page
Opening the communication port on the server side: _tcpOpenServer() ........................................... 27
Starting a connection request on the client side: _tcpOpenClient() .................................................. 28
er

Sending data via TCP: _tcpSend() ..................................................................................................... 29


Receiving data via TCP: _tcpReceive() ............................................................................................. 30
Closing the TCP connection: _tcpClose Connection(), closing the server: _tcpCloseServer() .......... 31
ez

Example: Sending and receiving with UDP (1) .................................................................................. 32


Example: Sending and receiving with UDP (2) .................................................................................. 33
Example: Sending and receiving with UDP (3) .................................................................................. 34
Example: Sending and receiving with UDP (4) .................................................................................. 35
r.s

Example: Sending and receiving with UDP (5) .................................................................................. 36


Example: Sending and receiving with TCP (1) .................................................................................. 37
Example: Sending and receiving with TCP (2) .................................................................................. 38
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 Communication with SIMOTION
Communication networks in TIA

Shared use of HMI

om
Shared communication:
PROFIBUS, PROFINET, Ethernet

C230-2/C240

l.c
P350-3
D4x5/D410

ai
Shared use of
distributed I/Os and

SIMOTION
drives via PROFIBUS
and PROFINET

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.3
SITRAIN Training for
Automation and Drives
@
PROFIBUS PROFIBUS is the network for the cell and field level in the open, multi-vendor
communication system of SIMOTION and SIMATIC. It is used to transfer small
to medium data volumes. PROFIBUS is implemented as an electrical network
based on a shielded two-wire line, as an optical network based on a fiber-optic
er

cable, or as a wireless network using infrared technology.


PROFIBUS is available in different variants depending on the application. The
technology distinguishes between RS 485/fiber-optic cables and the method
based on IEC 1158-2. PROFIBUS PA hasm been designed specifically for use
ez

in explosion-protected applications on ethe basis of its electrical properties.


Industrial Ethernet Industrial Ethernet is a subnet fosr the control level and cell level for
communication between co mputers and automation systems. It is designed for
the exchange of large data volumes and can be used for long-distance
r.s

communication. Ethernet @is implemented as an electrical network based on a


shielded coaxial or tw isted-pair cable or as an optical network based on a fiber-
optic cable.

The CSMA/CD alccess method is used. Before sending data, each station
ne

checks whether data is being transmitted by other stations. If not, it can send the
data immediately. If a collision occurs due to data being transmitted
simultaneously, both stations abort and repeat transmission after a random wait
time. Thlis access method means that all stations on the Industrial Ethernet
have equal priority.
ca

PROFINET PROFINET is the innovative and open Industrial Ethernet standard (IEC 61158)
for industrial automation. With PROFINET, devices can be linked from field level
through to management level.
In conjunction with the IRT protocol (Isochronous Real Time), PROFINET can
be used to control drives isochronously and for non-time-critical communication
(e.g. TCP/IP) between automation components via a single cable.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 Communication with SIMOTION
Communication services for SIMOTION

Communication using _Xsend/_Xreceive


SINAMICS

SINAMICS
Program-controlled
via MPI or PROFIBUS
MPI=2

om
up to 200 bytes
SIMOTION/SIMATIC

SIMOTION

Communication using _udpSend/_udpReceive and

l.c
_tcpSend/ _tcpReceive
SINAMICS

SINAMICS

Program-controlled

ai
via Industrial Ethernet
MPI=2
up to 1,400/4,096 bytes
SIMOTION/SIMATIC/PC

SIMOTION
SIMOTION

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.4
SITRAIN Training for
Automation and Drives
@
_Xsend/_Xreceive The _Xsend() and _Xreceive() functions support the transparent transfer of data
packets via PROFIBUS or MPI. Data transfer is coordinated at both ends: the
user program on the client is responsible for sending the data and the user
program on the server is responsible for receiving the data.
er

The program on the receiving device recognizes whether it is the data packet to
be received on the basis of a user-definable integer (job identifier) appended to
the data packet. Moreover, data exchange is only successful if the user program
accepts and does not reject the data packet.
ez

Data is sent in the form of byte sequences in an array, i.e. the data has no
logical structure. SIMOTION devices can send or receive up to 200 bytes at
once; the actual user data length depends on the communications partner.
A SIMATIC station, for example, restricts the user data length to 76 bytes.
r.s

_udpSend/ These functions support simple data transfer across different networks
_udpReceive without acknowledgment (datagram service) according to layer 4 of the ISO
reference model. Contiguous data blocks with a maximum size of 1,400 bytes
can be transferred between two Ethernet stations based on IP. (UDP = User
Datagram Protocol.)
ne

The UDP service enables communication with any communications partner (e.g.
PC or third-party system) supporting UDP send/receive. UDP telegrams are not
secure because the receipt of data is not acknowledged. However, UDP is
mainly used in applications which work on the principle of user
ca

acknowledgment.

_tcpSend/ The function sends and receives a TCP data stream (Transmission Control
_tcpReceive Protocol). Contrasting with the UDP protocol, internal acknowledgment
mechanisms are used together with a retransmission function to ensure that lost
data packets can be processed, thereby making data communication secure.
Data transmission with UDP and TCP is exclusively performed via Industrial
Ethernet and additionally via TCP/IP networks (e.g. telephone network or
Internet).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 Communication with SIMOTION
How communication works
Sender:
1. Pack data in ARRAY OF BYTES
Task „ AnyType_to_BigByteArray (to SIMATIC, Motorola, SUN, etc.)
„ AnyType_to_LittleByteArray (to PC, DEC Alpha, etc.)
Solution with OPC

om
2. Send data
„ _Xsend(...) or _udpSend(...), _tcpSend

Receiver:

l.c
1. Receive data
„ _Xreceive(...) or _udpReceive(...), tcpReceive

ai
2. Unpack data from ARRAY OF BYTES
„ BigByteArray_to_AnyType (from SIMATIC, Motorola, SUN, etc.)

SIMOTION
Siemens AG 2013. All rights reserved.
„
gm
LittleByteArray_to_AnyType (from PC, DEC Alpha, etc.)

Date:
File:
10.01.2013
MC-SMO-PRG_A1.5
SITRAIN Training for
Automation and Drives
@
Procedure for The procedure for sending is essentially divided into the following two steps:
sending
• Packing the transmit data in an ARRAY OF BYTES (byte stream)
er

The data to be sent is usually stored in a set of variables with different


data types. These variables must be copied ("packed") in an array of bytes
before they are actually sent. In the "packing operation", the byte order (Little
Endian, Big Endian) of the receiver should be considered in order to keep the
effort involved in "unpacking" the data to a minimum.
ez

Depending on the byte order of the receiver:


- Big Endian", i.e. the higher-order byte is stored at the higher address,
e.g. as on SIMATIC S5, SIMATIC S7, Motorola, etc.
- "Little Endian", i.e. the higher-order byte is stored at the lower address,
r.s

e.g. as on PCs with Intel processors etc.


the variables to be sent are "packed" in a byte array using:
- AnyType_to_BigArray()
- AnyType_to_LittleArray().
ne

• The byte array is then sent to the receiver using the corresponding system
functions.

Procedure for The procedure for receiving data transmitted by any sender follows the reverse
ca

receiving order:
• The corresponding receive functions are used to receive the data from the
the target system and store the data in an ARRAY OF BYTES.
• The SIMOTION user program then has to unpack the individual information
units from this "byte stream". Depending on the byte
order of the sender, this is done using:
- BigByteArray_to_AnyType()
- LittleByteArray_to_AnyType()

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 Communication with SIMOTION
Packing data in ARRAY OF BYTES

Data_Send: ARRAY[0..N] OF BYTES (e.g. N = 1399)

Address: 0 Data_Send := ANYTYPE_TO_LITTLEBYTEARRAY(


Task 1 anydata := Axis_1.positioningstate.commandposition,
2 offset:=0)
Solution with OPC 3

om
Axis_1.positioningstate.commandposition
4
5
Data type: LREAL, i.e. 8 bytes
6 .
7 .
. .
.

l.c
n Data_Send := ANYTYPE_TO_LITTLEBYTEARRAY(
anydata := Axis_2.positioningstate,
n+1
offset:=n)
n+2
n+3

ai
Axis_2.motionstatedata
n+.
n+.
Data type: STRUCT
n+. (has a total of 44 bytes)

SIMOTION
n + 43

N
.

Siemens AG 2013. All rights reserved.


gm
Note: "Enum" data type occupies 4 bytes

Date:
File:
10.01.2013
MC-SMO-PRG_A1.6
SITRAIN Training for
Automation and Drives
@
Overview The following functions:
• AnyType_to_LittleByteArray()
• AnyType_to_BigByteArray()
er

are used to convert variables of the following data types:


• Elementary data types, e.g. BOOL, INT, REAL, LREAL, etc.
• User-defined data types: ARRAYs, STRUCT, ENUMERATORs
ez

• Standard data types of technology packages and devices


An optional constant offset (default = 0) can be specified in addition to the
variables to be converted. The offset is the array index of the first element to be
stored in the array.
It must fall within the array limits. These functions are available in SIMOTION
r.s

Kernel Version V2.1 and higher.

Notes • Each variable of the BOOL data type (including variables that are
components within a structured data type) occupies one byte in the byte
ne

array. The value FALSE is mapped to 16#00, the value TRUE to 16#01.
• When enumerator data types ("Enum") are converted, a warning:
"Data type Enum is not portable when converted" is output. Enumerator data
types are stored internally as UDINT and thus occupy 4 bytes in the byte
array.
ca

• When an ST source file is compiled, a check is made to determine whether


the offset falls within the array limits and whether the variable can be
mapped in full in the byte array (between the offset and the upper array
limit).
If not, error message "6036 Constant value is outside the definition range ..."
is output.
• Only those byte array elements that are covered by variables to be
converted are occupied by values. Other elements of the byte array remain
unchanged.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 Communication with SIMOTION
Unpacking data from ARRAY OF BYTES
Data_Received : ARRAY[0..N] OF BYTES; // (e.g. N = 1399)
MyPosition, MyVelocity : LREAL;

Address: 0 MyPosition := LITTLEBYTEARRAY_TO_ ANYTYPE (


Task 1 bytearray := Data_Received,
2 offset:=0)
Solution with OPC 3

om
MyPosition Data type: LREAL, i.e. 8 bytes
4
5
6 .
7 .
. .
.

l.c
n MyVelocity := LITTLEBYTEARRAY_TO_ ANYTYPE (
bytearray := MyVelocity,
n+1
offset:=n)
n+2
n+3

ai
MyVelocity Data type: LREAL, i.e. 8 bytes
n+4
n+5
n+6

SIMOTION
n+7
.
N

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.7
SITRAIN Training for
Automation and Drives
@
Overview The following functions:
• LittleByteArray_to_AnyType()
• BigByteArray_to_AnyType()
er

convert a byte array to a variable of any data type (elementary data types,
system data types, user-defined data types).
The array index of the first element to be evaluated in the array is an optional
constant offset (default = 0). It must fall within the array limits.
ez

Notes • When an ST source file is compiled, a check is made to determine whether


the offset falls within the array limits and whether the byte array (between the
offset and the upper array limit) completely covers the variable.
r.s

Otherwise, a corresponding error message is output.


• One byte from the byte array is assigned to a variable of data type BOOL
(including variables that are components within a structured data type).
The value of the assigned variable is FALSE if the byte contains the value
16#00 and TRUE if the value is not equal to 16#00.
ne

• 4 bytes from the byte array are assigned to an enumerator variable ("Enum"
data type). If the value (as UDINT) is outside the valid value range, this
(invalid) value is assigned to the variable.
In this case, an error message is not output. The user is responsible for the
ca

validity of the values in conversions of this type.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 Communication with SIMOTION
Using the _sizeof() system function to pack data

„ If sender and receiver are both SIMOTION devices


1. Define data structure of send data
TYPE
Task
MyDataStruct : STRUCT
Position : LREAL;
Solution with OPC Velocity : LREAL;

om
. . .
END_STRUCT;
END_TYPE

2. Create user variable and send buffer with _sizeof()


VAR_GLOBAL

l.c
MySendData : MyDataStruct;
DataSend : ARRAY[0.._sizeof(in := MyDataStruct) -1] OF BYTE;
END_VAR

ai
3. Copy process variable to user variable and pack user variable in send buffer
MySendData.Position := Axis_1.positioningstate.commandposition;
MySendData.Velocity := Axis_1.motionstatedata.commandvelocity;

SIMOTION
. . .

Siemens AG 2013. All rights reserved.


gm
DataSend := ANYTYPE_TO_LITTLEBYTEARRAY(anydata := MySendData, offset:=0);

Date:
File:
10.01.2013
MC-SMO-PRG_A1.8
SITRAIN Training for
Automation and Drives
@
Overview The example above demonstrates the packing of send data with the "system
function" _sizeof(), which is available as of V4.0. This procedure is
recommended if:
• Data is to be transferred between two SIMOTION devices and
er

• The programmer wants to avoid possible errors caused by:


- The memory requirements of indimvidual data types or
- Areas of the send buffer being overwritten during the individual stages
of the packing process due to incoerrect offsets being specified in
ez

ANYTYPE_TO_LITTLEBYTiEARRAY() functions, etc., for example.

It is not recommended for transfesrring data between a SIMOTION device and


a non-SIMOTION device (a PC, a SIMATIC, etc.). The reason for this is the
r.s

undocumented alignment @of the individual elements within a structure.


The procedure for pack ing data is as follows:
Procedure
1. First, a data struucture with the data elements to be sent must be
created in the TYPE sectiongl. Essentially, the order and the types of the
individual data elements are defined in this structure.
ne

2. Next, ao user variable of the same type as the structure created and a
send buffeelr (as ARRAY[0.._sizeof(..)-1]) must be created in the VAR section.
The size of the data structure can be identified by running the _sizeof() function
and used to specify the max. array index when declaring the send buffer.
3. It is only after this that the process variables to be sent are copied to the
ca

user variable and then the packing function is called to copy the user variable to
the send buffer. 0 must be specified as the offset.
With this procedure, neither the memory requirements of the individual data
types nor the total size of a structure are relevant. The _sizeof() function can also
be used in the send function (e.g. _udpsend()) to specify the number of bytes to
be sent.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 Communication with SIMOTION
Using the _sizeof() system function to unpack data

„ If sender and receiver are both SIMOTION devices


1. Define the data structure of the receive data (must be the same as the send data)
TYPE
Task
MyDataStruct : STRUCT
Position : LREAL;
Solution with OPC Velocity : LREAL;

om
. . .
END_STRUCT;
END_TYPE

2. Create user variable and receive buffer with _sizeof()


VAR_GLOBAL

l.c
MyReceivedData : MyDataStruct;
DataReceived : ARRAY[0.._sizeof(in := MyDataStruct) -1] OF BYTE;
END_VAR

ai
3. Unpack receive buffer in user variable
MyReceivedData := LITTLEBYTEARRAY_TO ANYTYPE( anydata := DataReceived,
offset:=0);

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.9
SITRAIN Training for
Automation and Drives
@
Procedure The procedure for unpacking data is as follows:
1. First, a data structure with the data elements to be received must be
created in the TYPE section. Essentially, the order and the types of the
individual data elements are defined in this structure.
er

The order and type must be the same as in the data structure to be sent.
2. Next, a user variable of the same type as the structure created and a
receive buffer (as ARRAY[0.._sizeof(..)-1]) are created in the VAR section. The
size of the data structure can be identified by running the _sizeof() function and
used to specify the max. array indeex when declaring the receive buffer. With
ez

this procedure, the receive buffer and the send buffer are always the same size.
3. After this, following data receipt (e.g. _udpreceive()), the data from the
receive buffer is copied to the user variable by calling the unpack function. The
data is then a vailable there for further processing.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 Communication with SIMOTION
Setting, resetting, and toggling bits in bit data types

MyAnyBit := _setbit( //Set bit


in:= MyAnyBit, Set bit in byte, word,
n:= BitNo, or double word
value:= TRUE);
Task

Solution with OPC MyAnyBit := _setbit( //Reset bit

om
in:= MyAnyBit, Reset bit in byte, word,
n:= BitNo, or double word
value:= FALSE);

MyAnyBit := _togglebit(//Toggle bit Toggle bit in byte, word,


in:= MyAnyBit,

l.c
n:= BitNo); or double word

Example: MyByte : BYTE;

ai
X
MyByte := _setbit(MyByte, 5, TRUE)

SIMOTION
7 6

Siemens AG 2013. All rights reserved.


1
5 4 3 2 1 0 gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.10
SITRAIN Training for
Automation and Drives
@
Overview In the context of communication functions, it is not usual for every item of bit
information to be saved and transmitted in an associated Boolean variable.
Instead, individual bits are initially combined in BYTE, WORD, or DWORD
variables.
er

The following functions can be used to modify an individual bit within a bit string
variable (data type: BYTE, WORD, DWORD). The return value is the value of
the modified bit string variable "in".
If the data type of the "in" input parameter (e.g. DWORD) cannot be converted
ez

to the data type of the return value (e.g. BYTE), a corresponding error message
is output during compilation.
The value for the bit number "n" should be within the valid range. The valid
ranges are:
r.s

• [0..7] for BYTE


• [0..15] for WORD
• [0..31] for DWORD
If illegal values are specified (without an additional error message), the
ne

unchanged value of the bit string variable is returned.


For direct modification of the bit string variable, the return value can be
reassigned to it (see the above slide).

_setbit This function returns the value of the bit string variable "in", in which the bit
ca

specified in "n" has been set to the defined Boolean value ("value" := TRUE or
FALSE).

_togglebit This function returns the value of the bit string variable "in", in which the bit
specified in "n" has been inverted..

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 Communication with SIMOTION
Combining 8 bits in a byte
VAR
MyByte : BYTE;
MyBit0, MyBit1, MyBit2, MyBit3 : BOOL;
END_VAR
Task
MyByte := _byte_from_8bool( // Combine 8 bits in a byte
Solution with OPC bit0 := MyBit0,

om
bit1 := MyBit1,
bit2 := MyBit2,
bit3 := MyBit3,
bit4 := Axis_1.error = YES,
bit5 := Achse_2.error = YES,
bit6 := Axis_1.motionstatedata.motionstate <> STANDSTILL,
bit7 := Axis_2.motionstatedata.motionstate <> STANDSTILL);

l.c
// With language extension

MyByte.0 := MyBit0;

ai
.
MyByte.4 := Axis_1.error = YES;

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.11
SITRAIN Training for
Automation and Drives
@
_byte_from_8bool The system function _byte_from_8bool() is used to combine eight Boolean
variables or expressions in a byte. The Boolean value TRUE is then equivalent
to the bit state "1" and the value FALSE to the bit state "0".
er

Direct bit access The "Permit language extensions" option in the compiler settings provides a
user-friendly means of accessing individual bits in a bit string data type (BYTE,
WORD, or DWORD, for example).
The number of the bit to be accessed can be entered after the name of the
ez

variable, separated by a period. The variable must be a BYTE, WORD, or


DWORD type variable. In this case, the number of the bit can only be specified
via a constant.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 Communication with SIMOTION
Reading the states of individual bits from bit data types

„ Read out bit from byte, word, or double word:


VAR
Task MyResult : BOOL;
MyAnyBit : BYTE; //or WORD, DWORD
BitNo : UINT; // Bit number
Solution with OPC

om
END_VAR

MyResult := _getbit( //Read out bit state


in:= MyAnyBit,
n:= BitNo);

l.c
MyAnyBit

1 MyResult := _getbit(MyAnyBit, 5)

ai
7 6 5 4 3 2 1 0 returns MyResult equals TRUE

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.12
SITRAIN Training for
Automation and Drives
@
_getbit(..) The _getbit() function returns the value of the bit specified in "n" from bit string
variable "in" (data type: BOOL). The bit state "1" is equivalent to the return value
TRUE, the state "0" is equivalent to FALSE.
The value for the bit number "n" should be within the valid range. The valid
er

ranges are:
• [0..7] for BYTE
• [0..15] for WORD
ez

• [0..31] for DWORD


If the value is outside the valid range, the value FALSE is returned (without an
additional error message).
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 Communication with SIMOTION
Splitting a byte into 8 bits

VAR
MyByte : BYTE;
MyBit0, MyBit1, MyBit2, MyBit3, MyBit4, MyBit5, MyBit8, MyBit7 : BOOL;
Task MyByteToBool : _byte_to_8bool;
END_VAR
MyBytetoBool (bytein := MyByte); // Split a byte into 8 bits
Solution with OPC

om
// MyByte is the input byte
MyBit0 := MyBytetoBool.bit0; // Assign 8 outputs
MyBit1 := MyBytetoBool.bit1;
MyBit2 := MyBytetoBool.bit2;
.
.

l.c
.

MyBit0 := MyByte.0; // Read out bit state


MyBit1 := MyByte.1; // with language extension
MyBit2 := MyByte.2

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.13
SITRAIN Training for
Automation and Drives
@
_byte_to_8bool System function block _byte_to_8_bool() is used to split a variable or expression
of the BYTE data type into eight individual Boolean variables. The bit state "1" is
then equivalent to the value TRUE and the state "0" is equivalent to FALSE.
An instance must be created in the declaration part in order to use the system
er

function block. The actual instance name is then used in the call.

Direct bit access The "Permit language extensions" option in the compiler settings provides a
user-friendly means of accessing individual bits in a bit string data type (BYTE,
ez

WORD, or DWORD, for example).


The number of the bit to be accessed can be entered after the name of the
variable, separated by a period. The variable must be a BYTE, WORD, or
DWORD type variable. In this case, the number of the bit can only be specified
r.s

via a constant.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 Communication with SIMOTION
_Xsend(), _Xreceive() (S7 basic communication)

„ Data exchange with other SIMOTION devices via MPI and


PROFIBUS

„ Data exchange with SIMATIC S7 via MPI subnet only:

om
„ User data up to 200 bytes (SIMOTION) or 76 bytes (SIMATIC S7)

„ The connection to the partner is set up and terminated


dynamically

l.c
„ Job tracking is possible

„ No connection configuration, i.e. communications partners can

ai
be in different S7 projects

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.14
SITRAIN Training for
Automation and Drives
@
Overview The system functions _Xsend() and _Xreceive() are used to exchange small
data volumes between SIMOTION devices and between SIMOTION and an
S7/M7-300/400 CPU respectively.
The communications partners must be connected to the same PROFIBUS or
er

MPI subnetwork. Routing via routers is not supported.

User data size Communication between SIMOTION and an S7/M7-300/400 CPU module is
only possible via an MPI subnet. In this case, the data volume per call is
ez

restricted to 76 bytes. For communication between SIMOTION devices (C2xx,


P3xx or D4xx), the upper limit is 200 bytes per call.
The sent data is in the form of byte sequences in an array, i.e. the data has no
logical structure.
r.s

Connections When a communication function is called, a connection to the addressed partner


is opened and closed again dynamically when data transfer is complete
according to the parameterization (communicationmode parameter). To set up
the connection, one unreserved connection resource is required on each of the
ne

communications partners.
The partner is addressed by specifying the address directly in the call.
Therefore, no connection configuration is necessary (i.e. communications
partners can be located in different S7 projects).
ca

Job identifier The program on the receiving device recognizes whether it is the data packet to
be received on the basis of a user-definable integer appended to the data
packet.

Job tracking The status of an Xsend or Xreceive job can be checked with the command
GetStateOfXCommand().

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 Communication with SIMOTION
Sending data via PROFIBUS/MPI: _Xsend()
Send data
RetVal := _Xsend(
communicationmode, // ABORT_CONNECTION or HOLD_CONNECTION
address, // StructXsendDestAddr
messageid, // Job identifier (UDINT)
nextcommand, // IMMEDIATELY or WHEN_COMMAND_DONE

om
commandid, // Command identification
data, // ARRAY[0..199] OF BYTE for send data
datalength); // Number of bytes (UDINT)

StructXsendDestAdddr

l.c
StructXsendDestAddr STRUCT
deviceId; // (USINT)1:X8,X101,X126 2:X9,X102,X136
remoteSubnetIdLength; // (USINT) Always 0 for PROFIBUS and MPI
remoteStaddrLength; // (USINT) Always 1 for PROFIBUS and MPI

ai
nextStaddrLength; // (USINT) Always 0 for PROFIBUS and MPI
remoteSubnetId; // (ARRAY[0..5] of USINT) not relevant
remoteStaddr; // (ARRAY[0..5] of USINT), array element
// with index 0 = partner address 0 .. 126

SIMOTION
nextStaddr);
END_STRUCT

Siemens AG 2013. All rights reserved.


//

Date:
File:
gm (ARRAY[0..5] of USINT) not relevant

10.01.2013
MC-SMO-PRG_A1.15
SITRAIN Training for
Automation and Drives
@
Overview The _Xsend() function sends a data packet with transparent data to a
communications partner.

Parameters communicationMode: The connection remains open after data transmission or is


er

closed, i.e. the communication resources are released.


address: This parameter specifies the destination address of the partner. The
parameter has the following data type StructXSendDestAddr:
ez

• deviceId (USINT): Connection terminal


C230-2: 1 for X8, 2 for X9 P350: 1 for X101, 2 for X102
D4x5: 1 for X126, 2 for X136
• remoteSubnetIdLength (USINT) Length of the subnet mask: always 0
r.s

• remoteStaddrLength (USINT) Length of the station address: always 1


• nextStaddrLength (USINT) Length of the address of the router: always 0
• remoteSubnetId (ARRAY [0..5] OF USINT) Subnet mask (not relevant)
• remoteStaddr (ARRAY [0..5] OF USINT) Station address of the target
ne

system in remoteStaddr[0], the rest is not relevant


• nextStaddr (ARRAY [0..5] OF USINT) Address of the router (not relevant)
messageId: At the job identifier, identifies the recipient of the data
nextCommand: Choice between synchronous (WHEN_COMMAND_DONE) and
asynchronous (IMMEDIATELY) transmission. Synchronous transmission waits
ca

until the receiver acknowledges receipt of the data packet. During asynchronous
data transmission, the program is resumed immediately after the command is
issued. The status can be determined with _GetStateOfXCommand.
commandId: Needed for _GetStateOfXCommand().
data (ARRAY[0..199] OF BYTES): Contains the data to be sent.
dataLength: Specifies the number of bytes to be sent from data.
Return value: The return value indicates whether the call was successful
(RetVal = 0) or unsuccessful (RetVal < 0).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 Communication with SIMOTION
Receiving data via PROFIBUS/MPI: _Xreceive()
Receive data
RetStructRetXreceive := _Xreceive(
messageId, // (UDINT) Job identifier
nextcommand, // IMMEDIATELY or WHEN_COMMAND_DONE
commandid); // Command identification

StructRetXreceive

om
StructRetXreceive STRUCT
functionResult; // (DINT) Result of call
dataLength; // (UDINT) Number of bytes received
data; // (ARRAY[0..199] OF BYTES) Receive data
END_STRUCT

l.c
functionResult indicates the following states:
• Asynchronous start:
16#00007000 Job is still active

ai
16#000000xx Job is complete. Number of received bytes in xx (also in "datalength")
16#000080xx Job was aborted with errors. xx reports a unique error number.
• Synchronous call:
16#000000xx Execution was completed without errors (xx length of data). Number of

SIMOTION
received bytes also in "dataLength"

Siemens AG 2013. All rights reserved.


gm
16#000080xx Job was aborted with errors. xx reports a unique error number.

Date:
File:
10.01.2013
MC-SMO-PRG_A1.16
SITRAIN Training for
Automation and Drives
@
Overview The _Xreceive() function receives the data sent by a communications partner
with _Xsend().

Parameters messageId: The Xreceive call uses this job identifier to identify a data packet
er

intended for it. An Xreceive call only receives data packets in which the job
identifier (messageid parameter) added by the sender in the Xsend call matches
the job identifier of the Xreceive call.
Data packets with different job identifiers are not accepted by an Xreceive call.
ez

nextCommand: As with _Xsend(), you can choose between synchronous


(WHEN_COMMAND_DONE) and asynchronous (IMMEDIATELY) data
transmission.
In synchronous data transmission, the program waits until a valid data packet
r.s

(same messageid in Xsend() and Xreceive()) is received. The system then


automatically acknowledges receipt to the sender.
During asynchronous data transmission, the program is resumed immediately
after the command is issued. You can call _GetStateOfXCommand() to
determine the status of command execution.
ne

commandId: Needed for _GetStateOfXCommand().


Return value: The parameter has the data type StructRetXreceive:
• functionResult : functionResult indicates whether or not command execution
was successful (0: successful, <> 0: error).
ca

• dataLength: Indicates the number of bytes received.


• data: Receive buffer for data received (max ARRAY[0..199] OF BYTE).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 Communication with SIMOTION
Determining the status of an X job: _GetStateOfXCommand()

Determine status of an X_job


RetStructRetXCommandState := _GetStateOfXCommand(
commandid); // Command identification

om
StructRetXCommandState
StructRetXCommandState STRUCT
functionResult; // (DINT) Result of call
commandIdState; // ACTIVE, NOT_EXISTENT, WAITING
END_STRUCT

l.c
CommandIdState indicates the following states:
• ACTIVE: The job is currently underway (asynchronous command).

ai
• NOT_EXISTENT: The job is already complete or does not exist yet.
• WAITING: The job is waiting for data (synchronous command).

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.17
SITRAIN Training for
Automation and Drives
@
Overview The _GetStateOfXCommand() function is used to scan the command execution
status of an _Xsend or _Xreceive job.
commandId: Used to identify the Xsend or Xreceive job whose status is to be
Parameters determined.
er

Return value The parameter is of data type SteructRetXCommandState:

• functionResult: functionResult indicatesm whether or not command


execution of _getStateOfXcommand was successful (0: successful, <> 0: error).
ez

The commandIdState parameter only reeturns the valid status if execution was
successful.
• commandIdState: If executsion was successful, the command execution
status of the Xsend or Xreceive job identified by commandId is stored here.
r.s

Possible values are:


ACTIVE: The job is currently underway (asynchronous command).
NOT_EXISTENT: The job is already complete or does not exist yet.
WAITING: Job execution has not yet commenced (synchronous
ne

command).
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 Communication with SIMOTION
Communication via Industrial Ethernet

„ Industrial Ethernet is a standard- based network


„ Ethernet standard to IEEE 802.3(u)
„ Designed for industry (ITP, industry-compatible TP, network
components, redundancy, throughput, etc.)

om
„ Bus system suitable for use in distributed automation
solutions

„ Standard communication protocols on Ethernet


(the most important are):

l.c
„ Internet Protocol (IP)
„ Transmission Control Protocol (TCP)
„ User Datagram Protocol (UDP)

ai
„ Flexible addressing

SIMOTION
„

„
IP addresses
Port numbers

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.18
SITRAIN Training for
Automation and Drives
@
Industrial Ethernet Industrial Ethernet is a high-performance network for the control and cell levels
based on the IEEE 802.3 (ETHERNET) standard. With a current market share
of over 80%, Ethernet is number one worldwide in today's network landscape.
Ethernet has important features that can mean significant benefits for your
er

application:
• Fast commissioning thanks to a really straightforward connection method
• High availability since existing networks can be extended without any
adverse effects
ez

• Virtually unlimited communication capabilities, since scalable performance


using switching technology is available if required
• Networking of different areas of application such as office and production
• Company-wide communication thanks to to interface options based on WAN
r.s

(Wide Area Network) technology such as ISDN or the Internet


• Information security thanks to ongoing compatible further development
The new technology of the Internet is opening up a whole range of possibilities
for worldwide networking.
ne

TCP/IP TCP/IP (Transmission Control Protocol/Internet Protocol) is a set of network


protocol family protocols based on the Internet. The main TCP/IP protocols are listed below:
• IP: Internet Protocol
ca

• TCP: Transmission Control Protocol


• UDP: User Datagram Protocol
• ARP: Address Resolution Protocol
• ICMP: Internet Control Message Protocol

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 Communication with SIMOTION
The TCP/IP protocol family

FTP NFS
SMTP rlogin Telnet TFTP BOOTP

om
TCP UDP

ICMP

l.c
Internet protocol (IP)
ARP RARP

ai
Network hardware

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.19
SITRAIN Training for
Automation and Drives
@
Network access The lowest layer, the network access layer, matches the OSI layer model to a
layer large extent and provides the basis for data transfer on the network. On this
layer, data is packed into packets and prepared for physical transmission (layer
1 in OSI).
er

A further function of the network access layer is the resolution and conversion of
logical addresses to physical addresses. Under TCP/IP, this is handled by the
Address Resolution Protocol (ARP). Reverse ARP (RARP) is used for the
reverse procedure (conversion from physicmal to logical addresses).
ez

Internet protocol The Internet protocol (IP) providesi the basis for all TCP/IP networks. It creates
what are called datagrams - datas packets prepared specifically for the Internet
protocol - and handles their tr ansport within the local subnet or their forwarding
to other subnets (i.e. routing@).
r.s

The further functions of IP include the fragmentation of datagrams. Data packets


have different maximu m sizes in different subnets. The MTU (Maximum
Transmission Unit)u specifies the maximum packet size in each subnet. At a
transition point tol a network with a smaller packet size, the routers fragment the
packet. The frgagments can then be transported to the destination across
ne

different routeso.

TCP TCP ise the transport protocol used to exchange data between two hosts. Data
is referred to as segments in TCP jargon. TCP ensures a high level of security,
kbecause data sent across the network has to be acknowledged by the
ca

receiver. If acknowledgment is not received, the segment is sent again after a


configurable wait period.

The User Datagram Protocol (UDP) is a simple connection-free protocol. UDP


UDP guarantees neither that the datagrams will reach the intended recipient nor that
they will be transmitted in the correct order. UDP is used primarily in high-
performance applications (IP radio, IP video).

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 Communication with SIMOTION
Communication via UDP (User Datagram Protocol)

„ Properties
„ No protection against loss of packet content or sequence
„ Ideal for real-time applications in automation
„ Flexible addressing based on IP addresses and ports

om
„ Sending of multicast message frames
SINAMICS

SINAMICS

Port: 3333

... Port: 2222

l.c
Application_1

Application_n

SIMOTION

ai
IP address: 169.254.11.22 IP address: 169.254.11.20

..Source Dest. Source Dest.


IP addr. … IP addr. ... port … port ... Data

SIMOTION
Siemens AG 2013. All rights reserved.
IP header

Date:
File:
gm
UDP header

10.01.2013
MC-SMO-PRG_A1.20
SITRAIN Training for
Automation and Drives
@
Overview The User Datagram Protocol (UDP) is a simple connection-free protocol. UDP
was defined in order to provide application processes with a direct means of
sending data packets and thus to meet the needs of transaction-oriented traffic.
UDP resides immediately above the IP layer, on which it is based.
er

Properties UDP has a minimalist protocol mechanism. It saeves protocol overhead


of UDP and thus supports higher transfer rates than TCP. No mechanisms are needed
for opening and closing the connection.
However, the transfer of data packets in the network is not safeguarded, i.e. no
ez

automatic retransmission takes place - unlike TCP - if packets are lost. This
makes UDP suitable for real-time applications where the application implements
(indeed has to implement) altesrnative measures in the event of an error such
as packet loss, a connection fault, failure of the communications partner, etc. An
optional checksum can be used to detect data transmission errors.
r.s

A further advantage UDP has over TCP is its support of "broadcast message
frames", which allow data to be sent to multiple nodes in a single call.

The same method las for TCP/IP connections is used for the addressing of UDP
packets. Twog tuples consisting of the IP address and port number represent
ne

Addressing
the end points oof a TCP connection.

The IP laddress is ultimately used to address the destination partner. The IP


address is subdivided into a network address and a host address. Within the
destination partner, 16-bit integer port numbers are used to address the
ca

application.

In SIMOTION, ports with numbers greater than 2000 can be used freely. Ports
Note with numbers less than or equal to 2000 (well-known ports) should not be used
in the user program.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 Communication with SIMOTION
IP addresses and IP classes

Class A: Valid range #Networks #Host

0 7 bits network 24 bits host 1 to 126 126 16777214

Subnet mask: 255.0.0.0

om
Class B:
10 14 bits network 16 bits host 128 to 191 16384 65534

Subnet mask: 255.255.0.0

l.c
Class C:
110 21 bits network 8 bits host

ai
192 to 223 2097152 254

Subnet mask: 255.255.255.0

SIMOTION
Note: The numbers 0 and 127 are reserved.

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.21
SITRAIN Training for
Automation and Drives
@
IP addresses Each access point for a device on a network is identified by its address. The IP
address is used on TCP/IP networks. It comprises 4 bytes and is structured
according to certain rules, e.g.:
192.168.42.1. (dot notation)
er

In dot notation, each IP address is expressed by four decimal numbers between


0 and 255, separated by dots.
IP addresses have two parts: the network ID and the host ID. The network ID
ez

specifies the subnet to which the host is connected; the host ID specifies the
address of the access point for the host.

IP Classes The subdivision of an IP address into a subnet and host breaks the IP network
down into a large collection of interconnected subnets. 5 classes were originally
r.s

defined; however, only the following classes are used: A, B, and C.

Subnet mask A subnet mask is a filter used to identify all systems connected to the same
physical network section.
The rules for the subnet mask are very simple:
ne

• Ones in the subnet mask identify the number part of the subnet
• Zeros identify the part of the address used for the host ID
Even if the subnet masks are not used, the hardware automatically defines the
default subnet mask for class A, B, or C.
ca

Note If send and receive stations are connected to the same network, or connected
directly by a crossed Ethernet cable, the network ID of both IP addresses must
match.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 Communication with SIMOTION
Sending data via UDP: _udpSend()

Send data
RetVal := _udpSend(
sourcePort, // (UINT) Sender port
destinationAddress, // (ARRAY[0..3] OF USINT) IP addr. receiver

om
destinationPort, // Receiver port
communicationMode, // CLOSE_ON_EXIT, DO_NOT_CLOSE ON_EXIT
dataLength, // Number of bytes (UDINT)
data); // ARRAY[0..1399] OF BYTE for send data

RetVal (DINT) indicates the following states:

l.c
16#00000000 Data sent successfully
16#FFFFFFFF Resource bottleneck
16#FFFFFFFE Port not available
16#FFFFFFFD Internal error

ai
16#FFFFFFFB Error receiving
16#FFFFFFF9 Error sending
16#FFFFFFF8 Incorrect parameter

SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm 10.01.2013
MC-SMO-PRG_A1.22
SITRAIN Training for
Automation and Drives
@
Overview The udpSend(..) function sends a UDP message frame to the receiver identified
by the IP address and port number. Up to 1,400 bytes can be transmitted in one
call. Command execution is always synchronous. The return value can be used
to determine whether or not the call has been successful.
er

sourcePort (UINT): Port number of the sender


Parameters destinationAddress (ARRAY [0..3] OF USImNT): IP address of the receiver
destinationPort (UINT): Port number of the receiver
communicationMode (EnumUdpComemunicationMode): Here you can specify
ez

whether the assigned communsiication resource (socket with port number)


remains open after data trans mission or is closed.

• CLOSE_ON_EXIT: Socket is closed.


r.s

• DO_NOT_CLOSE_ON@_EXIT: Socket remains open.


dataLength (UDINT): Number of user data bytes to be sent. The value can
also be determined withu the _sizeof() function. However, the return value
must be converted from DINT tlo UDINT.
ne

data (ARRAY [0g..1399] OF BYTE): Buffer for the data to be sent (user data
area).
Return vlalue (DINT): The return value indicates whether the call was
successful (RetVeal = 0) or unsuccessful (RetVal < 0). Possible values are:
ca

• 16#00000000: Data sent successfully


• 16#FFFFFFFF Resource bottleneck
• 16#FFFFFFFE Port not available
• 16#FFFFFFFD Internal error
• 16#FFFFFFFB Error receiving
• 16#FFFFFFF9 Error sending
• 16#FFFFFFF8 Incorrect parameterization

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 Communication with SIMOTION
Receiving data via UDP: _udpReceive()
Receive data
RetStructRetUdpReceive :=
_udpreceive(
port, // Receiver port
communicationMode, // CLOSE_ON_EXIT, DO_NOT_CLOSE ON_EXIT
nextCommand, // IMMEDIATELY or WHEN_COMMAND_DONE
receiveVariable); // ARRAY[0..1399] OF BYTES, receive data

om
StructRetUdpReceive
StructRetUdpReceive STRUCT
functionResult; // (DINT) Result of call
sourceAdress; // IP address of sender
sourcePort; // Port number of sender

l.c
dataLength; // (UDINT) Number of bytes received
END_STRUCT

functionResult indicates the following states:

ai
16#00000000 Communication on this port completed without errors 16#FFFFFFFF Resource bottleneck
16#00007001 Communication on this port started 16#FFFFFFFD Internal error
16#00007002 Communication on this port active 16#FFFFFFFC Receive function on this
16#00007003 Communication on this port aborted port already active

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.23
16#FFFFFFFB Error receiving
16#FFFFFFF8 Incorrect parameter

SITRAIN Training for


Automation and Drives
@
Overview The _udpReceive(..) function receives a UDP message frame at a port specified
in a transfer parameter. The command can be executed synchronously or
asynchronously and an active job can be aborted.
er

Parameters port (UINT): Port number of the receiver


communicationMode (EnumUdpCommunicationMode): Here you can specify
whether the assigned communication resource (socket with port number)
remains open after data transmission or is closed.
ez

• CLOSE_ON_EXIT: Socket is closed.


• DO_NOT_CLOSE_ON_EXIT: Socket remains open.
nextCommand (EnumNextCommandMode):
r.s

• IMMEDIATELY: The next command is activated immediately


(asynchronous data reception).
• WHEN_COMMAND_DONE: The next command is activated when the
command is complete (synchronous data reception).
• ABORT_CURRENT_COMMAND: The active function at this port is
ne

aborted (abort).
receiveVariable (ARRAY [0..1399] OF BYTE): Buffer for receive data.
Return value: The parameter has the data type StructRetUdpReceive:
• functionResult: functionResult indicates whether or not command
ca

execution was successful (0: successful, see slide 0).


• sourceAddress(ARRAY [0..3] OF USINT): IP address of the sender
• sourcePort (UINT): Port number of the sender
• dataLength (UDINT): Number of received user data bytes

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 Communication with SIMOTION
Communication via TCP (Transmission Control Protocol)
„ Properties
„ TCP ensures secure data transfer
„ Acknowledgment mechanisms and packet retransmissions
provide protection against loss of packet content or sequence

om
„ Communication procedure based on client/server model
„ Before data can be sent, a client must set up a connection
with the server
„ Multiple clients can set up a connection with a server

l.c
„ Simultaneous bidirectional data transmission is supported on
one connection
„ Flexible addressing based on IP addresses and ports
(like UDP)

ai
„ Due to unpredictable time delays caused by retransmissions,
often unsuitable for real-time applications in automation

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.24
SITRAIN Training for
Automation and Drives
@
Overview The Transmission Control Protocol (TCP) is a reliable, connection-oriented,
byte-stream protocol. Its main task is to support secure data transport over a
network. Like UDP, TCP resides immediately above the IP layer, on which it is
based.
er

Properties TCP provides a connection-oriented data stream instead of the connectionless


data frame transmission used with UDP. Unlike UPD, TCP guarantees data
delivery. TCP is mainly used by applications which need an absolute guarantee
ez

that data will be delivered.


However, the more versatile options supported by TCP do come at a price: an
increased load is placed on the CPU and greater bandwidth is required from the
network. In addition, guaranteed delivery - which is achieved via an
acknowledgment mechanism and retransmission of lost data packets - means
r.s

that TCP behaves in a way that is not deterministic. The sender never knows
when a sent packet reaches its recipient. TCP is, therefore, unsuitable for many
applications in automation which require real-time properties and determinism.
In the same way as with UDP, the applications are connected to ports of the
system.
ne

Before an application can send data to a partner, a connection must be set up.
To set up the connection, the client first sends a connection request to the
server. Simultaneous bidirectional data transmission can only take place when
the connection has been set up successfully. The application writes data to the
TCP port, the data is transferred via the network and read by the application at
ca

the other end. Once data exchange has been completed, the connection can be
closed by the client or server.
TCP creates packets from the byte stream in an arbitrary manner; any limits
between the individual sections of a message are not taken into account. For
example, if an application writes five times to the TCP port, the application on
the other side may have to read ten times to receive data, or even just once. At
both ends, there is no correlation between the number and scope of the
individual read and write operations, although TCP does guarantee that data will
be in the correct order.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 Communication with SIMOTION
How communication works with TCP

Time
SIMOTION (client) SIMOTION (server)
_tcpOpenServer()
_tcpOpenClient()

om
_tcpSend() _tcpSend()

_tcpReceive() _tcpReceive()
.

l.c
. .
. .
. .
.

ai
_tcpCloseConnection() or _tcpCloseConnection()

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.25
_tcpCloseServer()

SITRAIN Training for


Automation and Drives
@
Sequence The above diagram illustrates the temporal sequence of communication
between two SIMOTION devices via TCP.
1. First, the server uses _tcpOpenServer() to open a TCP port and waits for a
client to set up a connection. The number of the port and the maximum
er

number of parallel connection requests are specified in the parameters for


this call.
2. When the server port is open, the client can start a connection request by
issuing the _tcpOpenClient() call.
ez

Once the connection has been set up, the _tcpOpenClient() call returns a
ConnectionId to identify the communication connection.
This ConnectionId is required for further addressing of the server in the
_tcpSend() and _tcpReceive() calls.
r.s

The _tcpOpenServer() call also returns the ConnectionId after a request as


well as the IP address and port number of the client.
The ConnectionId serves to identify the connection; it is used in the
_tcpSend() and _tcpReceive() calls. The server uses the IP address and port
number to identify the client.
ne

3. Data can now be exchanged in both directions. In the _tcpSend() and


_tcpReceive() calls, the partner is addressed using only the ConnectionId.
4. Once data transfer is complete, the connection can be disconnected
by either the client or the server calling _tcpCloseConnection().
ca

The occupied communications resources (memory areas) are released and


the functional capability of the communication connection (i.e. exchange of
"idle message frames") is no longer monitored.
5. A server closes its port by calling _tcpCloseServer().

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 25 Communication with SIMOTION
Timeout behavior with TCP/IP

om
Double-click

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.26
SITRAIN Training for
Automation and Drives
@
Settings In the HW Config, you can set the timeout behavior for TCP communication for
the controller in the "Object Properties - Ethernet Extended" dialog.
Any changes to the default values may cause undesired behavior and should,
therefore, only be made by experts.
er

• Connect Timeout (default value: 15,000 ms, minimum value: 1,000 ms):
Maximum time the TCP waits internally for the communications partner
to respond to a connection request.
ez

The minimum time is 1 s.


• Max. Retransmit Timeout (default value: 3,000 ms, minimum value: 1,000 ms)
Time the TCP waits internally for an acknowledgment of orderly receipt of a
sent data segment. If no acknowledgment is received within this time frame,
r.s

the sent segment is retransmitted.


• Max. Retransmit Count: (default value: 5, minimum value: 1)
Specifies the maximum number of times TCP will repeat transmission for
a data segment. If no acknowledgment has been received to indicate orderly
receipt of the data segment by the time the transmission has been repeated
ne

for the maximum number of times, the connection is considered faulty (i.e. the
partner can no longer be reached).

Note When a connection is disconnected, this will only be detected by the TCP/IP
functions after a time delay (>= 1 second) due to system constraints.
ca

If the _tcpSend() function sends additional data on this connection during this
time lapse, the data is lost. When the disconnect is detected, both sides need to
close the connection before a new connection setup can be initiated.
Usually this only occurs if the control fails or if there is damage to a cable.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 26 Communication with SIMOTION
Opening the communication port on the server side:
_tcpOpenServer()

Open server port


RetStructRetTcpOpenServer := _tcpOpenServer(
port, // Receiver port
backlog, // Max. number of parallel connections
nextCommand) // IMMEDIATELY or WHEN_COMMAND_DONE);

om
structRetTcpOpenServer
StructRetTcpOpenServer STRUCT
functionResult; // (DINT) Result of call
connectionId; // ID identifying the connection
clientAddress; // IP address of connecting client

l.c
clientPort; // Port number of connecting client
END_STRUCT

functionResult indicates the following states:

ai
16#00000000 Connection set up successfully 16#FFFFFFFF Resource bottleneck
16#00007001 Function started 16#FFFFFFFD Internal error
16#00007002 Function active
16#FFFF8FFF

SIMOTION
Server port assigned more than once

Siemens AG 2013. All rights reserved.


Date:
File:
gm 10.01.2013
MC-SMO-PRG_A1.27
SITRAIN Training for
Automation and Drives
@
Overview The _tcpOpenServer() function sets up a TCP/IP connection on the server side.
Once it has been called, _tcpOpenServer() waits for the connection requests
from the communications partners (TCP clients) at the port specified by the
"port" parameter.
er

The backlog parameter is used to specify the maximum number of connections


to the server that can be active in parallel. Thee returned connectionId is required
for subsequent write and read calls (_tcpSend(), _tcpReceive()).
After this, the function is available again fomr other connections to be set up. If
no more connections are to be set up, the resources occupied by
ez

_tcpOpenServer() can be released again by calling _tcpeCloseServer().


Calling this function does not closesi previously established connections
automatically; they have to be closed by calling _tcpCloseConnection().
The function must have return value = 16#0 before data transmission with TCP/
IP can start.
r.s

.
The function may on ly be called in the BackgroundTask or in a MotionTask.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 27 Communication with SIMOTION
Starting a connection request on the client side:
_tcpOpenClient()

Start connection request on the client side


RetStructRetTcpOpenCient := _tcpOpenClient(
port, // Own port
serverAdress, // IP address of the server
serverPort, // Port number of the server

om
nextCommand) // IMMEDIATELY or WHEN_COMMAND_DONE;

structRetTcpOpenClient
StructRetTcpOpenClient STRUCT
functionResult; // (DINT) Result of call
connectionId; // ID identifying the connection

l.c
END_STRUCT

functionResult indicates the following states:


16#00000000 Connection set up successfully 16#FFFF8FFF Address combination from IP addr.

ai
16#00000001 Function started and port assigned more than once
16#00000002 Function active 16#FFFF8FFB Connection request
16#FFFFFFFF Resource bottleneck refused
16#FFFFFFFD Internal error.

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.28
SITRAIN Training for
Automation and Drives
@
Overview The _tcpOpenClient function sets up a TCP/IP connection on the client side.
When the function is called, a connection request is sent to the server
addressed by serverAddress and serverPort.
The returned connectionId is required for subsequent write and read calls
er

(_tcpSend(), _tcpReceive()).
The function must have return value = 16#0 before data transmission with
TCP/IP can start.
ez

The function may only be called in the BackgroundTask or in a MotionTask.


r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 28 Communication with SIMOTION
Sending data via TCP: _tcpSend()

Send data (server and client)


RetVal := _tcpSend(
connectionId, // Connection identification
nextCommand, // IMMEDIATELY or WHEN_COMMAND_DONE;
dataLength, // Number of bytes (UDINT)
data); // ARRAY[0..4095] OF BYTE for send data

om
RetVal (DINT) indicates the following states:

l.c
16#00000000 Data sent successfully
16#00007001 Function started (only with nextCommand = IMMEDIATELY)
16#00007002 Function active (only with nextCommand = IMMEDIATELY)
16#FFFFFFFF Resource bottleneck
16#FFFFFFFD Internal error

ai
16#FFFF8FFE Invalid connection ID
16#FFFF8FFD Connection closed by communications partner
16#FFFF8FFC Connection termination

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.29
SITRAIN Training for
Automation and Drives
@
Overview _tcpSend() is used to send data to a communications partner via a connection
previously established with _tcpOpenServer() or _tcpOpenClient(). Up to 4,096
bytes can be sent in one call.
Both the client and the server can send data over the active connection.
er

The command can be executed synchronously (nextCommand =


WHEN_COMMAND_DONE) or asynchronously (nextcommand =
IMMEDIATELY). With an asynchronous call (nextCommand = IMMEDIATELY),
the function must be called until it returns the value 0 (or a negative value in
ez

case of an error).
Negative values in functionResult indicate an error during data transmission. In
this case, the connection must be closed by calling _tcpCloseConnection().
The function may only be called in the BackgroundTask or in a MotionTask.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 29 Communication with SIMOTION
Receiving data via TCP: _tcpReceive()
Receive data (server and client)
StructRetTcpReceive:= _tcpReceive(
connectionId, // Connection identification
nextCommand, // IMMEDIATELY or WHEN_COMMAND_DONE;
receiveVariable); // ARRAY[0..4095] OF BYTE for data

om
structRetTcpReceive
StructRetTcpReceive STRUCT
functionResult; // (DINT) Result of call
dataLength; // Number of data items received
END_STRUCT

l.c
RetVal (DINT) indicates the following states:
16#00000000 Data sent successfully
16#00007001 Function started (only with nextCommand = IMMEDIATELY)
16#00007002 Function active (only with nextCommand = IMMEDIATELY)

ai
16#FFFFFFFF Resource bottleneck
16#FFFFFFFD Internal error
16#FFFF8FFE Invalid connection ID
16#FFFF8FFD Connection closed by communications partner

SIMOTION
16#FFFF8FFC

Siemens AG 2013. All rights reserved.


Connection termination

gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.30
SITRAIN Training for
Automation and Drives
@
Overview The _tcpReceive() function waits for data at the active connection to the
communications partner and reads it out. The function receives data via a
connection previously established with _tcpOpenServer() or _tcpOpenClient().
Data can be received in arbitrary packet sizes. Generally, the packet sizes do
er

not correspond to those on the transmitting side. A send packet can be split up
into several receive packets and multiple send data packets can also be
combined in one receive packet.
If the call was successful, i.e. if the value = 16#0 has been returned in
ez

functionResult, the received data will be available in the receiveVariable


parameter. The number of bytes received is indicated by the value in datalength.
If _tcpReceive() is called again, the receiveVariable is overwritten with new data
whose length matches the value specified by the dataLength parameter.
r.s

Negative values in functionResult indicate an error during data transmission. In


this case, the connection must be closed by calling _tcpCloseConnection().
The function may only be called in the BackgroundTask or in a MotionTask.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 30 Communication with SIMOTION
Closing the TCP connection: _tcpClose Connection() Closing
the server: _tcpCloseServer()

Close connection (server and client)


RetVal:= _tcpCloeseConnection(
connectionId); // Connection identification;

om
RetVal (DINT) indicates the following states:
16#00000000 Connection closed
16#FFFFFFFD Internal error
16#FFFF8FFE Invalid connection ID

l.c
Port closed by server
RetVal:= _tcpCloseServer(
port); // Number (UINT) of the server port;

ai
RetVal (DINT) indicates the following states:
16#00000000 Wait state terminated

SIMOTION
16#FFFF8FFE

Siemens AG 2013. All rights reserved.


Invalid port number

gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.31
SITRAIN Training for
Automation and Drives
@
Close Calling the _tcpCloseConnection() function closes an active connection that was
connection set up by calling _tcpOpenClient() or _tcpOpenServer() and releases the
internal resources previously occupied.
The return values of the _tcpSend() and _tcpReceive() calls tell the SIMOTION
er

user program that the connection has been closed.


The function may only be called in the BackgroundTask or in a MotionTask.
ez

Close The _tcpCloseServer() function terminates the wait state for connection
server port requests from TCP clients initiated by _tcpOpenServer.
The function may only be called in the background task or in a motion task.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 31 Communication with SIMOTION
Example: Sending and receiving with UDP (1)

SINAMICS

SINAMICS

270O
90O
0O
180O

270O
0O

90O
180O

om
SMC

SIMOTION
IP address: 192.168.0.1 IP address: 192.168.0.10
Subnet: 255.255.255.0 Subnet: 255.255.255.0

l.c
Port: 2222 Port: 2222

Axis_1.control Cyclic
Axis_2.control

ai
Start_1
Axis_1.motionstatedata.motionstate <> STANDSTILL
Start_2
Axis_2.motionstatedata.motionstate <> STANDSTILL
Axis_1.error Event- Pos_Axis_1 34
34 Pos_Axis_2 bytes
Axis_2.error controlled
bytes Axis_1.positioningstate.commandposition Velo_Axis_1

SIMOTION
Axis_2.positioningstate.commandposition
Axis_1.motionstatedata.commandvelocity
Axis_2.motionstatedata.commandvelocity

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.32
Velo_Axis_2

SITRAIN Training for


Automation and Drives
@
Description The following example illustrates UDP communication between a SIMOTION
device and a PC application.
The SIMOTION device sends status information about the two axes Axis_1 and
Axis_2 cyclically to the "master" PC. This status information (see slide) is
er

"converted" to an array of 34 bytes (Little Endian) and then transmitted to the PC


using the udpSend(..) function. The status information is displayed in a window
on the PC.
Conversely, new position and velocity setpoints can be entered for the two axes
ez

in this window on the PC and the desired axis started from there. The
transmission of this information is event-controlled, not cyclic, and occurs when
the user activates the axis start button.
In the same cycle as the one used to send data, the SIMOTION device also
r.s

checks whether the PC has transmitted new setpoint data. It sends the
corresponding request using an asynchronous udpReceive(..) function call.
If new data is available, MotionTasks are activated in the SIMOTION user
program in order to move the desired axis to the new target position at the
desired velocity.
ne

The following pages provide a brief description of the PC application and a


listing from the associated SIMOTION user program.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 32 Communication with SIMOTION
Example: Sending and receiving with UDP (2)

om
1. Connect

2. Specify new target


positions and velocities

3. Start

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.33
SITRAIN Training for
Automation and Drives
@
Overview This VB application is used to control axis motion from the PC. The status of the
axes is also displayed in the window.

Operation To move the axes, proceed as follows:


er

1. When the application has been launched, activate the "Connect" button
to open an internal connection between the application and a
communications socket. This socket bears the address information of the
communications partner. It can be specified in the "Connect to" and "Remote
ez

port" input fields.


Once the communications socket has been set up successfully, the
application is ready to receive new data from the SIMOTION device. The
"Start" buttons for starting axis motion are also activated and can be
r.s

selected.
2. The next step is to define new settings for the end positions and velocities
of both axes and set the axes in motion using the associated "Start" button.
3. A new data packet is not transmitted to the SIMOTION device until the
"Start" button is selected. If a suitable udpReceive call is not active in
ne

SIMOTION, the operating system of the SIMOTION device generates a


negative acknowledgment message frame and displays a corresponding
error message on the PC.
If no communication connection to the SIMOTION device is open (e.g. if the
cable has been removed), this error cannot be detected by the PC
ca

application due to the properties of the UDP protocol. In this case, an


additional error message is not output.
Active traversing can only be aborted by specifying a new position or
velocity.
4. The application can be closed with the "Exit" button. The existing connection
to the communication socket used is closed and the socket is released.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 33 Communication with SIMOTION
Example: Sending and receiving with UDP (3)

om
l.c
ai
SIMOTION
MCC program for
communication

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.34
MCC program for
traversing an axis

SITRAIN Training for


Automation and Drives
@
Overview On the left-hand side of the above slide you can see the MCC program that is
responsible for communication with the PC. One of the two MCC programs in which
the traversing motion of the two axes is implemented is shown on the right-hand
side.
er

These MCC programs are assigned to MotionTasks which are started automatically
when the system ramps up.
MCC-UDP
ez

This program calls the udp_receive(..) user function to check cyclically whether new
data has been received from the PC. If new data has been received, it is unpacked
from the byte array with the udp_receive(..) function and written to the interface
variables of the ST UNIT.
r.s

The status information of both a xes is then packed in a byte array and transmitted
to the PC with@ the udp_send(..) function.
The udp_receive(..) and udp_send(..) functions are part of the ST UNIT listed on
the next two pages.
MCC program for
ne

axis motion This MCC proggram evaluates the "Start_1" variable sent by the PC together with
the new target position and velocity for Axis_1. The programmed traversing
movement starts on a rising edge.
Anel identical MMC program is used to move Axis_2.
ca

UDP example
project Tkhe SIMOTION project is contained in PRG_D425-2_UDP_V431_e.zip. The
Visual Basic project is in the directory called UDP_english. The corresponding EXE
file is UDP_comm.exe.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 34 Communication with SIMOTION
ST unit for sending and receiving with UDP (4)
INTERFACE
USEPACKAGE CAM;

VAR_GLOBAL
_MccRetDINT: DINT; // Return value for sending
_MccRetStructRetUdpReceive : StructRetUdpReceive; // for receiving

om
StatusByte : BYTE; // Bit 0 AxisEnable_1, Bit 1 AxisEnable_2,
// Bit 2 Axis_1 moving, Bit 3 Axis_2 moving,
// Bit 4 AxisError_1, Bit_5 AxisError_2

Data_Send : ARRAY[0..33] OF BYTE; //Buffer for send data


Data_Received : ARRAY[0..33] OF BYTE; //Buffer for receive data
Pos_Axis_1: LREAL; // New position for Axis_1

l.c
Pos_Axis_2: LREAL; // New position for Axis_2
Velo_Axis_1: LREAL; // New velocity for Axis_1
Velo_Axis_2: LREAL; // New velocity for Axis_2
Start_1: BOOL; // Start signal for Axis_1

ai
Start_2: BOOL; // Start signal for Axis_2
LocalPort : UINT := 2222;
RemoteAdress : ARRAY[0..3] OF USINT := [169,254,11,20];
RemotePort: UINT := 2222;
END_VAR

FUNCTION UDP_SEND;
FUNCTION UDP_RECEIVE;
END_INTERFACE
gm
// Function for sending data
// Function for receiving data

IMPLEMENTATION
@
FUNCTION UDP_SEND : VOID

StatusByte:= byte_from_8bool( // Combine 8 bits in a byte


bit0 := Axis_1.control = ACTIVE,
er

bit1 := Axis_2.control = ACTIVE,


bit2 := Axis_1.motionstatedata.motionstate <> STANDSTILL,
bit3 := Axis_2.motionstatedata.motionstate <> STANDSTILL,
bit4 := Axis_1.error = YES,
bit5 := Axis_2.error = YES,
ez

bit6 := FALSE, bit7 := FALSE);


Data_Send := ANYTYPE_TO_LITTLEBYTEARRAY(s
anydata := Axis_1.positioningstate.commandposition,
offset:=0);
Data_Send := ANYTYPE_TO_LITTLEBYTEARRAY(@
r.s

anydata := Axis_2.positioningstate.commandposition,
offset:=8);
Data_Send := ANYTYPE_TO_LITTLEBYTEARRAY(u
lanydata := Axis_1.motionstatedata.commandvelocity,
offset:=g16);
ne

oData_Send := ANYTYPE_TO_LITTLEBYTEARRAY(
anydata := Axis_2.motionstatedata.commandvelocity,
offset:=24);
Data_Send[32k] := StatusByte;
c._MccRetDINT := _udpsend(sourceport := LocalPort,
ca

destinationaddress := RemoteAdress,
destinationport := RemotePort,
communicationmode := DO_NOT_CLOSE_ON_EXIT,
datalength := 34,
data := Data_Send);

END_FUNCTION

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 35 Communication with SIMOTION
ST unit for sending and receiving with UDP (5)
FUNCTION UDP_RECEIVE : VOID

_MccRetStructRetUdpReceive :=
_udpreceive(
port := LocalPort,
communicationmode := DO_NOT_CLOSE_ON_EXIT,
nextcommand := IMMEDIATELY,

om
receivevariable := Data_Received);

IF _MccRetStructRetUdpReceive.functionresult = 0 THEN
Pos_Axis_1 := LITTLEBYTEARRAY_TO_ANYTYPE(Data_Received, 0);
Pos_Axis_2 := LITTLEBYTEARRAY_TO_ANYTYPE(Data_Received, 8);
Velo_Axis_1 := LITTLEBYTEARRAY_TO_ANYTYPE(Data_Received, 16);

l.c
Velo_Axis_2 := LITTLEBYTEARRAY_TO_ANYTYPE(Data_Received, 24);

Start_1 := _getbit(Data_Received[32],0);
Start_2 := _getbit(Data_Received[32],1);

ai
END_IF;

END_FUNCTION

END_IMPLEMENTATION
gm
@
er
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 36 Communication with SIMOTION
Example: Sending and receiving with TCP (1)
TCP server Up to three TCP clients
SINAMICS

SINAMICS

270O
90O
0O
180O

270O
90O
0O

180O

om
SMC

SIMOTION
IP address: 192.168.0.1
Subnet: 255.255.255.0
IP address: 192.168.0.10

l.c
Port: 2222
Subnet: 255.255.255.0
Port: xxxx

Cyclic
AxisNumber

ai
Axis.control
34 Axis.motionstatedata.motionstate <> STANDSTILL
Event-
Start 34
Axis.error Pos_Axis
bytes Axis.positioningstate.commandposition controlled Velo_Axis bytes
Axis.motionstatedata.commandvelocity

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.37
SITRAIN Training for
Automation and Drives
@
Description The following example illustrates TCP communication between a SIMOTION
device and TCP clients on a PC. Once the SIMOTION device is running,
MotionTask_5 is started automatically. When _tcpOpenServer() is called,
MotionTask_5 waits cyclically for connection requests from TCP clients.
er

Once a TCP client is running, a connection to the SIMOTION TCP server can be
set up by clicking the "Connect" button. The connection status is displayed in a
text field.
The first TCP client which requests a connection to the SIMOTION server is
ez

connected with the 1st axis by the SIMOTION system; the second TCP client is
connected with the 2nd axis, and the third TCP client gets no connection. If
another client requests a connection to the SIMOTION server, this request is
refused.
r.s

If SIMOTION accepts a connection setup, a separate MotionTask is started for


each TCP client; the task handles both communication with the client and the
traversing motion of the assigned axis.
SIMOTION sends each TCP client the axis number and information about the
status of the associated axis cyclically (the 3rd client receives the status
ne

information of the 1st axis). As in the UDP example, all of the information is
"converted" to a 34-byte array (Little Endian) and then sent to the client with the
_tcpSend() function. The status information is displayed in a pane in the client
window.
Conversely, each client can specify a new setpoint position and velocity for its
ca

axis and start the desired axis. The transmission of this information is event-
controlled, not cyclic, and occurs when the user activates the axis start button.
In the same cycle as the one used to send data, the SIMOTION device also
checks whether the PC has transmitted new setpoint data. It sends the
corresponding request using an asynchronous _tcpReceive() function call.

TCP example project The SIMOTION project is contained in PRG_D425_TCP_V431_e.zip. The


Visual Basic project is in \TCP_.english The EXE file is TCP_comm.exe.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 37 Communication with SIMOTION
Example: Sending and receiving with TCP (2)

om
1. Connect/Disconnect

l.c
2. Specify new target
positions and velocities

ai
3. Start

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A1.38
SITRAIN Training for
Automation and Drives
@
Overview This VB application is used to control axis motion from the PC. The status of the
axes is also displayed in the window.
First, the SIMOTION device must be started. On startup, SIMOTION
automatically waits for connection requests from TCP clients. The switches for
er

the %I0.0, %I0.1, and %I0.2 inputs must be set to "0" on the SIMOTION device
("1" closes the connection on the server side).
Up to three connection requests will only be accepted if %I0.0, %I0.1, and %I0.2
equal 0. The status of the connection (active = 1, inactive = 0) is displayed at
ez

outputs %Q4.0, %Q4.1, and %Q4.2.

Operation To move the axes with a TCP client, proceed as follows:


1. A TCP client can be started by double-clicking the file TCP-Client.exe.
r.s

Immediately after application startup, a connection to the SIMOTION server


is set up by clicking the button. The corresponding address information for
the server must be specified for this connection.
If another instance of the TCP client is started, a different port number must
be entered in the "local port" field for a connection to be set up successfully.
ne

The status of the connection is displayed in the client window. It can also be
output on a DOS screen by issuing the command: "netstat".
2. An end position and a velocity can be specified for the axis. Motion is
started by clicking the "Start" button.
ca

A new data packet is not transmitted to the SIMOTION device until the
"Start" button is selected. It is also at this point that motion is executed.
Active traversing can only be aborted by specifying a new position or
velocity.
3. The application can be closed with the "Exit" button. The connection to the
communications partner is then aborted.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 38 Communication with SIMOTION
Supplementary "FixedGear" TO

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Channel structure for "supplementary technology objects" ............................................................... 2
Supplementary technology objects .................................................................................................... 3
er

"Motion vectors" with technology objects ........................................................................................... 4


Functionality of a "FixedGear" ............................................................................................................ 5
Creating the "FixedGear" TO ............................................................................................................. 6
Configuring a "FixedGear" .................................................................................................................. 7
ez

Default for "FixedGear" ...................................................................................................................... 8


Interconnections for "FixedGear" ....................................................................................................... 9
System functions for "FixedGear" ...................................................................................................... 10
Enabling/Disabling the motion input at "FixedGear" .......................................................................... 11
Enabling/Disabling "FixedGear" ......................................................................................................... 12
r.s

Setting the offset at "FixedGear" ....................................................................................................... 13


System variables for "FixedGear" ..................................................................................................... 14
Detailed structure of the MotionIn interface ........................................................................................15
Interconnecting the motion input at the Axis TO ................................................................................ 16
ne

Using the motion input to activate positioning motion ........................................................................ 17


Using the motion input to activate traversing .................................................................................... 18
Using the motion input to traverse a position-related velocity profile ................................................ 19
Motion sequence for absolute "FixedGear" ....................................................................................... 20
Motion sequence for relative "FixedGear" .......................................................................................... 21
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 "FixedGear" TO
Channel structure for "supplementary technology objects"

External
encoder
Virtual Cam_1
axis

Leading Cam_2
axis TO Synchro-
nous

om
_enablegearing Cam_3
operation
_enablecamming
TO
...

_pos
_move
... Buffer IPO Servo

l.c
_runpositionbasedmotion
_runvelocitybasedmotion
_runmotioninpositionlockedvelocityprofile
Motion input

ai
Formula FixedGear
Axis
Object Controller ...
TO
Adder

SIMOTION
Siemens AG 2013. All rights reserved.
...
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.2
...

SITRAIN Training for


Automation and Drives
@
Overview V3.2 and higher integrates more of the technology objects we call
supplementary technology objects (AdditionObjectType, FixedGear, etc.). You
can also interconnect TOs using motion vectors.
For this purpose, a "motion input" and a "motion output" have been integrated
er

into each "Axis" TO. The motion input of an axis can, for example, be
interconnected with motion outputs of other TOs, such as the motion outputs of
supplementary technology objects.
This allows modular and flexible configuration of complex motion dependencies
ez

via TO interconnections.
The motion of an axis can be triggered over the following channels:
• Via a single-axis command, e.g. _move(), _pos(),, etc. In this case, the
motion command is sent to the interpolator via the buffer. The interpolator
r.s

calculates the position setpoints for position control.


• Via a synchronous operation command, _enablegearing(),
_enablecamming(). In this case, the command is sent to the addressed
SynchronousOperation TO. The SynchronousOperation TO calculates the
associated position setpoints for the following axis from the master values;
ne

they are then supplied to position control.


• Via the motion input of the Axis TO. The possible interconnections between
the motion input and the motion outputs of other TOs are configured in the
"Interconnections" dialog for the axis.
ca

The motion input of an Axis TO is activated - and, in the event of a multiple


interconnection, the desired TO is selected - using the system commands
_runpositionbasedmotion() and _runvelocitiybasedmotion().
Motions can be executed in the basic or superimposed coordinate system
via this motion channel too.

Note The supplementary technology objects in a SCOUT project can only be used via
the "CAM_EXT" technology package. You might need to integrate "CAM_EXT"
into the project with the menu command: Edit -> Select technology packages.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 "FixedGear" TO
Supplementary technology objects

FixedGear for fixed synchronous operation


(without synchronization/desynchronization)
based on a defined gear ratio

AdditionObjectType can add up to 4 input vectors

om
for 1 output vector

FormulaObject can apply mathematical operations


to scalars (LREAL, DINT) and "Motion" type
motion vectors

l.c
SensorObject for acquiring scalar measured values

ai
ControllerObject can process and control

SIMOTION
Siemens AG 2013. All rights reserved.
scalar variables

gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.3
SITRAIN Training for
Automation and Drives
@
FixedGear The FixedGear technology object enables you to implement fixed synchronous
operation (without synchronization/desynchronization) based on a defined gear
ratio. A FixedGear converts an input variable to an output variable with a
configured gear ratio.
er

A FixedGear TO can be used for the following purposes, for example:


• To make allowance for diameters in a master variable
• To implement a fixed gear ratio without coupling
ez

• As a motion-coupled gear on the master; slaves are "engaged" or


"disengaged". This ensures that the gear is always synchronized with the
master.
Example: A paper web runs in synchronism with the master.
r.s

AdditionObjectType The AdditionObjectType TO enables you to add up to four input vectors for one
output vector. All input vectors and the output vector are "Motion" type vectors
(generalized motion vectors).
An AdditionObjectType can be used as follows, for example:
ne

• To add superimpositions/offsets in the main signal path, e.g. color register,


cut-off register, to the paper web

FormulaObject The FormulaObject TO can be applied in the TO interconnection to scalars


(LREAL, DINT) and to Motion type motion vectors. Although the components of
ca

a "motion vector" can be modified individually, the motion vector is


interconnected as a whole.

SensorObject The Sensor TO is used to record and process scalar measured values. The
Sensor TO imports a value from the I/O and then smoothes, scales, and limits
the output signal in standardized formats.

ControllerObject The ControllerObject TO is used to process scalar variables and control them
with a universal PIDT1 controller.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 "FixedGear" TO
"Motion vectors" with technology objects
„ A "motion vector", i.e. motion input/output, consists of the
following components:
z s: Position
z v : Velocity
z a: Acceleration

om
„ "Motion vectors" are graphically gated with other TOs at the input
of a TO
„ The supplementary TOs are controlled via system functions

System functions

l.c
Input e.g.: Output e.g.:
Motion output of an axis Motion input of an axis or
(setpoint or actual value) another TO
or motion output of a TO

ai
Supplementary
TO

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.4
SITRAIN Training for
Automation and Drives
@
Motion vector A motion vector consists of three components:
• s: Position
• v : Velocity
• a: Acceleration (not currently in use)
er

as well as internal information to identify the vaelidity


status.
ez

The following TOs have "motion vector" type inputs: Axes (virtual and real),
FixedGear, AdditionObjectType, FormulmaObject, and ControllerObject as well
as the SynchronousOperation TOs for a following axis.
The following TOs provide "motion vecietor" type outputs: Axes (virtual and
real), ExternalEncoder, SensorObject, FixedGear, AdditionObjectType,
r.s

FormulaObject, and Controller sObject.


Motion basis The motion basis of the mo@tion vector can vary: position or velocity.
Consequently, it is al so referred to as the "position vector" or "velocity vector".
The "acceleration" component is not yet in use in the current version.
The position colmponent is zero for the "velocity" motion basis. Accordingly, a
drive axis, fogr example provides only the motion vector with the velocity motion
ne

basis on the output side.


Commandslo/command parameters (Axis TO) or the configuration
(AddeitionObjectType, FixedGear) are used to take into account/set the motion
basis.
Tkhe components of the motion vector are kept consistent at the output side of
ca

the Axis TO, FixedGear TO (the derivative of the position variable is the velocity
variable, the derivative of the velocity variable is acceleration).
The components of the motion vector are not kept consistent at the output side
of the "AdditionObjectType" and "FormulaObject" TOs. Velocity and acceleration
can be specifically defined in this item for the position.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 "FixedGear" TO
Functionality of a "FixedGear"

Setpoint or actual value of an Motion input of an


axis or motion output axis or a TO
of a TO FixedGear

om
+ X +
Offset Gear ratio Offset

l.c
Application:
• To make allowance for diameters in a master variable
• To implement a fixed gear ratio without coupling

ai
• As a motion-coupled gear on the master; slaves are "engaged" or "disengaged".
This ensures that the gear is always synchronized with the master.

SIMOTION
Example: A paper web

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.5
SITRAIN Training for
Automation and Drives
@
Overview The "FixedGear" technology object is use to implement fixed synchronous
operation (i.e. without a specific synchronization/desynchronization strategy)
based on a defined gear ratio.
A FixedGear converts an input variable (motion vector) to an output variable
er

(motion vector) with a configured gear ratio.


A FixedGear is interconnected to a motion vecetor from another TO on the
input side and the output side.
The basic functionality involves multiplyimng the input vector by the configured
ez

gear ratio. The individual vector componeents are multiplied by the gear ratio.
No limiting operations, no transitioni phases, and no corrections (except the
offset value) are taken into account. sOffset changes, gear changes, and input
changeovers are directly enab led on the output vector.
r.s

Properties
• Both absolute and rela@tive synchronous operation with or without
offset are possible
• The master vaulue can be changed on the fly (direct transition)
• If velocity is sellected as the motion basis, the component s (position)
ne

is set to zero on theg output side in the motion output.


• The geaor ratio can be specified either as a rational value (LREAL) or
as a ratio of two 32-bit numbers (DINT) in the form of a numerator/
denominator The gear ratio can be changed using system commands
• An offset can be defined/set on both the input side and the output
ca

side. The offset is relative to the selected gear basis. The offset does not have
a unit; it references the set user unit.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 "FixedGear" TO
Creating the "FixedGear" TO

om
Insert fixed gear

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.6
SITRAIN Training for
Automation and Drives
@
Overview FixedGear technology objects for all devices are created in the "Technology"
folder. Once it has been created, a "FixedGear" can be assigned to all
compatible TOs of a device.
er

Procedure To create a new "FixedGear" TO, proceed as follows:


1. In the project navigator, double-click the "Insert fixed gear" entry in the
"TECHNOLOGY" folder.
ez

The "Insert fixed gear" dialog opens.


2. In this dialog, enter a name and, if applicable, the author, version, and
a comment, then click OK to confirm your entries.
The new TO is inserted in the "TECHNOLOGY" folder.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 "FixedGear" TO
Configuring a "FixedGear"

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.7
SITRAIN Training for
Automation and Drives
@
Configuration Double-click the "Configuration" entry underneath the inserted TO to open the
dialog for configuring the "FixedGear". The following settings can be made in
this dialog box.
er

Ignore position If this box is checked, velocity is be selected as the motion basis. The
components v (velocity) and a (acceleration) are multiplied by the gear ratio and
output at the motion output. The component s (position) is set to 0 on the output
side.
ez

In this case, if gated with a motion input of an Axis TO, the output of the motion
vector can only be used for synchronous velocity operation
(_runVelocityBasedMotion()).
If this box is not checked, the position is used as the motion basis. The
r.s

components s, v, a of the input vector are multiplied by the gear ratio and an
offset is calculated for s if necessary.

Configuration Here you can select the following types for the output vector:
• Linear axis: The components of the motion output are displayed in the
ne

system variables in mm, mm/s, and mm/s2.


• Rotary axis: The system variables are displayed in o, o/s, and o/ s2

Processing You can select either IPO or IPO2 for the processing level.
cycle clock
ca

Input side Here you specify whether the replacement value or the last valid value is to be
used for calculating the output vector if the input vector is invalid.

Activate modulo Here you can activate modulo calculation for the motion output. If you select
"System specification", the modulo properties are taken from the axis assigned
to the motion output.
If you select "Set using configuration", you can enter the modulo values directly.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 "FixedGear" TO
Default for "FixedGear"

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.8
SITRAIN Training for
Automation and Drives
@
Default In this dialog, you can specify the system variables for the default values
(userdefault....). To open the dialog, double-click the "Default" entry in the
project navigator.
er

Direction Here you select the effective direction of the gear.


• Same direction: An increase in the master value also leads to an increase in
the position values of the following axis
ez

• Opposite direction: An increase in the master value leads to a decrease in


the position values of the following axis

Gear type • Absolute gear


If you select Absolute gear, the motion input of the "FixedGear" is
r.s

interpreted as absolute. The specified offset is applied to component s


(position), which is multiplied by the specified gear ratio and output
to the motion output.
• Relative gear
ne

If the "FixedGear" is activated, the current position of the motion input is


considered to be more or less the zero point. Then, the difference between
the position value of the motion input and the "zero point" (with the offset
applied) is multiplied by the gear ratio and output at the motion output.
If velocity is specified as the motion basis, there is no difference between
ca

absolute and relative gearing.

Gear ratio Depending on which mode is selected, the gear ratio is specified here either as
a numerator/denominator ratio or as a floating-point number.

Activation/ The "FixedGear" is activated and deactivated (i.e. the motion input is gated to
Deactivation the motion output) either immediately (i.e. when the enable command is issued)
(_enablefixedgearing()) or when the motion input reaches a specific position.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 "FixedGear" TO
Interconnections for "FixedGear"

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.9
SITRAIN Training for
Automation and Drives
@
Interconnections A "FixedGear" has one motion input and one motion output. In the
"Interconnection" dialog, the motion input can be interconnected to the motion
outputs of other technology objects, such as the motion output (setpoint or
actual value) of an Axis TO, an external encoder, or a suitable supplementary
er

technology object.
However, only one interconnection can ever be active at runtime, i.e. return the
master value for the motion output of the "FixedGear".
e
ez

Activating the Which of the configured interconnections is active can be set with the following
interconnection system function.
• _setFixedGearMaster()
At runtime, you can use this function to switch between different master values
r.s

on the fly.

Procedure Proceed as follows to interconnect the motion input of the "FixedGear" to other
TOs:
ne

1. In the projeclt navigator, double-click the "Interconnections" entry


underneath the "FixedGegar" TO. This opens a dialog in which you can select
the inteorconnections.
2. Clickl in the corresponding input field on the right-hand side and select
the motion output of the required TO. You can only select TOs that have already
ca

been created.
Note The "Cam profile" entry is intended for use in a future version. It is not active in
Version 3.2.1.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 "FixedGear" TO
System functions for "FixedGear"

Setpoint or actual value of an Motion input of an


axis or motion output FixedGear axis or a TO
of a TO
+ X +
Offset Gear ratio Offset

om
_enableFixedGearMotionIn Commands for setting the "master" or for
_disableFixedGearMotionIn enabling and disabling the motion input
_setFixedGearMaster

l.c
_enableFixedGearing Commands for enabling and disabling
_disableFixedGearing the gear and setting offsets
_setFixedGearingOffset

ai
_resetFixedGear
_resetFixedGearError
_resetFixedGearConfigDataBuffer Other commands
_resetFixedCommandId

SIMOTION
_getStateOfFixedGearCommand
_getFixedGearErrorNumberState

Siemens AG 2013. All rights reserved.


Date:
File:
gm10.01.2013
MC-SMO-PRG_A2.10
SITRAIN Training for
Automation and Drives
@
Overview The following commands are available for programming the "FixedGear":
_enableFixedGearMotionIn() Enable the motion input
_disableFixedGearMotionIn() Disable the motion input
er

_enableFixedGearing() Enable the "FixedGear"


_disableFixedGearing() Disable the "FixedGear"
_setFixedGearingOffset() Set the offset on the input/output side
ez

_setFixedGearMaster() Set/switch the master value


_resetFixedGear() Reset the gear
_resetFixedGearError() Reset error
_resetFixedGearConfigDataBuffer() Delete configuration data accumulated
r.s

_bufferFixedGearCommandId() Buffer CommandId and command status


_removeBufferedFixedGearCommandId() Delete CommandId
_getStateOfFixedGearCommand() Read out command status
_getFixedGearErrorNumberState() Read out status of an error number
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 "FixedGear" TO
Enabling/Disabling the motion input at "FixedGear"

Enable motion input


RetVal := _enablefixedgearmotionin(
fixedgear, // Specification of the FixedGear object
nextcommand, // Wait for ... ?
Commandid); // Command identification

om
Disable motion input
RetVal := _disablefixedgearmotionin(//
fixedgear, // Specification of the FixedGear object
nextcommand, // Wait for ... ?

l.c
Commandid); // Command identification

Set master input

ai
RetVal := _setfixedgearmaster( //
fixedgear, // Specification of the FixedGear object
master, // Specif. of the TO for the current input
nextcommand, // Wait for ... ?

SIMOTION
Commandid);

Siemens AG 2013. All rights reserved.


//

gm
Date:
File:
Command identification

10.01.2013
MC-SMO-PRG_A2.11
SITRAIN Training for
Automation and Drives
@
Enabling/Disabling The input interconnection is enabled and disabled separately from the
the motion input functionality itself. If the input values are not active, the replacement values
are used.
• _enableFixedGearMotionIn(): Use interconnected input values
er

• _disableFixedGearMotionIn(): Disable interconnected input values In


this case, the replacement values are used.
The configuration data element MotionIn.behaviorByInvalidInterface is used to
ez

specify which of the following values is used if the interconnection values are
enabled but invalid:
• LAST_VALID_INTERFACE_VALUE: the last valid value or
• DEFAULT_VALUE: the replacement values from the system variables for
MotionInDefault
r.s

(Following system startup, the last valid value is 0). If input interconnection is not
active, the replacement value is always used.

Switch master
ne

setpoint The active master can be defined and switched online with the
• _setFixedGearMaster()
function. The TO to be activated must be interconnected with the motion input,
otherwise the call returns error number: 10 "A connection to a technology object
required for this operation does not exist".
ca

Alarm 50101 "The programmed master is not configured" is also issued.


If multiple TOs are interconnected with the motion input of the "FixedGear", the
required TO must be selected with this command.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 "FixedGear" TO
Enabling/Disabling "FixedGear"
Enable gear
RetVal := _enablefixedgearing(
fixedgear, // Specification of the FixedGear object
direction, // Direction of the gear
gearingtype, // Absolute or relative gear
gearingmode, // Numerator/denom. or floating-point no.
gearingratiotype, // DIRECT or USER DEFAULT

om
gearingratio, // Specification of floating-point number
gearingnumerator, // Specification of numerator
gearingdenominator, // Specification of denominator
enablemode, // Immediate or leading axis position
startpositionmastertype, // DIRECT or USER DEFAULT
startpositionmaster, // Specification of leading axis position
nextcommand, // Wait for ... ?

l.c
commandid); // Command identification

Disable gear
RetVal := _disablefixedgearing(

ai
fixedgear, // Specification of the FixedGear object
disablemode, // Immediate or leading axis position
endpositionmastertype, // DIRECT or USER DEFAULT
endpositionmaster, // Specification of leading axis position

SIMOTION
nextcommand,
commandid,

Siemens AG 2013. All rights reserved.


// Wait for ... ?
// Command identification
gm
motionoutbehaviourmode); //Last valid value or replacement value

Date:
File:
10.01.2013
MC-SMO-PRG_A2.12
SITRAIN Training for
Automation and Drives
@
Enabling/Disabling The actual gear functionality, i.e. the the gating of the motion input to the
"FixedGear" motion output, is performed with the following functions:
• _enableFixedGearing(): Enable gear functionality
er

The command is synchronous. The gear is enabled without a transition


function. The gear ratio is specified in the function parameter. The
"startPosition..." parameter acts only if position is selected as the gear basis.
• _disableFixedGearing(): Disable gear functionality
ez

The gear is disabled with _disableFixedGearing() without a transition


function.
The motionoutbehaviourmode parameter is used to set how the motion
output responds to the _disableFixedGearing()- command.
r.s

Possible settings are:


- DEFAULT_VALUE: The value set in the MotionOutDefault system
variable is output at the motion output.
- LAST_VALUE. The last interface value is frozen. The derivatives
of the interface value are set to zero.
ne

- ZERO_VALUE: The value zero is specified for the output side.


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 "FixedGear" TO
Setting the offset at "FixedGear"

Set offset
RetVal := _enablefixedgearing(
fixedgear, // Specification of the FixedGear object
offsetrange, // Master or slave
offsetmode, // Absolute or additive
offsetvalue, // Offset value

om
activationmode, // For active or future SO
nextcommand, // Wait for ... ?
commandid); // Command identification

l.c
activationmode:
DEFAULT_VALUE: For all future synchronous operations
ACTUAL_VALUE Only for the currently active synchronous operation

ai
ACTUAL_AND_DEFAULT_VALUE For the currently active synchronous operation and
for all future synchronous operations

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.13
SITRAIN Training for
Automation and Drives
@
Setting the offset on
the input/output side This function is used to set an offset on the input or output side.
The following is applicable:
er

• An offset with reference to the current synchronous operation is retained only


for the duration of the _enableFixedGearing() command, i.e. the command
is directly assigned to the active _enableFixedGearing().
• The current offset is applied without compensating motion, i.e. it is
ez

applied directly to the motion output.

activationMode The activationMode parameter of the _setFixedGearingOffset() command can


parameter be set to control how the offset is applied.
The following settings are possible:
r.s

• DEFAULT_VALUE: For the next synchronous operation and all subsequent


synchronous operations
• ACTUAL_VALUE: Only for the current synchronous operation
• ACTUAL_AND_DEFAULT_VALUE For the current synchronous operation
ne

and all subsequent synchronous operations

System variables The synchronous operation adjustments on the "FixedGear" can be read out in
the system variables for the gearingAdjustments structure.
ca

The master and slave structure elements indicate the current offset entries for
the active gearing.
The defaultValueMaster and defaultValueSlave indicate the offset adjustments
for future gearing.
These system variables are read-only. Write operations are only possible with
the _setFixedGearingOffset() function.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 "FixedGear" TO
System variables for "FixedGear"

enablecommand Activation state


disablecommand

Setpoint or actual value of an Motion input of an


axis or motion output FixedGear axis or a TO
of a TO

om
+ X +
Offset Gear ratio Offset

motionin.state motionout.state
motionin.value.s fixedgearvalue.s motionout.value.s
motionin.value.v fixedgearvalue.v motionout.value.v

l.c
motionin.value.a fixedgearvalue.a motionout.value.a

State and values of the State and values of the


motion input motion output
..gearingsettings.direction

ai
..gearingsettings.ratio
..gearingsettings.numerator
..gearingsettings.denumerator
..
Settings for gear type, trans-
mission ratio, direction, etc.

SIMOTION
Siemens AG 2013. All rights reserved.
gm
gearingadjustment.master.offset
gearingadjustment.slave.offset

Date:
File:
10.01.2013
MC-SMO-PRG_A2.14
Settings for offsets

SITRAIN Training for


Automation and Drives
@
MotionIn The structure elements for MotionIn indicate the values of the motion vector
interconnected to the FixedGear. The variables are read-only variables.

MotionInDefault The structure elements for MotionInDefault indicate the replacement values of
er

the motion vector interconnected to the FixedGear. The variables are read/write
variables.

FixedGearValue The structure elements for fixedGearValue indicate the output values of the
ez

FixedGear. The variables are read-only variables.

MotionOut The structure elements for MotionOut indicate the values of the output interface
s

interconnected to the FixedGear. Unlike the FixedGearValue values, if required,


r.s

the replacement values may also be displayed here after _disableFixedGear().


@

The variables are read-only variables.

MotionOutDefault The structure elements for MotionOutDefault indicate the replacement values of
u

the motion vector interconnected to the FixedGear. These variables are


ne

read/write variables.

userDefault The structure elements for userDefault indicate the user defaults (direction,
ratio, numerator, denominator, etc.) at the FixedGear. These variables are
read/write variables.
ca

effectiveData The structure elements for effectiveData indicate the values that are currently
effective (direction, ratio, numerator, denominator, etc.) at the FixedGear.
These variables are read-only variables.

Enablecommand The variable indicates the processing status of an _enable/disableFixedGearing


disablecommand command. If 'enable/disableCommand:=ACTIVE', the command waits for
r

synchronization/desynchronization. The variables are read-only variables.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 "FixedGear" TO
Detailed structure of the MotionIn interface

Buffer IPO Servo

om
_runpositionbasedmotion
_runvelocitybasedmotion
_runmotioninpositionlockedvelocityprofile

l.c
TO_CONNECTION VALUE

Set either directly in the command


or using the system variable:

ai
Fixed
Gear - defaultMotionIn.position
... - defaultMotionIn.velocity
... - defaultMotionIn.acceleration

SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm 10.01.2013
MC-SMO-PRG_A2.15
SITRAIN Training for
Automation and Drives
@
MotionIn As of V3.2, an axis can be traversed according to the defaults set at the MotionIn
interface interface. The MotionIn values can be picked up directly by another TO such as
Axis, ExternalEncoder, AdditionObjectType, FormulaObject, or FixedGear.
As of V4.0, the MotionIn values can also be set from within the user program. In this
er

case, it is possible to set the value directly as a parameter in the command or using
the system variables defaultMotionIn.position, etc. If you choose to use a system
variable, new values are applied cyclically in the system variables.
Thus, both a job-based interface, wheere new axis positions are only taken into
ez

account when a new motion commandi is issued, and a cyclic interface are available
at the Axis TO. The usesr program can activate the MotionIn interface with a
_runPositioBasedMotionIn() or _runVelocityBasedMotionIn() command, for
example, and then set new axis positions or velocities continuously by cyclically
r.s

overwriting the @defaultMotionIn.position or defaultMotionIn.velocity system


variable respectively.
The _runPositionBased MotionIn() command activates the MotionIn interface with
position reluference and _runVelocityBasedMotionIn() activates the MotionIn
interface with velocity reference.
ne

The MotionIn interface is deactivated by a substitute single-axis command such as


_move(), _pos(), _stop(), _stopEmergency() or by substitute synchronous operation
commands _enablegearing(), _enablecamming(), or it can be subsetituted by
issuing another MotionIn command.
Mokreover, as with the other interfaces (single-axis commands, synchronous
ca

operation commands), motion can be executed from the MotionIn interface in the
basic or superimposed coordinate system. In this case, execution is controlled with
the merge parameter of the corresponding command.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 "FixedGear" TO
Interconnecting the motion input at the Axis TO

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.16
SITRAIN Training for
Automation and Drives
@
Interconnections As of V3.2, each Axis TO has a multi-point capable motion input which can be
interconnected with the motion outputs of other TOs.
This makes it possible to couple motion outputs of the following technology
objects directly to the motion input of an axis:
er

• Axis
• ExternalEncoder
• AdditionObjectType
ez

• FormulaObject
• FixedGear
• Sensor
• Controller
r.s

However, only one interconnection can ever be active at runtime, i.e. return the
position and velocity values for the motion of the axis.
Which of the configured interconnections is active is determined by setting
parameters in the following system functions:
ne

• _runPositionBasedMotionIn() or
• _runVelocityBasedMotionIn()
• _runmotioninpositionlockedvelocityprofile()
ca

Procedure Proceed as follows to interconnect the motion input of the "FixedGear" to other
TOs:
1. In the project navigator, double-click the "Interconnections" entry underneath
the "Axis" TO. This opens a dialog in which you can select the
interconnections.
2. Click in the corresponding input field on the right-hand side and select the
motion output of the required TO. You can only select TOs that have already
been created.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 "FixedGear" TO
Using the motion input to activate positioning motion
RetVal :=_runPositionBasedMotionIn(
axis, // Specification of the axis (_posAxis)
reference, // Specif. of the TO for motion input
velocitytype, // DIRECT or USER DEFAULT
velocity, // Velocity
positiveacceltype, // DIRECT or USER DEFAULT
positiveaccel, // Acceleration pos. direction

om
negativeacceltype, // DIRECT or USER DEFAULT
negativeaccel, // Acceleration neg. direction
positiveaccelstartjerktype, // DIRECT or USER DEFAULT
positiveaccelstartjerk, // Jerk on startup pos. direction
positiveaccelendjerktype, // DIRECT or USER DEFAULT
positiveaccelendjerk, // Jerk at the end of the accel. ramp
negativeaccelstartjerktype, // DIRECT or USER DEFAULT

l.c
negativeaccelstartjerk, // Jerk at the start of the decel. phase
negativeaccelendjerktype, // DIRECT or USER DEFAULT
negativeaccelendjerk, // Jerk at the end of the decel. phase
velocityprofile, // Continuous or trapezoidal
mergemode, // Attach, substitute, or superimpose

ai
nextcommand, // Wait for ... ?
commandid, // Command identification
valuereferencetype, // TO_CONNECTION or VALUE
motionintype, // Value direct or system variable

SIMOTION
positionin,
velocityin,
accelerationin);

Siemens AG 2013. All rights reserved.


gm
// Position only for value direct
// Velocity only for value direct
// Acceleration only for value direct

Date:
File:
10.01.2013
MC-SMO-PRG_A2.17
SITRAIN Training for
Automation and Drives
@
Overview The
• _runPositionBasedMotionIn()
command activates the MotionIn interface with position reference. Once the
er

MotionIn interface has been activated with position reference, the axis moves to
(is synchronized with) the position defined in the interface with the velocity
profile and dynamic parameters defined in the command.
The "mergemode" parameter can be set to select whether the motion is
ez

attached or substitutes. "mergemode" can also be set to select whether motion


is to take place in the basic or superimposed coordinate system.
The "valueReferenceType" parameter determines whether the MotionIn position
is taken from an interconnected TO (valueReferenceType =
TO_CONNECTION) or applied directly as a value (valueReferenceType =
r.s

VALUE). In the former case, the "reference" parameter determines the active
TO; in the latter case, the "motionInType" parameter is also evaluated. In the
former case, the MotionIn interface must also be connected to the required TO
under the axis interconnections.
If "motionInType = DIRECT", the "positionIn" parameter of the command is
ne

used; if "motionInType = DEFAULT_VALUE", the content of the


defaultMotionIn.position system variable determines the position in the MotionIn
interface.
If the value in the defaultMotionIn.position system variable changes cyclically,
the modified values are also applied to the MotionIn interface cyclically and the
ca

axis moves to the new positions according to the defined dynamic parameters.
Currently, the state of synchronization is neither stored in the system variables
of the axis nor can it be checked with corresponding system functions. Whether
the axis is synchronized with the motion input, i.e. whether the position of the
axis matches the position in the motion input, must be evaluated in the
application.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 "FixedGear" TO
Using the motion input to activate traversing
RetVal :=_runVelocityBasedMotionIn(
axis, // Specification of the axis (_driveAxis)
reference, // Specification of the TO for motion input
velocitytype, // DIRECT or USER DEFAULT
velocity, // Velocity
positiveacceltype, // DIRECT or USER DEFAULT
positiveaccel, // Acceleration pos. direction
negativeacceltype, // DIRECT or USER DEFAULT

om
negativeaccel, // Acceleration neg. direction
positiveaccelstartjerktype, // DIRECT or USER DEFAULT
positiveaccelstartjerk, // Jerk on startup pos. direction
positiveaccelendjerktype, // DIRECT or USER DEFAULT
positiveaccelendjerk, // Jerk at the end of the acceleration ramp
negativeaccelstartjerktype, // DIRECT or USER DEFAULT
negativeaccelstartjerk, // Jerk at the start of the decel. phase

l.c
negativeaccelendjerktype, // DIRECT or USER DEFAULT
negativeaccelendjerk, // Jerk at the end of the decel. phase
velocityprofile, // Continuous or trapezoidal
mergemode, // Attach, substitute, or superimpose
nextcommand, // Wait for ... ?

ai
Commandid, // Command identification
movingmode, // Position-controlled or speed-controlled
valuereferencetype, // TO_CONNECTION or VALUE
motionintype, // Value direct or system variable

SIMOTION
positionin,
velocityin,
accelerationin);

Siemens AG 2013. All rights reserved.


gm
// Position only for value direct
// Velocity only for value direct
// Acceleration only for value direct

Date:
File:
10.01.2013
MC-SMO-PRG_A2.18
SITRAIN Training for
Automation and Drives
@
Overview The
• _runVelocityBasedMotionIn()
command activates the MotionIn interface with velocity reference. Once the
er

MotionIn interface has been activated with position reference, the axis
accelerates or decelerates to the velocity defined in the interface with the
velocity profile and dynamic parameters defined in the
_runVelocityBasedMotionIn() command.
ez

The "mergemode" parameter can be set to select whether the motion is


attached or substitutes. "mergemode" can also be set to select whether motion
is to take place in the basic or superimposed coordinate system.
The "valueReferenceType" parameter determines whether the velocity is taken
from an interconnected TO (valueReferenceType = TO_CONNECTION) or
r.s

applied directly as a value (valueReferenceType = VALUE). In the former case,


the "reference" parameter determines the active TO; in the latter case, the
"motionInType" parameter is also evaluated. In the former case, the MotionIn
interface must also be connected to the required TO under the axis
interconnections.
ne

If "motionInType = DIRECT", the "velocityIn" parameter of the command is used;


if "motionInType = DEFAULT_VALUE", the content of the
defaultMotionIn.velocitysystem variable determines the velocity in the MotionIn
interface.
If the value in the defaultMotionIn.positon system variable changes cyclically,
ca

the modified values are also applied to the MotionIn interface cyclically and the
axis is accelerated/decelerated to the new velocity according to the defined
dynamic parameters.
Currently, the state of synchronization is neither stored in the system variables
of the axis nor can it be checked with corresponding system functions. Whether
the axis is synchronized with the motion input, i.e. whether the position of the
axis matches the position in the motion input, must be evaluated in the
application.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 "FixedGear" TO
Using the motion input to traverse a position-related
velocity profile
RetVal := _runmotioninpositionlockedvelocityprofile(
axis, // Specification of the axis (_driveAxis)
reference, // Specification of the TO for motion input
profile, // Specification of the cam
positiveacceltype, // DIRECT or USER DEFAULT
positiveaccel, // Acceleration pos. direction

om
negativeacceltype, // DIRECT or USER DEFAULT
negativeaccel, // Acceleration neg. direction
positiveaccelstartjerktype, // DIRECT or USER DEFAULT
positiveaccelstartjerk, // Jerk on startup pos. direction
positiveaccelendjerktype, // DIRECT or USER DEFAULT
positiveaccelendjerk, // Jerk at the end of the accel. ramp
negativeaccelstartjerktype, // DIRECT or USER DEFAULT

l.c
negativeaccelstartjerk, // Jerk at the start of the decel. phase
negativeaccelendjerktype, // DIRECT or USER DEFAULT
negativeaccelendjerk, // Jerk at the end of the decel. phase
velocityprofile, // Continuous or trapezoidal
mergemode, // Attach, substitute, or superimpose

ai
nextcommand, // Wait for ... ?
Commandid, // Command identification
movingmode); // Pos.-controlled or speed-controlled

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.19
SITRAIN Training for
Automation and Drives
@
Overview The
• _runmotioninpositionlockedvelocityprofile()
command activates the MotionIn interface with velocity reference. The axis
er

moves according to a velocity profile that is specified in the cam function:


Velocity = f (position)
Here, the position is an absolute axis position that is specified using the
MotionIn interface. The profile is started at the current MotionIn position.
ez

The cam itself is defined with the "Profile" parameter. The axis interconnections
must include the interconnection of the "Motion profile" entry to the required
cam.
The dynamic parameters for any required transition motions, e.g. to approach
r.s

the profile and to move away from the profile, are defined in the command.
The "mergemode" parameter can be set to select whether the motion is
attached or substitutes. "mergemode" can also be set to select whether motion
is to take place in the basic or superimposed coordinate system.
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 "FixedGear" TO
Motion sequence for absolute "FixedGear"

Gear ratio: 1:1

om
_runPositionBasedMotionIn()

_enableFixedGear()

_setFixedGearMaster()

l.c
ai
Set position Position component
of the "leading axis" of the motion output

SIMOTION
Siemens AG 2013. All rights reserved.
Position component
of the motion input gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.20
Set position
of the "following axis"

SITRAIN Training for


Automation and Drives
@
Overview The above trace recording illustrates the sequences during activation of
synchronous operation via a "FixedGear". The following system variables were
recorded for this purpose:
er

• <LeadingAxis>.positiongstate.commandposition
• <FixedGear>.motionIn.value.s
• <FixedGear>.motionOut.value.s
• <FollowingAxis>.positioningstate.commandposition
ez

"ABSOLUTE" was selected as the gear type and 1:1 as the gear ratio. No
additional zero offsets were programmed.

Sequence The leading axis (linear axis with modulo property) moves in the positive
r.s

direction at constant velocity.


When the _setFixedGearMaster() command is issued, the motion output of the
leading axis (position setpoint) is applied to the motion input. The value of the
"FixedGear".motionIn.value.s system variable changes from 0 to the position
setpoint of the leading axis. The value of the position component of the motion
ne

output motionOut.value.s remains set to 0.


The "FixedGear" is enabled when the _enableFixedGear() command is issued.
The position setpoint is applied directly to the motion output. The value of the
"FixedGear" motionout.value.s system variable changes from 0 to the position
setpoint of the leading axis. The following axis remains at position 0.
ca

The motion input of the following axis is enabled with position reference when
the _runPositionBasedMotionIn() command is issued. The following axis moves
to the position in the motion input in accordance with the specified velocity
profile. After this, the following axis moves in synchronism with the leading axis.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 "FixedGear" TO
Motion sequence for relative "FixedGear"

Gear ratio: 1:1

_setFixedGearMaster()

om
_runPositionBasedMotionIn()

Set position _enableFixedGear()

l.c
of the "leading axis"
Set position of the
"following axis"

ai
Position component Position component
of the motion input
of the motion output

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A2.21
SITRAIN Training for
Automation and Drives
@
Overview The above trace recording illustrates the sequences during activation of relative
synchronous operation via a "FixedGear". The following system variables have
been recorded for this purpose:
er

• <LeadingAxis>.positiongstate.commandposition
• <FixedGear>.motionIn.value.s
• <FixedGear>.motionOut.value.s
• <FollowingAxis>.positioningstate.commandposition:
ez

"RELATIVE" was selected as the geari type and 1:1 as the gear ratio. No
additional zero offsets were progsrammed.
The leading axis (linear ax@is with modulo property) moves in the positive
Sequence direction at constant velocity.
r.s

When the _setFixedGea rMaster() command is issued, the motion output of the
leading axis (positionu setpoint) is applied to the motion input. The value of the
"FixedGear" motionIln.value.s system variable changes from 0 to the position
setpoint of theg leading axis. The value of the position component of the
motion output mootionOut.value.s remains set to 0.
ne

The "FlixedGear" is enabled when the _enableFixedGear() command is


issued. The deifference between the position at the motion input and the
position at the motion input at the time of activation is output to the motion
output. The value of kthe "FixedGear" motionout.value.s system variable
changes from 0 to this difference. The following axis remains at position 0.
ca

The motion input of the following axis is enabled with position reference when
the _runPositionBasedMotionIn() command is issued. The following axis
moves to the position in the motion input in accordance with the specified
velocity profile.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 "FixedGear" TO
OPC (OLE for Process Control) for SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm 10.01.2013
MC-SMO-PRG_A3.1
SITRAIN Training for
Automation and Drives
@
Contents Page
Communication with SIMOTION - The mission ................................................................................. 3
Solution using client/server architecture ........................................................................................... 4
er

Solution with OPC ............................................................................................................................ 5


The OPC Foundation ....................................................................................................................... 6
Benefits of OPC .............................................................................................................................. 7
ez

OPC specifications ........................................................................................................................... 8


The OPC Data Access interface ...................................................................................................... 9
Custom and automation interface for Data Access ............................................................................ 10
The class model for OPC Data Access ............................................................................................. 11
r.s

OPC Data Access ............................................................................................................................ 12


The OPC Alarms & Events interface ................................................................................................. 13
Class model for OPC Alarms & Events ............................................................................................. 14
Types of event for OPC Alarms & Events ......................................................................................... 15
ne

SIMOTION with SIMATIC NET OPC ................................................................................................ 16


Structure of the SIMATIC NET OPC server for Data Access ............................................................. 17
Access using ActiveX Controls ......................................................................................................... 18
Example: OPC via Ethernet .............................................................................................................. 19
ca

Procedure for configuration ............................................................................................................. 20


Step 1: Exporting OPC data from SIMOTION SCOUT ...................................................................... 21
Step 1: Checking the "tag file" *.sti with the symbol file configurator .................................................. 22
Step 1: Communication information in "OPC_AE .xml" ..................................................................... 23
Step 2: Setting the operating mode for the communication module ................................................ 24
Step 2: Setting the PG/PC interface .................................................................................................. 25
Step 2: Selecting the S7 protocol ...................................................................................................... 26

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 1 OPC for SIMOTION
OPC (OLE for Process Control) for SIMOTION

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.2
SITRAIN Training for
Automation and Drives
@
Contents Page
Step 2: Selecting the symbol file (*.sti tag file) .................................................................................. 27
Step 3: Access to SIMOTION with OPC SCOUT .............................................................................. 28
er

Step 3: Establishing a connection to the OPC server and setting up a group ................................... 29
Step 3: Adding items to a group ........................................................................................................ 30
Step 3: Monitoring and writing items ................................................................................................. 31
Restrictions affecting OPC communication ....................................................................................... 32
ez

Using OPC XML to access data ....................................................................................................... 33


r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 2 OPC for SIMOTION
Communication with SIMOTION - The mission

Windows PC/Panel PC

Third-party
HMI

?
Parameteri-

om
zation
SCOUT ProTool/Pro
Control
Drivers Drivers

l.c
PROFIBUS/Ethernet

ai
SIMOTION
Siemens AG 2013. All rights reserved.
SIMOTION P3xx
gm
SIMOTION D4xx

Date:
File:
10.01.2013
MC-SMO-PRG_A3.3
SIMOTION C2xx

SITRAIN Training for


Automation and Drives
@
Communication with The above slide illustrates communication between our standard tools, such as
SIMOTION systems SIMOTION SCOUT and ProTool/Pro, and SIMOTION runtime systems. Both
SCOUT and ProTool/Pro have integrated drivers for the Windows operating
system which handle data exchange with SIMOTION systems. These proprietary
er

drivers are optimized for high-performance communication with SIMOTION


systems.

However, some users prefer to use their own tools and defaults for SCADA
ez

(Supervisory Control and Data Acquisition) systems. How can applications like
these be integrated, i.e. how can datae exchange between the applications and
SIMOTION be implemented?
Access with
drivers In the past, using software app lications to control multi-vendor hardware was an
r.s

arduous task. A multitude of different systems and protocols was used. Users
had to integrate special so@ftware (drivers) for each vendor and protocol in
order to access the specific interface of the automation system.
In most cases, uyou had to be an expert in C/C++ programming in order to be
able to implemenlt data exchange between an application "A" and an automation
ne

system "B". Programmers needed in-depth knowledge of both the data interface
of application "A" and the driver interface to the programmable controller "B".
Toolkits had to be purchased in order to use both the data interface of "A" and
the driver interface of "B". This frequently cost thousands.
User eprograms were tied to a particular vendor, protocol, or system.
ca

Subsequent modifications or extensions to data exchange had to be


programmed from scratch and were, therefore, very time-consuming and
expensive.
Communication
with OPC OPC (OLE for Process Control) based on COM or DCOM is a standardized
multi-vendor software interface which has revolutionized data exchange in
automation applications. OPC makes configuring data exchange with the
hardware and between applications easier.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 3 OPC for SIMOTION
Solution using client/server architecture

Windows NT/2000/XP
PC application

Open, standardized interface


Solution with OPC

PC

om
Example
Database
Server

S7 protocol

l.c
PROFIBUS Industrial Ethernet

ai
SIMATIC SIMOTION SIMATIC
S7 S7 SIMOTION

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.4
SITRAIN Training for
Automation and Drives
@
Client/server The client/server architecture is another concept for the implementation of data
approach communication between an application and an automation system. The server -
in this case a Windows application - uses a standard interface to pass the
automation system data to a separate PC application for processing. The
er

interface is independent of the PC application and the automation system.


In this case, in addition to the hardware, the automation system vendor has to
implement a server with a suitable interface. The server uses its integrated
drivers (e.g. S7 protocol) to communicate with the underlying hardware and
ez

passes the data to the PC application across the standardized interface.


The configuration of data exchange between applications and hardware can be
greatly simplified in client/server architectures of this kind. The data (i.e. tags) to
be exchanged between application and hardware can usually be selected in
familiar Microsoft Explorer style by clicking with the mouse. Individual data items
r.s

(tags) can be combined in groups to optimize data transfer both to the


underlying hardware and between server interface and PC application.
Instead of having to spend time and effort programming drivers, the vendors of
software products (e.g. visualization programs, measuring systems, etc.) now
simply have to provide a suitable client interface for their application.
ne

End users can now choose freely between different hardware and software
vendors, basing their choice on the functionality they need, without having to
check whether a suitable driver is available.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 4 OPC for SIMOTION
Solution with OPC

OLE for Process Control


Task Openess Productivity and
Conectivity

om
Example
OLE is based on COM, the component model of Microsoft
„ Objects are self-contained units

l.c
„ Objects can be accessed beyond process boundaries
„ Objects are extensions of the operating system
„ Since Windows NT, objects can also be accessed beyond

ai
computer boundaries (DCOM)

SIMOTION
technology

Siemens AG 2013. All rights reserved.


gm
OPC denotes a standard interface for communication in automation

Date:
File:
10.01.2013
MC-SMO-PRG_A3.5
SITRAIN Training for
Automation and Drives
@
What is OPC? OPC stands for OLE for Process Control. The standard interface of the future, it
is based on the component model of the Microsoft company, which produces the
Windows operating system.
The term OLE "Object Linking and Embedding" was at one time used by
er

Microsoft to refer to the complete component architecture. However, we use the


term COM (Component Object Model) today toe describe the component
architecture.
COM is a central component of the Windomws operating system and controls
ez

interaction between multiple software components. By using COM, the OPC


server essentially becomes part ofie the Windows operating system and is thus
independent of file names, storsage locations, and versions.
DCOM (Distributed COM) is a further development of COM supporting
r.s

distributed applications and enabling cross-computer interaction between


different software compon@ents within a network.

What does the As an industrial stuandard, OPC defines the exchange of information for different OPC
interface do? applications inl industrial environments. It allows you to monitor, retrieve, and
ne

process systgem data and events from the automation systems on your PC.
The OPC ointerface is the part of the software on a PC which acts as the
platform for operator control and monitoring systems or other applications. It
resides below elthe application program.
ca

Tkhe applications of the OPC interface are based on the client/server model. A
component makes its services available to other components via interfaces. The
other components can avail of these services as needed. In the case of OPC, an
application can detect which OPC servers are set up in a given system. It can
then address one or more of those servers and check which services are
available on each server.
A vendor of a hardware module which transmits process data (communication
systems, measuring instruments, etc.) provides an OPC server for the module,
which handles the connection to the data source.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 5 OPC for SIMOTION
The OPC Foundation

„ Multi-vendor cooperation for standardization


Task „ Some of the member organizations
„ ABB

om
„ Digital
Example
„ Fisher-Rosemount Systems
„ Honeywell Software
„ Intellution Inc.

l.c
„ Microsoft
„ Siemens

ai
„ Toshiba
„ Rockwell
„ ...

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.6
SITRAIN Training for
Automation and Drives
@
OPC Foundation Microsoft has defined a de-facto standard with its Windows operating systems.
Microsoft's most important basic technology for the exchange of data between
applications is COM/OLE.
OLE for Process Control (OPC) is based on this technology. The primary
er

objective of OPC activities is the establishment of a standardized software


interface, based on the familiar Microsoft technology, which is easy for users to
handle and easy for vendors of automation systems to implement.
The OPC Foundation was formed in the USA in September 1996. At that time,
ez

the OPC Foundation comprised 5 members. Today, the OPC Foundation has
approximately 360 members, including all the main worldwide vendors of
automation systems such as Fisher-Rosemount, Siemens, Trebing & Himstedt,
Rockwell Automation, Wonderware, ABB, National Instruments, and Honeywell.
r.s

43% of the member organizations of the OPC Foundation are from the USA,
30% from Europe, and 23% from Asia. The notably high proportion (more than
20%) of end users in the OPC Foundation is an indication of the significant
benefits anticipated by the end users of OPC technology. Microsoft also
demonstrates its full support of the standard through its membership.
ne

No other organization has the same scope of bundled resources at its disposal
in terms of development capacity and global marketing.
The implementation of the OPC specification in products occurred so fast that
neither corporate interests nor established standards committees could keep
pace. Exiting the starting blocks at such a pace meant that OPC managed to
ca

escape being hampered by corporate strategy and technology discussions, a


fate that has befallen many other technologies.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 6 OPC for SIMOTION
Benefits of OPC

„ Bringing an end to
Task
dependency on specific PC 1 PC 2
vendors for hardware Application Application
and software

om
1 2
Client interface Client interface
Example „ Plug & play configuration
of data exchange COM/DCOM

„ Multi-client access and

l.c
data distribution
OPC server OPC server
„ Network capability A B
(Intranet)

ai
Device Device

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.7
A
...
B
...

SITRAIN Training for


Automation and Drives
@
Benefits of OPC Apart from achieving the general aim of facilitating the connection of process
engineering and business/office applications, OPC offers a range of further
benefits.
er

Bringing an end This technology was previously characterized by the need to use special drivers
to dependency to handle data exchange between a PC application and the hardware.
on specific vendors OPC has created a standard interface which makes services available
independently of a specific application.
ez

Hardware vendors have to implement the OPC server interface as an additional


feature of their products. The vendors of software products (e.g. visualization
programs, measuring systems, etc.) merely have to use a suitable OPC client
interface.
r.s

Plug & play confi- OPC makes configuring of data exchange between hardware and applications
guration of much easier. The database for an OPC server is selected in familiar
data exchange Microsoft Explorer style by clicking with the mouse. Individual tags can be
combined in groups so that only data that is actually relevant is exchanged.
ne

Multi-client access Any OPC server is able to process requests from several clients. If data is to
and data be used in several different places, for example by a visualization program
distribution and a database, different software packages can access the data on the OPC
server. This capability is already supported by the functions of the operating
ca

system (COM technology).

Network capability In addition to COM technology, OPC uses DCOM (Distributed COM) for network
(Intranet) (Intranet) capability. This means that both data sources (OPC servers) that are
available on the local PC and all servers on the network are available as remote
data sources. Distributed operator stations, multi-user systems, and access to
distributed data sources are no problem with OPC. The OPC clients don't even
notice whether the data source is local or remote. OPC and DCOM hide the
difference.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 7 OPC for SIMOTION
OPC specifications

„ OPC Overview and OPC Common Definitions


Task
and Interfaces

„ OPC Data Access

om
Benefits of OPC „ OPC Alarms and Events
SIMATIC NET
„ OPC Historical Data Access
Licenses

l.c
„ OPC Data Exchange (OPC DX)
Prices
„ OPC XML

ai
„ ...

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.8
SITRAIN Training for
Automation and Drives
@
OPC specifications OPC encompasses a range of general and detailed specifications which build on
one other and cover special requirements. OPC is an object-oriented
client/server architecture based on Microsoft's COM/DCOM technology.
Networking takes place using DCOM over Ethernet.
er

Data Access Data Access (OPC DA) describes the cyclic exchange of process data. An OPC
server for Data Access manages the process variables and the different
features used to access these variables.
ez

Alarm&Events In addition to the "Data Access" initerface, a specification has been defined for
event handling. Standard acknowsledgement mechanisms, alarm categories,
filter mechanisms, etc. are ava ilable. Alarms can thus be distributed to any
r.s

number of clients.
Historical Data
Historical Data Acce ss allows data to be stored in and retrieved from long-term
Access (HDA)
archives. Access tou historical data was previously only possible within a
SCADA system using anallysis tools (trend loggers, etc.). OPC HDA has
ne

standardized multi-vendogr access.


OPC Data Exchange The exislting OPC DA specification assumes that a node is either a client or a
(OPC DX)
serveer. The OPC DX specification extends the functionality so that a
client/server interface can be implemented in a node. This allows different OPC
ca

servers to communicate directly.


OPC XML OPC XML is a standard enabling communication over a platform-independent
protocol via the Internet. A client is no longer restricted to a Windows
environment (COM/DCOM). Other operating systems such as LINUX can
monitor and exchange OPC data via the Internet over the HTTP protocol and
SOAP interface.
The functional scope of access via OPC XML is similar to that of OPC DA.
However, only simple read and write services are implemented.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 8 OPC for SIMOTION
The OPC Data Access interface

„ Definition of an interface for


Task
process data exchange

„ One or a number of clients can be connected

om
to the server
Example
„ Definition of a name space and an
object hierarchy (branch and leaf nodes)

l.c
„ The name space contains all data, in any
structure

ai
„ Data items (OPC items) have attributes

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.9
SITRAIN Training for
Automation and Drives
@
What is OPC Data The most frequently used interface within the OPC standard today is the
Access (OPC DA)? Data Access interface. Data Access is an OPC specification for accessing
process data via variables. An OPC server for Data Access manages the
process variables and the features used to access these variables.
er

The OPC server can:


• Read the value of one or more process variables from the programmable
controller
ez

• Write the value of one or more process variables to the programmable


controller
• Monitor the value of one or more process variables in the programmable
controller
The server checks whether the value of the process variable has changed in the
r.s

PLC. If a new value is detected, the server returns the value to the client. The
data type, a time stamp, and a quality inference about the validity of the value
are transmitted in addition to the actual value.
The messages to the client are not transmitted faster than the update rate
specified by the client. If a value changes faster than the update rate, the client
ne

is not informed of the intermediate values.


Functions are also available for browsing the server name space, combining
data units in groups, setting up communication channels, and optimizing
performance.
ca

Data Access OPC Data Access can be used on a SIMOTION device to access the
with SIMOTION following variables:
• System variables of the device and the technology objects
• Global device user variables
• Symbolic I/O variables
• Interface variables from user programs

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 9 OPC for SIMOTION
Custom and automation interface for Data Access

Visual
Basic Automation
Task
interface
client/ (DLL)
MS Office "sopcdaauto.dll"

om
OPC server Protocol
Benefits of OPC software
and
C/C++ hardware
SIMATIC NET connection
Client Custom
Licenses interface

l.c
"OPCDAServer.exe"
Prices
SIMATIC NET
Visual Data Control
Basic

ai
(OCX)
client/ "sinet_opcdata.
MS Office ocx"

SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm10.01.2013
MC-SMO-PRG_A3.10
SITRAIN Training for
Automation and Drives
@
Overview The OPC standard defines objects described by object interfaces. The OPC
standard defines two versions of the object interfaces on an OPC server which
can be addressed by an OPC client.
• COM Custom Interface
er

• OLE Automation Interface


In addition, Siemens makes a further "interface" available in the form of a
custom control (OCX):
ez

• SIMATIC NET Data Control

Custom Interface The Custom Interface is designed for languages that use function points, such
as C++, and optimized for performance. It is not suitable for access by script
languages (VBA).
r.s

The Custom Interface is implemented directly on the OPC server


(OPCDAServer.exe). A common OPC server is used for SIMOTION and
SIMATIC S7.
ne

Automation The Automation Interface is an add-on for the Custom Interface. With the
Interface aid of the Automation Interface, the convenience of modern development
systems and script languages can also be used in OPC programming.
The Automation Interface is implemented as a DLL (SOPCDAAuto.dll). A link to
this DLL must be set up when creating the OPC clients with Visual Basic.
ca

OCX Control SIMATIC Data Control enables access to OPC data from container applications
such as Visual Basic or Microsoft Office without any programming effort. The
selection and association of the data with the display and input fields of an
application is configured using a convenient browser.
Data Control (sinet_opcdata.ocx) has to be added to the client project when
creating the OPC clients.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 10 OPC for SIMOTION
The class model for OPC Data Access

OPC client

Task Data Access server


OPCBrowser
OPCServer

om
OPCGroup OPCGroup
Example

OPCItem OPCItem
OPCItem

l.c
Namespace
(address
C230 space)

ai
Axis 1 Axis 2 xxx

SIMOTION
Current_set

Siemens AG 2013. All rights reserved.


gm
Current_actual

Date:
File:
10.01.2013
MC-SMO-PRG_A3.11
SITRAIN Training for
Automation and Drives
@
Class model The OPC specification for Data Access subdivides the interfaces and their
for OPC DA functions (methods) into three hierarchical classes. This structure is known as the
class model. A class defines the set of functions (methods) and properties which an
object has to support.
er

OPC server The OPC Server class is at the top of the hierarchy. Every OPC server belongs
to this class. This class represents the access point for all further services
supported by the OPC Data Access server.
ez

The "OPC server" class has various aettributes and methods which provide
information about the status, versiion, and address space of the process variables
available on an OPC sesrver object. An OPC server also manages the instances of
the "OPC group" class, which resides below it.
r.s

OPC group The "OPC group" class str@uctures the process variables used by the OPC
server. An OPC client can use the objects of the "OPC group" to generate suitable
units of pruocess variables and run operations with them. For example, all process
variablles on a given screen page of an OCM system could be combined in gthe
same group.
ne

The "OPC group" class defines methods which can be used to read and write
the valueslo of the process variables. Multiple variables can be combined in one
reequest and transmitted simultaneously. These set calls make for high processing
speeds in particular when an OPC server is used across a DCOM knetwork
connection.
ca

An object of the "OPC item " class represents a connection to a process


OPC item variable. A process variable is an element of the namespace of the OPC server,
e.g. a system variable (e.g. actual position of the axis) in SIMOTION.
An OPC item is identified by its item ID. The item ID is a name specified by the
vendor of the server and must be unique within the namespace of the server. Every
OPC item has associated value, quality, and time stamp properties.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 11 OPC for SIMOTION
OPC Data Access

„ Synchronous read/write
„ Asynchronous read/write
Task
„ Cache
„ ActiveState

om
„ CycleTime
Example
„ Set operations (creation of groups, etc.)
„ Messaging in the event of a change
„

l.c
UpdateRate
„ PercentDeadband
„ ActiveState

„ Attribute items

ai
„ VARIANT data type
„ Time stamp

SIMOTION
Siemens AG 2013. All rights reserved.
„ Quality
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.12
SITRAIN Training for
Automation and Drives
@
Data access at Functions are available at group and item level both for monitoring variables and
group level for other read and write access operations.
A client can use the OPCGroup object to generate semantically meaningful units
of OPC items in order to process them together.
er

For example, monitoring of all of the OPC items in a group can be activated by
calling a single function. Therefore, all process variables on a given screen page
of an OCM system should be combined in one group, for example. Monitoring of
the variables can then be activated when the screen page is opened.
ez

A common "UpdateRate" and "DeadBand" can be specified for a group. The


"DeadBand" determines the bandwidth in which no messages are triggered as a
result of value changes. The "UpdateRate" specifies the rate at which a client is
informed about changes to the values or states of items.
r.s

Synchronous and asynchronous functions for reading and writing variables are
available within the group. The OPC Automation interface uses events to return
changes to the values of active items and the results of asynchronous
operations.
Data access can also be optimized by reading process variables from the
ne

internal cache of the OPC server.

Data access at Individual items can also be read in synchronous or asynchronous mode.
item level Additional information such as access rights, data type, time stamp (i.e. the time
when the last value was recorded), and the quality of the value can be scanned
ca

from the associated attributes of the item.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 12 OPC for SIMOTION
The OPC Alarms & Events interface

„ Structuring, transfer, and acknowledgment


of events
Task

„ Filter feature on client supports selection of

om
events to be transmitted
Benefits of OPC

SIMATIC NET „ The "Alarms & Events" server sends only


Licenses events, not values

l.c
Prices
„ Option to transmit auxiliary values is
supported

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.13
SITRAIN Training for
Automation and Drives
@
What is OPC Alarms & Events is a specification for transmitting process alarms and events.
Alarms & Events? It is highly flexible and can, therefore, be used on a wide variety of event
sources.
The spectrum ranges from simple to complex events and even events requiring
er

acknowledgement. The OPC specification defines the possible state transitions


for conditional events in a state diagram. Here too, access to events is based on
a class model.
ez

Selection using Events are special process states which have to be signaled to a receiver.
filter criteria The OPC client uses filter criteria to define which events are signaled to the
corresponding programs.
All events that match the filter criteria must be transmitted to the user by the
r.s

creator of the event. his is the main difference between Alarms & Events and
Data Access. When variables are monitored, only value changes that occur
within the specified time scale are signaled.

Message content The message returns the parameters defined in the OPC specification along
ne

with any auxiliary values defined by the vendor.


Messages can be simple event messages or more complex state-related
messages. In the case of these complex state-related messages, the event
sender can request an acknowledgment from the user.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 13 OPC for SIMOTION
Class model for OPC Alarms & Events

OPC client

Task "OPCAlarmload.exe"
OPCEvent
Server

om
OPCEvent
Browser
Benefits of OPC
Alarms & Events
server
SIMATIC NET
OPCEvent OPCEvent
Licenses Subscription Subscription

l.c
Prices
Namespace
D425-2

ai
Axis 1 Axis 2 xxx

SIMOTION
Siemens AG 2013. All rights reserved.
Alarm Alarm

gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.14
SITRAIN Training for
Automation and Drives
@
Overview The class model of Alarms & Events allows the OPC client to be adapted to the
needs of an automation solution. Alarms & Events distinguishes between three
classes:
• OPCEventServer
er

• OPCEventSubscription
• OPCEventAreaBrowser (the OPCEventAreaBrowser class is optional; it is
not supported by the SIMOTION OPC Alarms & Events server).
ez

OPC Alarms server The OPCEventServer class is at the top of the hierarchy. Every OPC Alarms &
Events server belongs to this class. This class represents the access point for
all further services supported by the OPC Alarms & Events server.
The objects of the OPCEventServer class essentially handle the logging in of
r.s

clients to receive events. In addition, they provide information about supported


event categories and the attributes which can be transmitted with an event.

OPCEvent- A client uses the objects of the OPCEventServer class to create one or more
Subscription objects of the OPCEventSubscription class. An object of this class is a
ne

subscription to a set of events. Objects of this class manage the required filters
and attributes on a client-specific basis.

OPCEventArea Alarms & Events supports the subdivision of large plants into different plant
ca

areas. Areas can be used to filter events. The plant areas can be examined
using objects of the OPCEventAreaBrowser class.
Objects of the OPCEventAreaBrowser class are optional; they are not supported
by the SIMOTION OPC Alarms & Events server.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 14 OPC for SIMOTION
Types of event for OPC Alarms & Events

Event types:
Task „ Simple events
„ e.g.: Diagnostics buffer entries

om
Benefits of OPC
„ Conditional events
SIMATIC NET
„ e.g.: TO alarms, AlarmSQ
Licenses

l.c
Prices
„ Tracking events
„ e.g.: operator actions (not supported by the SIMOTION

ai
Alarms server)

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.15
SITRAIN Training for
Automation and Drives
@
Simple events Simple events are typically informative messages which are not associated with
any particular actions. Simple events do not usually refer to error states which
need to be acknowledged specifically. System messages such as start of ramp-
up, device error, etc., are examples of simple events.
er

Information about the event (e.g. time stamp, alarm no., source, alarm text,
severity, etc.) is transmitted to the client in a SimpleEvent object.
In a SIMOTION system, all entries in the diagnostics buffer (not user-specific
entries) are mapped to simple events. When a client logs in, it first receives the
ez

entire content of the diagnostics buffer.

Conditional events Conditional events are always associated with the detection of a particular
condition which usually requires some kind of response (acknowledgment) from
r.s

the user or operator. Conditional events are thus always associated with
information about system states (e.g. incoming alarm, outgoing alarm,
acknowledged, etc.).
In a SIMOTION system, the TO alarms and the configured AlarmS messages
are mapped to conditional events.
ne

Tracking events Tracking events are similar to simple events, but indicate that a particular action
has been initiated by the operator at the "event source". Information about the
operator ("ActorID", etc.) is thus transmitted in addition to the information
associated with a simple event.
ca

Tracking events are not supported by the SIMOTION Alarms server.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 15 OPC for SIMOTION
SIMOTION with SIMATIC NET OPC

SIMATIC NET Edition 2008 + SP3 for SIMOTION 4.3.1.3


(contains SIMATIC NET V7.1.3 for Windows XP + SP3)
Task

om
Example

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.16
SITRAIN Training for
Automation and Drives
@
SIMATIC NET for The following packages are required to create OPC applications under
Windows XP Windows XP: Version V7.1.3 can only be used in combination with the following
packages:
• Windows XP Professional + SP3
er

• as of SIMOTION SCOUT V4.3.1.3


A license is not needed for the OPC server dureing the design
phase.
ez

SIMATIC NET V8.1 or 8.2 is required fomr the Windows 7 Enterprise and
SCOUT V4.3.1.3.
The version which is internally storedie on "SIMATIC NET, PC Software, Edition
2008 + SP3" CD is V7.1.3.
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 16 OPC for SIMOTION
Structure of the SIMATIC NET OPC server for Data Access

CLIENT Examples VB application


Task
OPC HMI Any OPC Microsoft
Data
DataOCX
OCX
Scout systems applications Office

om
Multi-vendor capability
Example
SIMATIC NET OPC server with multiplexer

PROFInet S7 S5-comp. comm.


server S/R server
server DP
DP server
server FMS SNMP
server

l.c
(Send/Receive) server server

Master class 1/2


DCOM S7 S5-comp. comm.
Send/Receive Slave SOFTNET FMS comm.. SNMP

ai
comm. (FDL) Base CP5613/14

Industrial Ethernet PROFIBUS

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.17
SITRAIN Training for
Automation and Drives
@
SIMATIC NET The OPC server for Data Access enables standardized access to the
DA OPC server industrial communication networks of SIMATIC NET.
The SIMATIC NET OPC server supports the interfacing of applications to any
automation components networked using PROFIBUS or Industrial Ethernet. The
er

following protocols are supported for communication via PROFIBUS and


Industrial Ethernet:
• S7 communication
• S5-compatible communication
ez

PROFIBUS also supports the followinge


protocols:
• PROFIBUS DP
• PROFIBUS FMS
r.s

The following protocols ar@e supported in addition for communication


via Industrial Ethernet:
• PROFINet
• SNMP
ne

The commungication functions are optimized for different requirements.


Several communicaotion functions can be used simultaneously by OPC
servers.
The S7 lprotocol over PROFIBUS or Industrial Ethernet is used for access to
a SIMOTION system.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 17 OPC for SIMOTION
Access using ActiveX Controls

Task

om
Example

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.18
SITRAIN Training for
Automation and Drives
@
SIMATIC SIMATIC Computing, part of the SIMATIC NET PC software, is used to
Computing generate simple applications for data access without any need for programming.
The process data can be read from or written to a SIMOTION system via
PROFIBUS or Industrial Ethernet.
er

A total of four different ActiveX Controls, which can be configured and


interconnected, are available in SIMATIC Computing. These SIMATIC NET
ActiveX Controls are based directly on the OPC interface. Applications
generated using SIMATIC NET ActiveX Controls can also be used in
ez

conjunction with the OPC servers of other vendors.

SIMATIC NET OPC The most important control is SIMATIC NET OPC Data Control. Without this
Data Control control, no other SIMATIC control can access the process data.
(sinet_opcdata.ocx) Data Control accesses process data determined by the OPC server.
r.s

Display controls Display controls are elements for the visualization of process data. They
receive their data via SIMATIC NET OPC Data Control and not directly by
accessing OPC or another interface.
ne

• Button Control (s7vbbttn.ocx): Accesses individual bits stored on the OPC


server. Button Control only accesses in bit format and works with two values:
"OFF = 0" and "ON = 1".
• Number Control (S7wcnumx.dll): Accesses the process data using variables.
Process data can be accessed in byte, word, or doubleword format.
ca

Individual bits within the data can be changed.


• Slider Control (s7vbslid.ocx): Accesses the process data using variables.
Process data can be accessed in byte, word, or doubleword format.

Note If a process variable is interconnected using ActiveX Controls, the connection


for access to the associated process data is established automatically. If the
value of a process variable is changed in an ActiveX Control, the value is also
changed in the controller and thus in the process.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 18 OPC for SIMOTION
Example: OPC via Ethernet
PG/Laptop

Task

Solution with OPC

om
Step 7 SCOUT ProTool/Pro OPC SCOUT EXCEL/
Drivers Drivers Drivers
Visual Basic

SIMATIC NET

l.c
CP5611 Ethernet

Ethernet

ai
SINAMICS

SINAMICS

0O
270O
90O

180O

0O
270O
90O

SIMOTION
Siemens AG 2013. All rights reserved.
Date:
File:
gm
180O

SMC

10.01.2013
SIMOTION D425-2

MC-SMO-PRG_A3.19
SITRAIN Training for
Automation and Drives
@
Overview The following examples illustrate communication between two OPC client
applications, OPC SCOUT, and a Visual Basic application, and a SIMOTION
system using the SIMATIC NET OPC Data Access server.
This example shows how a SIMOTION D425-2 is connected to a PG/PC via
er

Ethernet. The two OPC client applications, "OPC SCOUT" and "VB Application",
run on the same PG/PC as the OPC server.
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 19 OPC for SIMOTION
Procedure for configuration
Step 1:
„ Export the OPC data from SIMOTION SCOUT
Task „ .sti file
(assignment of symbols to addresses)
Solution with OPC

om
„ xml file (all S/Q, TO alarms, and other communication
information)

Step 2:
„ Make settings to start the OPC server

l.c
„ Set the operating mode of the PG interface
„ Select the S7 protocol

ai
„ Select the required sti file

Step 3:

SIMOTION
Siemens AG 2013. All rights reserved.
gm
„ Start OPC client application (OPC SCOUT)

Date:
File:
10.01.2013
MC-SMO-PRG_A3.20
SITRAIN Training for
Automation and Drives
@
Overview In order to establish a connection between a PG/PC and a SIMOTION device
via OPC at runtime, you must first carry out a number of steps to configure the
OPC interface:
er

Engineering Start by performing the following actions when creating the project on the
system engineering system of the SIMOTION device:
1. Create a project for the SIMOTION device using SIMOTION SCOUT.
2. Export the OPC data with SCOUT in omffline mode.
ez

3. If several networks have been configurede , these gateways must be


configured in SIMOTION SCOUT iimmediately after the file export is
complete.
4. If there are several SIMOTI ON projects with SIMOTION devices,
r.s

they will need to be configur@ed and combined using the SIMOTION OPC
File Manager.
5. Then copy the ex ported files to the PG/PC on which the OPC server
is running.
ne

The followingg settings are required on the PG/PC with the OPC server:
PG/PC

1. It mighot be necessary to install an Ethernet interface in the PC and


install the lSIMATIC NET PC software.
2. Tehe interface must be set to the required IP address.
ca

3. The S7 protocol and the corresponding interface must be selected for


OPC server access to the SIMOTION device (SIMATIC NET tool: Configuration
Console).
3. Finally, the required *.sti file(s) must be selected for OPC server access
Client applircation (tool: Configuration Console).

You can now launch the OPC client application.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 20 OPC for SIMOTION
Step 1: Exporting OPC data from SIMOTION SCOUT
2. Version of SIMATIC NET

1. Export OPC files

Task

om
For Data Access

For Alarms&Events

l.c
4. Enter interface 3. Enter path

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Drive:\Documents and Settings\All Users\Anwendungsdaten\
Siemens\SIMATIC.NET\opc2\binS7\simotion\xml\

Date:
File:
10.01.2013
MC-SMO-PRG_A3.21
SITRAIN Training for
Automation and Drives
@
Procedure To declare the data configured in SIMOTION SCOUT to SIMATIC NET, the
necessary files need to be exported. OPC data can only be exported when
SIMATIC NET OPC is installed, a project is loaded, and SIMOTION SCOUT is
in offline mode.
er

Proceed as follows:
1. Switch OPC SCOUT to offline mode if necessary and select the menu item:
Options -> Export OPC data... .
ez

The dialog "Setting the Data for Export" opens.


2. Select the correct version of the OPC server and the types of process
variable (controller and/or drive) you are going to export.
si

Select the "OPC data" entry if you want to access SIMOTION process
variables. If the box is checked, the symbol names and variable addresses
r.s

are exported to the *.sti file.


Check the OPC alarm/event box to export the configured alarms and alarm
texts. All available languages of the alarms are exported to the *.xml file.
lu

3. The next step is to enter the target directory for the exported files in the
ne

"OPC Export" dialog. Subsequently, the exported files have to be


stored on the PG/PC with the OPC server in the following target directory:
As of SIMATIC NET 2007: for the "OPC_AE.XML and OPC_Data.idl" files -
<System drive>\Documents and Settings\All Users\Application Data\
Siemens\SIMATIC.NET\opc2\binS7\simotion\xml".
ca

"OPC_DATA.sti": <System drive>\Documents and Settings\All Users\


Application Data\Siemens\SIMATIC.NET\opc2\binS7\symbolic
The "User Data" folder has the "System Folder" property and may be hidden.
4. Select the required interface of the SIMOTION target device with which the
PG/PC (OPC server) and SIMOTION will subsequently communicate.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 21 OPC for SIMOTION
Step 1: Checking the "tag file" *.sti with the symbol file
configurator
Start -> SIMATIC -> SIMATIC NET -> Symbol File Configurator

Task

Solution with OPC

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.22
SITRAIN Training for
Automation and Drives
@
Overview Existing symbol files can be accessed with the Symbol File Configurator.
Symbol files can be extended or modified. In particular, the following properties
of a symbol can be modified:
• Visibility in the OPC Browser
er

• Access rights (read-only/write) for OPC clients


• Value range of the variables for supporting the "Percent Deadband"
OPC functionality
ez

Structure A symbol file is organized hierarchically and is similar in structure to a file


system. The folders are used to structure the data. The symbols contain the
actual information from the process variables including access rights, data
types, and item and runtime names.
r.s

OPC ItemID The OPCItemID is the process variable identifier used by the OPC server. An
ItemID is passed from the OPC client to the OPC server to identify a process
variable and is unique on the OPC server.
Detailed knowledge of the exact structure of the ItemID is important, especially
ne

when programming your own OPC clients with C/C++ or Visual Basic.

Symbolic name A symbolic name is an OPCItemID used within a hierarchical namespace. In this
case, the symbolic name is derived in the established namespace from the
ca

names of the hierarchical levels and the actual symbol. The symbolic name can
also be used to access a process variable.

Runtime name A runtime name is an OPCItemID which contains tracking and address
information for assignment purposes. It is accepted directly by the OPC server
without using a symbol file. The Symbol File Configurator assigns a symbolic
name to a runtime name.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 22 OPC for SIMOTION
Step 1: Communication information in "OPC_AE .xml"

Alarm and
message texts
Task

Solution with OPC

om
Ethernet and
PROFIBUS
address

l.c
List of all
TOs

ai
Access point
for SIMOTION
OPC server

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.23
SITRAIN Training for
Automation and Drives
@
Overview The file in the screenshot above is an OPC_AE.xml file. It can be opened in
Internet Explorer by double-clicking the file name. A file of this type contains the
following data for each configured language:
• Texts of all AlarmS/Q messages configured by the user
er

• Texts of all diagnostic messages configured by the user


• Texts of all system diagnostics buffer messages
• Texts of all TO system error messagesm
• Identifiers and addresses of all esubnetworks and interfaces
ez

• Identifiers of all TOs


• Access point for OPC serv er
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 23 OPC for SIMOTION
Step 2: Setting the operating mode for the
communication module

Start -> SIMATIC -> SIMATIC NET -> Configuration Console

Task

Solution with OPC

om
Modules -> Intel(R) PRO... -> General

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.24
SITRAIN Training for
Automation and Drives
@
Overview The "Configuration Console" is a tool with versatile features for the configuration
and diagnostics of PC hardware components and PC user programs. The
settings of the OPC servers supplied with the software can also be configured
here.
er

The "Configuration Console" tool can be launched from the Windows start menu
by selecting:
Start -> SIMATIC -> SIMATIC NET -> Configuration Console
ez

Operating mode The operating mode of the module can be changed. The possible settings
module are:
Configured mode:
In this mode, as is the case with a SIMATIC station, a configuration of the
r.s

PG/PC must be created. In this case, the PG/PC is treated in exactly the same
way and has the same properties (e.g. routing) as a PLC. The Ethernet module
and the OPC server are configured in exactly the same way as the modules in a
SIMATIC station.
All parameters of the module have to be defined in the PC station configuration
ne

and downloaded to the device. The download can also be performed from a
remote engineering system.
PG mode
In this mode, the module remains under the control of the local Windows
ca

operating system. The network-related parameters of the module, e.g. the


station address and the transmission rate, are set by the "PG/PC - Set interface"
configuration program. This setting is only possible locally on the computer
itself.

SIMOTION "PG mode" should be set for the Ethernet module to enable the OPC server to
access the SIMOTION device. "Configured mode" should be selected, for
example, whenever the OPC server has to access both SIMOTION and
SIMATIC stations.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 24 OPC for SIMOTION
Step 2: Setting the PG/PC interface

Task
Modules -> Intel(R) PRO... -> Address
Solution with OPC

om
l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.25
SITRAIN Training for
Automation and Drives
@
Ethernet The settings for the IP address and subnet mask of the Ethernet module are
address entered in the Modules -> Intel(R) ...-> Address dialog. However, the values can
only be changed if the module is in PG mode and you have the corresponding
administrator rights.
er

When the module is in "Configured mode", it is only possible to change the


parameters via the hardware configuration of the PC station. In "PG mode", it is
also possible to change the network parameters using the "Set PC/PG interface"
e

tool.
ez

Note The IP address and the net mask set in this dialog must match the IP address
e

set in the Windows Control Panel.


r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 25 OPC for SIMOTION
Step 2: Selecting the S7 protocol

Task

Solution with OPC

om
OPC protocol selection

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.26
SITRAIN Training for
Automation and Drives
@
Protocol selection The OPC server supports various protocols. All protocols are activated in the
initial configuration. When commissioning a plant with several different
protocols, it can be advisable to put the communication system into operation
gradually.
er

In our example, access to the SIMOTION device is implemented using the S7


protocol. Therefore, you should uncheck all of the boxes except the one for the
S7 protocol.
ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 26 OPC for SIMOTION
Step 2: Selecting the symbol file (*.sti tag file)

Task

Solution with OPC

om
Symbols

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.27
SITRAIN Training for
Automation and Drives
@
OPC symbols One or more cross-protocol symbol files (*.sti) can be selected with the OPC
server in the "Symbols" dialog. A symbol file contains a symbolic namespace for
the OPC Server which can be organized hierarchically.
In Step 1, the symbol file of a project was exported from SIMOTION SCOUT. In
er

SIMATIC NET 7.0, the symbol file for SIMOTION must be stored in the following
location:
<System drive>\Documents and Settings\All Users\Application Data\Siemens\
SIMATIC.NET\opc2\binS7\simotion\xml\
ez

Symbol files/ If several symbol files are selected, aie name prefix can be entered in "Edit list"
Prefix in order to prevent name conflictss.
The prefix used to classify the symbols from the symbol file in the namespace is
r.s

displayed in the "Prefix" column. The prefix (e.g. "SYM1") is then inserted in
front of all symbols from this symbol file when browsing.
The default symbol file has no prefix. Its symbols are then classified
immediately below the root "SYM" uof the symbol namespace.
ne

Advanced In this g dialog, you select the module (TCP/IP -> Intel(R) ...) used by the OPC
symbols server to handle communication with the SIMOTION target device on the
PG/PC.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 27 OPC for SIMOTION
Step 3: Access to SIMOTION with OPC SCOUT

PG/PC

Task

om
OPC SCOUT

SIMATIC NET

l.c
CP5611 Ethernet

Ethernet

ai SINAMICS

SINAMICS
0O

270O
90O
180O

0O

270O
90O
180O

SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
SIMOTION D425-2

MC-SMO-PRG_A3.28
SITRAIN Training for
Automation and Drives
SMC
@
Overview OPC Scout can be used to test access to the OPC server and thus to start up
the OPC server.
OPC Scout can be launched from the Start menu of the Windows operating
system:
er

Start -> SIMATIC -> SIMATIC NET -> OPC Scout


ez
r.s
ne
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 28 OPC for SIMOTION
Step 3: Establishing a connection to the OPC server
and setting up a group
Start -> SIMATIC -> SIMATIC NET -> OPC SCOUT

Task

Solution with OPC

om
Step 1: Double-click OPC SimaticNet
(to establish a connection to the OPC server)

Step 2: Enter a group name

l.c
(create OPC group)

ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.29
SITRAIN Training for
Automation and Drives
@
Connecting Before the process variables of the SIMOTION device can be controlled and
OPC Scout to monitored, a connection to the desired OPC server must be established from
the OPC server OPC Scout.
To do this, double-click the "OPC.SimaticNET" entry or select the "Connect"
er

command from the "OPC.SimaticNet" context menu.


The OPC.SimaticNet server is launched and a connection to OPC Scout is
established.
ez

Creating an In the next dialog, "Add Group", you are prompted to create a new
OPC group OPC group.
Enter a group name (e.g. "MyGroup") and acknowledge with the "OK" button.
The OPC.SimaticNet server creates a new group and activates it, i.e. the
r.s

process variables (items) inserted in the group are automatically updated on the
SIMOTION device by the server.
The "Requested update cycle" entry is used to adjust the rate at which the
OPC.SimaticNet server transmits new values to OPC Scout.
ne

The "Advanced" check box is used to modify additional properties such as the
"Percent Deadband" or to display other information about the OPC group
created, such as the client and server group handle.
ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 29 OPC for SIMOTION
Step 3: Adding items to a group

Double-click
Task

om
\SYM
Step 3: Add items to group

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.30
SITRAIN Training for
Automation and Drives
OK
@
OPC Navigator Next, the namespace of the OPC.SimaticNet server can be scanned and new
process variables added to the new OPC group.
To do this, double-click the group you have just created or select the Add item
command from the shortcut menu.
er

The OPC Navigator opens. The process variables of the SIMOTION device are
displayed below the SYM root if no additional prefix has been declared.
e
ez

Adding an item The left-hand column of the OPC Navigator window shows the hierarchical
structure of the process space. You can insert process variables as follows:
1. Double-click to open the desirsied secondary level of the process
space in the left-hand window.
2. Select the level for which you want to display the variables.
All variables on that le@vel are displayed in the middle column.
r.s

3. In the middle pane, se lect the process variables you want to add to
the group and clicku the "->" button.
The selected lvariables are transferred to the right-hand pane. Conversely,
you can remove variables from the group again by clicking the "<-" button.
4. When youo have finished adding the variables to the group, confirm
your selection by clicking the "OK" button.
The selected variables are copied to the main window of OPC Scout and
ne

displayed together with their attributes.


ca

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 30 OPC for SIMOTION
Step 3: Monitoring and writing items

Monitor items
Task

Solution with OPC

om
Write value(s)
Right-click with the mouse

l.c
ai
SIMOTION
Siemens AG 2013. All rights reserved.
gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.31
SITRAIN Training for
Automation and Drives
@
OPC ItemIDs Unique name of the OPC item
Value Value of the variable, displayed in the format set in the Format column.
Format You can choose between original, hexadecimal, and binary notation for integer
er

values. The "original" notation for integer values is decimal. All non-integer
values are always shown in original notation. It is not possible to change the
format for these data types.
Type Canonical data type of the OPC item.
ez

Access Access rights for the OPC item ( "R"= Read-only, "W"= Write-only, "RW" =
Read/Write)
Quality Qualifies the meaningfulness of the value. "Good" quality indicates that the
value has been determined reliably.
r.s

Time stamp (UTC) Last time the OPC server detected a value change. The time stamp is
represented in UTC (Universal Coordinated Time) format. The UTC time is
equivalent to Greenwich Mean Time (GMT).
Result Write result of the last write operation for this OPC item.
Group Name of the group containing the OPC item.
ne

Client handle OPC item handle allocated by the client.


Server handle Handle assigned by the server.
Error Error messages displayed during the use of the OPC item but not attributable to
"Quality" or "Write Result".
ca

Change values 1. Right-click to open the context menu for the variables you wish to overwrite
and select the "Write Value(s)" command.
The "Write Value(s) to the Item(s)" dialog is opened.
2. Enter the new value in the "Value" input field and confirm your entry by
clicking the "Apply" or "OK" button.
The new value is transferred to the process variable in the controller.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 31 OPC for SIMOTION
Restrictions affecting OPC communication

Restrictions
„ Communication based on OPC client
COM/DCOM mechanisms Firewall?
Windows operating
„ Restricted to devices with system ...

om
Windows operating system DCOM (TCP/IP connections)

„ Requires a dedicated PC with OPC LAN, Internet


server
OPC server
„ DCOM assigns port numbers of

l.c
TCP/IP connections during access
via the Internet Windows operating
system
Î Problems with firewalls PROFIBUS/Ethernet

ai
Solution which gets around the
above problems:

SIMOTION
Î OPC XML

Siemens AG 2013. All rights reserved.


gm
Date:
File:
SIMOTION
P350

10.01.2013
MC-SMO-PRG_A3.32
SIMOTION
D4x5
SIMOTION
C230-2/C240

SITRAIN Training for


Automation and Drives
@
OPC today The OPC DA specification defines a software interface for data exchange in
automation systems. An OPC server gives an OPC client transparent access to
any data on a PLC. Clients and servers can originate from different vendors.
Interoperability is assured whenever the specifications are met. Thus, the
er

vendor of an HMI system no longer has to develop and provide drivers for
different communication systems.

Restrictions However, many applications cannot be implemented satisfactorily or even at all


ez

using the above scenario:


• OPC is based on COM/DCOM (Distributed Component Object Model).
However, this technology is only available on Windows platforms. An OPC
client or the OPC server can thus only run on that operating system platform.
In this case, other operating systems are not supported by OPC technology.
r.s

• For example, if the data is stored on a SIMOTION device or a PLC, an


additional OPC server is needed on a PC. This increases the time and
money that has to be spent on configuration.
Implementing an OPC server directly on a terminal device is usually much
ne

too expensive due to the underlying DCOM and RPC (Remote Procedure
Call) mechanisms.
• Remote maintenance and diagnostics is another area where OPC now plays
a role. OPC is designed to support access via the Internet. Because of the
"generous" allocation of free port numbers for underlying TCP/IP
ca

communication connections by DCOM, a further means of worldwide


communication is prevented due to the use of firewalls.

OPC XML DA With the "OPC XML DA" specification, the OPC Foundation has extended the
scope and application of OPC. This specification provides a means of operating
OPC connections via the Internet.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 32 OPC for SIMOTION
Using OPC XML to access data

Properties
„ DCOM mechanisms are OPC XML
client
replaced by IT mechanisms
Any operating system
„ HTTP (Hyper Text Transfer Protocol) (Linux, Windows, etc.) ...

om
„ SOAP (Simple Object Access
Protocol)
„ No problems with firewalls LAN,
(HTTP uses port 80) Internet

l.c
„ OPC XML client can run on any
Ethernet
platform (Linux, etc.)
„ OPC XML server runs directly on OPC XML

ai
the SIMOTION device server

„ Variables do not have to be exported


and an additional PC with OPC server

SIMOTION
is not required

Siemens AG 2013. All rights reserved.


gm
Date:
File:
10.01.2013
MC-SMO-PRG_A3.33
SITRAIN Training for
Automation and Drives
@
Overview A new specification based on XML (eXtensible Markup Language) has been
defined for OPC describing the process data interface using XML data records.
The specification paves the way for an OPC XML client to access data on an
OPC XML server. Data access via OPC XML has a functional scope similar to
er

OPC Data Access.

Function calls A web service allows function calls to be sent to a server via the Internet
via the Internet using the independent SOAP protocol (Simple Object Access Protocol). The
ez

description of the methods and parameters made available by a web service is


stored in XML format in WSDL (Web Service Definition Language) files. The
client can request the content of these WSDL files from the web server. Actual
data transfer is implemented using SOAP messages embedded in HTTP
telegrams.
r.s

It is thus only necessary to know the Internet address and the URL of the web
service in order to use web services.

OPC XML Data transfer using OPC XML is an example of this type of web service. The
exact description of the data interfaces and methods is contained in the WSDL
ne

specification, which is supplied by the OPC Foundation together with the OPC
XML DA specification.
Access to methods direct from the Internet presents a significant security risk.
Therefore, SOAP uses the Internet HTTP (HyperText Transfer Protocol) channel
ca

exclusively for data transfer. This channel can be managed easily with a firewall.

SIMOTION In the case of SIMOTION, the OPC XML DA Server runs directly on the target
hardware. An OPC XML Client can thus use the services of the server directly to
access the data and operating modes of the SIMOTION device.
The use of the integrated OPC XML server is only possible via Ethernet.

SITRAIN Training for MC-SMO-PRG


Automation and Drives Page 33 OPC for SIMOTION

You might also like