TwinCAT_2_PLC_Control_EN (1)[001-045]
TwinCAT_2_PLC_Control_EN (1)[001-045]
1 Foreword
The responsible staff must ensure that the application or use of the products described satisfy all the
requirements for safety, including all the relevant laws, regulations, guidelines and standards.
Disclaimer
The documentation has been prepared with care. The products described are, however, constantly under
development.
We reserve the right to revise and change the documentation at any time and without prior announcement.
No claims for the modification of products that have already been supplied may be made on the basis of the
data, diagrams and descriptions in this documentation.
Trademarks
Beckhoff®, TwinCAT®, TwinCAT/BSD®, TC/BSD®, EtherCAT®, EtherCAT G®, EtherCAT G10®, EtherCAT P®,
Safety over EtherCAT®, TwinSAFE®, XFC®, XTS® and XPlanar® are registered trademarks of and licensed by
Beckhoff Automation GmbH.
Other designations used in this publication may be trademarks whose use by third parties for their own
purposes could violate the rights of the owners.
Patent Pending
The EtherCAT Technology is covered, including but not limited to the following patent applications and
patents:
EP1590927, EP1789857, EP1456722, EP2137893, DE102015105702
with corresponding applications or registrations in various other countries.
EtherCAT® is a registered trademark and patented technology, licensed by Beckhoff Automation GmbH,
Germany
Copyright
Exclusion of liability
All the components are supplied in particular hardware and software configurations appropriate for the
application. Modifications to hardware or software configurations other than those described in the
documentation are not permitted, and nullify the liability of Beckhoff Automation GmbH & Co. KG.
Personnel qualification
This description is only intended for trained specialists in control, automation and drive engineering who are
familiar with the applicable national standards.
Description of symbols
In this documentation the following symbols are used with an accompanying safety instruction or note. The
safety instructions must be read carefully and followed without fail!
DANGER
Serious risk of injury!
Failure to follow the safety instructions associated with this symbol directly endangers the life and health of
persons.
WARNING
Risk of injury!
Failure to follow the safety instructions associated with this symbol endangers the life and health of per-
sons.
CAUTION
Personal injuries!
Failure to follow the safety instructions associated with this symbol can lead to injuries to persons.
NOTE
Damage to the environment or devices
Failure to follow the instructions associated with this symbol can lead to damage to the environment or
equipment.
Tip or pointer
This symbol indicates information that contributes to better understanding.
In addition, the recommendations from Beckhoff regarding appropriate protective measures should be
observed. Further information regarding information security and industrial security can be found in our
https://www.beckhoff.com/secguide.
Beckhoff products and solutions undergo continuous further development. This also applies to security
functions. In light of this continuous further development, Beckhoff expressly recommends that the products
are kept up to date at all times and that updates are installed for the products once they have been made
available. Using outdated or unsupported product versions can increase the risk of cyber threats.
To stay informed about information security for Beckhoff products, subscribe to the RSS feed at https://
www.beckhoff.com/secinfo.
Table of contents
1 Foreword .................................................................................................................................................... 3
1.1 Notes on the documentation ............................................................................................................. 3
1.2 Safety instructions ............................................................................................................................. 4
1.3 Notes on information security............................................................................................................ 5
3 Sample Program...................................................................................................................................... 33
4 Individual Components........................................................................................................................... 42
4.1 The Main Window ........................................................................................................................... 42
4.2 Options ............................................................................................................................................ 44
4.3 Managing Projects .......................................................................................................................... 67
4.4 Objects ............................................................................................................................................ 88
4.5 Editing Functions........................................................................................................................... 100
4.6 Online Functions ........................................................................................................................... 104
4.7 Windows........................................................................................................................................ 113
4.8 Help System .................................................................................................................................. 114
4.9 Log ................................................................................................................................................ 114
TwinCAT PLC Control is a complete development environment for your PLC. TwinCAT PLC Control puts a
simple approach to the powerful IEC language at the disposal of the PLC programmer. Use of the editors
and debugging functions is based upon the proven development program environments of advanced
programming languages.
A project is put into a file named after the project. First a default Task Configuration is opened. The name of
the task is 'Standard'. The first POU (Program Organization Unit) created in a new project will automatically
be named MAIN. You can rename this POU in the task configuration. TwinCAT PLC Control differentiates
between the different kinds of objects in a project: POUs, data types and ressources. The Object Organizer
contains a list of all the objects in your project.
First you should select the target system. Then configure the task. You can create the POUs needed to solve
your problem. Now you can program the POUs you need in the desired languages. Once the programming is
complete, you can compile the project and remove errors should there be any.
Once all errors have been removed, log in to the PLC and "load" your project in the PLC. Now TwinCAT PLC
Control is in Online mode. Test your project for correct sequence. To do this, enter input variables manually
and observe whether outputs are as expected. You can also observe the value sequence of the local
variables in the POUs. In the Watch and Recipe Manager you can configure data records whose values you
wish to examine.
In case of a programming error you can set breakpoints. If the process stops at such a breakpoint, you can
examine the values of all project variables at this point in time. By working through sequentially (single step)
you can check the logical correctness of your program.
An additional TwinCAT PLC Control debugging function: You can set program variables and inputs and
outputs at certain values. You can use the flow control to check which program lines have been run. The
Sampling Trace allows you to trace and display the actual course of variables over an extended period of
time.
A Log records operations, user actions and internal processes during an online session in a chronological
order.
The entire project can be documented or exported to a text file at any time.
More Features:
The entire project can be documented or exported to a text file at any time. Also it can be translated into
another language.
ENI: The ENI interface ('Engineering Interface') allows to connect the Programming system to an external
data base. There the data which are needed during creation of an automation project can be stored. The
usage of an external data base guarantees the consistency of the data, which then can be shared by several
users, projects and programs.
Summary
TwinCAT PLC Control is a complete development tool used to program your PLC which will save you a
measurable amount of time setting up your applications.
Functions, function blocks, and programs are POUs, which can be supplemented by actions.
Each POU consists of a declaration part and a body. The body is written in one of the IEC programming
languages which include IL, ST, SFC, FBD, LD or CFC. TwinCAT PLC Control supports all IEC standard
POUs. If you want to use these POUs in your project, you must include the library standard.lib in your
project.
POUs can call up other POUs. However, recursions are not allowed.
Function
A function is a POU, which yields exactly one data element (which can consist of several elements, such as
fields or structures) when it is processed, and whose call in textual languages can occur as an operator in
expressions.
When declaring a function do not forget that the function must receive a type. This means, after the function
name, you must enter a colon followed by a type.
In addition, a result must be assigned to the function. That means that function name is used as an output
variable.
Example in IL of a function that takes three input variables and returns the product of the first two divided by
the third:
The call of a function in ST can appear as an operand in expressions. Functions do not have any internal
conditions. That means that calling up a function with the same argument (input parameters) always
produces the same value (output).
NOTE
Declaration
If you declare a local variable in a function as retain, this has no consequence. The variable is not stored in
the retain area.
LD 7
Fct 2,4
ST Result
in ST:
in FBD:
In SFC a function call can only take place within a step or a transition.
If you define a function in your project with the name CheckBounds [} 334], you can use it to check for range
overflows in your project! The name of the function is defined and may have only this identifier.
The following typical program for testing the CheckBounds function goes beyond the boundaries of a defined
array. The CheckBounds functions makes sure that the value TRUE is not assigned to the position A[10], but
rather to the upper area boundary A[7] which is still valid. Therefore, the CheckBounds function can be used
to correct extensions beyond array boundaries.
If you define functions in your project with the name CheckDivByte, CheckDivWord, CheckDivDWord and
CheckDivReal, you can use them to check the value of the divisor if you use the operator DIV, for example
to avoid a division by 0. The name of the function is defined and may have only this identifier.
If you define functions with the names CheckRangeSigned and CheckRangeUnsigned, then range
exceeding of variables declared wit subrange types can be intercepted.
All these check function names are reserved for the described usage.
Functionblock
A function block is a POU which provides one or more values during the procedure. As opposed to a
function, a function block provides no return value.
Example in IL of a function block with two input variables and two output variables. One output is the product
of the two inputs, the other a comparison for equality:
Reproductions or instances (copies) of a function block can be created. Each instance possesses its own
identifier (the Instance name), and a data structure which contains its inputs, outputs, and internal variables.
Instances are declared locally or globally as variables, whereas the name of the function block is indicated
as the type of an identifier.
Example of an instance with the name INSTANCE of the FUB function block:
INSTANCE: FUB;
Function blocks are always called through the instances described above.
Only the input and output parameters can be accessed from outside of an function block instance, not its
internal variables.
PROGRAM prog
VAR
inst1:fb;
END_VAR
LD 17
ST inst1.in1
CAL inst1
END_PROGRAM
The declaration parts of function blocks and programs can contain instance declarations. Instance
declarations are not permitted in functions.
Access to a function block instance is limited to the POU in which it was declared unless it was declared
globally. The instance name of a function block instance can be used as the input for a function or a function
block.
All values are retained after processing a function block until the next it is processed. Therefore, function
block calls with the same arguments do not always return the same output values!
If the function block contains at least one retain variable, the entire instance is stored in the retain area.
The input and output variables of a function block can be accessed from another POU by setting up an
instance of the function block and specifying the desired variable using the following syntax:
<Instance name>.<Variable name>
If you would like to set the input parameters (thus the value of the inputvariables) when you open the
function block, you can do this in the text languages IL and ST by assigning values to the parameters after
the instance name of the function block in parentheses (this assignment takes place using ":=" just as with
the initialization of variables at the declaration position).
Please note, that the input/output variables (VAR_IN_OUT) of a POU will be turn over as a pionter.
Therefore no constants can be assigned to them at a call, and an external read or write access is impossible.
Example for the call of a VAR_IN_OUT variable inout1 of the POU fubo in ST:
VAR
inst:fubo;
var1:int;
END_VAR
var1:=2;
inst(inout1:=var1);
Examples for calling function block FUB described above. The multiplication result is saved in the variable
ERG, and the result of the comparison is saved in QUAD. An instance of FUB with the name INSTANCE is
declared:
In the example below the call is shown in ST. The declaration part is the same as with IL:
In FBD it would look as follows (declaration part the same as with IL):
Program
A program is a POU which returns several values during operation. Programs are recognized globally
throughout the project. All values are retained from the last time the program was run until the next.
Programs can be called. A program call in a function is not allowed. There are also no instances of
programs. If a POU calls a program, and if thereby values of the program are changed, then these changes
are retained the next time the program is called, even if the program has been called from within another
POU. This is different from calling a function block. There only the values in the given instance of a function
block are changed. These changes therefore play a role only when the same instance is called. A program
declaration begins with the keyword PROGRAM and ends with END_PROGRAM.
In IL:
CAL PRG Example
LD PRGexample.PAR
ST ERG
in ST:
PRGExample;
Erg := PRGexample.PAR;
In FBD:
If the variable PAR from the program PRGexample is initialized by a main program with 0, and then one after
the other programs are called with above named program calls, then the ERG result in the programs will
have the values 1, 2, and 3. If one exchanges the sequence of the calls, then the values of the given result
parameters also change in a corresponding fashion.
Action
As addition to function blocks and programs you can define actions. An action is an further implementation. It
can be written in a different language than the 'normal' implementation. Each action gets a name.
An action works with the data of the accompanying function block or program. It uses the same input/output
variables and local variables like the 'normal' implementation..
When function block Counter is called, the output variable gets increased or decreased depending on the
input variable 'in'. When action Reset, affiliated to the function block is called, the output variable is set to 0.
In both cases the same variable out is written.
An action is called with <program name>.<action name> respectively <instance name>.<action name>. If the
action should be called within the 'mother' module, in text editors only the action name is used, in graphical
editors the function block call without instance name.
Example
In AWL:
CAL Inst.Reset(In := FALSE)
LD Inst.out
ST ERG
In ST:
Inst.Reset(In := FALSE);
Erg := Inst.out;
In FBD:
See Chapter SFC [} 24] for more information about SFC Actions.
Ressourcen
You need the ressources for configuring and organizing your project and for tracing variable values:
• Global Variables which can be used throughout the project
• PLC Configuration for configuring your hardware
• Task Configuration for guiding your program through tasks
• Sampling Trace for graphic display of variable values
• Watch and Recepe Manager for displaying variable values and setting default variable values
Libraries
You can include in your project a series of libraries whose POUs, data types, and global variables you can
use just like user-defined variables. The library "standard.lib" is a standard part of the program and is always
at your disposal.
Data types
Along with the standard data types the user can define his own data types. Structures, enumeration types
and references can be created.
See 'Standard [} 295]-' and 'User Defined Datatypes [} 295]' in the appendix.
2.2 Languages
texual languages
• Instruction List (IL) [} 16]
• Structured Text (ST) [} 18]
grafical languages
• Function Block Diagram (FBD) [} 28]
• Ladder Diagram (LD) [} 29]
• Continous Function Chart (CFC) [} 28]
• Sequential Function Chart (SFC) [} 24]
A comment must be the last element in a line. Empty lines can be inserted between instructions.
Example:
LD 17
ST lint (* comment *)
GE 5
JMPC next
LD idword
EQ istruct.sdword
STN test
next:
Modifiers:
• C with JMP, CAL, RET: The instruction is only then executed if the result of the preceding expression is
TRUE.
• N with JMPC, CALC, RETC: The instruction is only then executed if the result of the preceding
expression is FALSE.
• N otherwise: Negation of the operand (not of the accumulator)
Below you find a table of all operators in IL with their possible modifiers and the relevant meaning:
JMPC label (*if the result was TRUE, then jump to the
label "label"*)
label:
It is also possible in IL to put parentheses after an operation. The value of the parenthesis is then considered
as an operand.
For example:
LD 2
MUL 2
ADD 3
ST Erg
MUL( 2
ADD 3
ST Erg
Here the resulting value for Erg is 10, then the operation MUL is only then evaluated if you come to ")"; as
operand for MUL 5 is then calculated.
Example:
IF value < 7 THEN
value := value + 1;
END_WHILE;
END_IF;
Expressions
An expression is a construction which returns a value after its evaluation. Expressions are composed of
operators and operands. An operand can be a constant, a variable, a function call, or another expression.
Valuation of expressions
The evaluation of expression takes place by means of processing the operators according to certain binding
rules. The operator with the strongest binding is processed first, then the operator with the next strongest
binding, etc., until all operators have been processed. Operators with equal binding strength are processed
from left to right.
Below you find a table of the ST operators in the order of their binding strength:
There are the following instructions in ST, arranged in a table together with example:
Instruction Example
Assignment A:=B; CV := CV + 1; C:=SIN(X);
Calling a function block and use of the FB version CMD_TMR(IN := %IX5, PT := 300);A:=CMD_TMR.Q;
RETURN RETURN;
IF IF D<0.0
THEN C:=A;
ELSIF D=0.0
THEN C:=B;
ELSE C:=D;
END_IF;
CASE CASE INT1 OF
1: BOOL1 := TRUE;
2: BOOL2 := TRUE;
ELSE
BOOL1 := FALSE;
BOOL2 := FALSE;
END_CASE;
FOR FOR I:=1 TO 100 BY 2 DO
IF ARR[I] = 70
THEN J:=I;
EXIT;
END_IF;
END_FOR;
WHILE WHILE J<= 100 AND ARR[J] <> 70 DO
J:=J+2;
END_WHILE;
REPEAT REPEAT J:=J+2;
UNTIL J= 101 OR ARR[J] = 70
END_REPEAT;
EXIT EXIT;
Empty instruction ;
The name already indicates, the structured text is designed for structure programming, i.e. ST offers
predetermined structures for certain often used constructs such as loops for programming. This offers the
advantages of low error probability and increased clarity of the program.
For example, let us compare two equally significant program sequences in IL and ST:
LD
Var1
MUL
2
ST Var1
LD
Counter
SUB
1
ST Counter
JMP
Loop
End:
LD Var1
ST ERG
Var1:=Var1*2;
Counter:=Counter-1;
END_WHILE
Erg:=Var1;
You can see, the loop in ST is not only faster to program, but is also significantly easier to read, especially in
view of the convoluted loops in larger constructs.
Assignment operator
On the left side of an assignment there is an operand (variable, address) to which is assigned the value of
the expression on the right side with the assignment operator :=
After completion of this line Var1 has the tenfold value of Var2.
A function block is called in ST by writing the name of the instance of the function block and then assigning
the values of the parameters in parentheses. In the following example a timer is called with assignments for
the parameters IN and PT. Then the result variable Q is assigned to the variable A.
The result variable, as in IL, is addressed with the name of the function block, a following point, and the
name of the variable:
INT_Var :INT;
<instructions>
END_FOR;
The <Instructions> are executed as long as the counter <INT_Var> is not greater than the <END_VALUE>.
This is checked before executing the <Instructions> so that the <instructions> are never executed if
<INIT_VALUE> is greater than <END_VALUE>. When <Instructions> are executed, <INT_Var> is always
increased by <Step size>. The step size can have any integer value. If it is missing, then it is set to 1. The
loop must also end since <INT_Var> only becomes greater.
Example:
FOR counter:=1 TO 5 BY 1 DO
Var1:=Var1*2;
END_FOR;
Erg:=Var1;
Let us assume that the default setting for Var1 is the value 1. Then it will have the value 32 after the FOR
loop.
The <END_VALUE> can not be the limit of the counter <INT_VAR>.E.g. if the variable counter is of type
SINT, and if <END_VALUE> is 127, you get an endless loop.
Syntax:
REPEAT
<instructions>
END_REPEAT;
The <Instructions> are carried out until the <Boolean expression> returns TRUE. If <Boolean expression> is
produced already at the first TRUE evaluation, then <Instructions> are executed only once. If
<Boolean_expression> never assumes the value TRUE, then the <Instructions> are repeated endlessly
which causes a relative time delay.
The programmer must make sure that no endless loop is caused. He does this by changing the condition in
the instruction part of the loop, for example by counting up or down one counter.
Example:
REPEAT
Var1 := Var1*2;
Counter := Counter-1;
UNTIL
Counter=0
END_REPEAT
Syntax:
WHILE <Boolean expression> DO
<instruction>
END_WHILE;
The <Instructions> are repeatedly executed as long as the <Boolean_printout> returns TRUE. If the
<Boolean_printout> is already FALSE at the first evaluation, then the <Instructions> are never executed. If
<Boolean_printout> never assumes the value FALSE, then the <Instructions> are repeated endlessly which
causes a relative time delay.
The programmer must make sure that no endless loop is caused. He does this by changing the condition in
the instruction part of the loop, for example, by counting up or down one counter.
Example:
WHILE counter<>0 DO
Var1 := Var1*2;
counter := counter-1;
END_WHILE
The WHILE and REPEAT loops are, in a certain sense, more powerful than the FOR loop since one doesn't
need to know the number of cycles before executing the loop. In some cases one will, therefore, only be able
to work with these two loop types. If, however, the number of the loop cycles is clear, then a FOR loop is
preferable since it allows no endless loops.
2.2.3.4 IF instruction
With the IF instruction you can check a condition and, depending upon this condition, execute instructions.
Syntax:
IF <Boolean_printout1> THEN
<IF_instructions>
<ELSIF_instructions1>
<ELSIF_instructions n-1>
ELSE
<ELSE_instructions>}
END_IF;
If the <Boolean_printout1> returns TRUE, then only the <IF_Instructions> are executed and none of the
other instructions. Otherwise the Boolean expressions, beginning with <Boolean_printout2>, are evaluated
one after the other until one of the expressions returns TRUE. Then only those instructions after this Boolean
expression and be-fore the next ELSE or ELSIF are evaluated. If none of the Boolean expressions produce
TRUE, then only the <ELSE_instructions> are evaluated.
Sample:
IF temp<17
END_IF;
Here the heating is turned on when the temperature sinks below 17 degrees. Otherwise it remains off.
<Value 1>:
<instruction 1>
<Value 2>:
<instruction 2>
...
<Value n>:
<instruction n>
ELSE
<ELSE-instruction>
END_CASE;
Example:
CASE INT1 OF
1, 5:
BOOL1 := TRUE;
BOOL3 := FALSE;
2:
BOOL2 := FALSE;
BOOL3 := TRUE;
ELSE
END_CASE;
Step
A POU written in a sequential function chart consists of a series of steps which are connected with each
other through directed connections (transitions).
There are two types of steps.
• The simplified type consists of an action and a flag which shows if the step is active. If the action of a
step is implemented, then a small triangle appears in upper right corner of the step.
• An IEC step consists of a flag and one or more assigned actions. The associated actions appear to the
right of the step.
Action
An action can contain a series of instructions in IL or in ST, a lot of networks in FBD or in LD, or again in
sequential function chart (SFC). With the simplified steps an action is always connected to a step. In order to
edit an action, click twice with the mouse on the step to which the action belongs. Or select the step and
select the menu command "Extras" "Zoom Action/Transition". In addition, one input or output action per step
is possible.
Actions of IEC steps hang in the Object Organizer directly under their SFC-POU and are loaded with a
doubleclick or by pressing <Enter> in their editor. New actions can be created with "Project" "Add Action"..
Additional to a step action you can add an entry action and an exit action to a step. An entry action is
executed only once, right after the step has become active. An exit action is executed only once before the
step is deactivated. A step with entry action is indicated by an "E" in the lower left corner, the exit action by
an "X" in the lower right corner. The entry and exit action can be implemented in any language. In order to
edit an entry or exit action, doubleclick in the corresponding corner in the step with the mouse. An entry and
exit action can only be defined to a simplified step, but not to an IEC step.
Transition/Transition condition
Between the steps there are so-called transitions. A transition condition must have the value TRUE or
FALSE. Thus it can consist of either a boolean variable, a boolean address or a boolean constant. It can also
contain a series of instructions having a boolean result, either in ST syntax (e.g. (i<= 100) AND b) or in any
language desired (see 'Extras” “Zoom Action/Transition”). But a transition may not contain programs,
function blocks or assignments!
Note:
Besides transitions, inching mode can also be used to skip to the next step; see SFCtip and SFCtipmode.
Active Step
After calling the SFC POU, the action (surrounded by a double border) belonging to the initial step is
executed first. A step, whose action is being executed, is called active. If the step is active, then the
appropriate action is executed once per cycle. In Online mode active steps are shown in blue. To each step
belongs a flag which saves the condition of the step. The step flag (active or inactive condition of the step) is
shown by the logical value of a Boolean structure element <StepName>.x. This Boolean variable has the
value TRUE if the appropriate step is active and FALSE if it is inactive. This variable is implicitly declared and
can be used in any action and transition of the SFC POU.In a control cycle all actions are executed which
belong to active steps. Thereafter the respective following steps of the active steps become active if the
transition conditions of the following steps are TRUE. The currently active steps will be executed in the next
cycle.
If the active step contains an output action, this will only be executed during the next cycle, provided that the
transition following is TRUE.
IEC step
Along with the simplified steps the standard IEC steps in SFC are available. In order to be able to use IEC
steps, you must link the library TcSystem.Lib into your project.
Any number of actions can be assigned to an IEC step. IEC actions are not fixed as input, step or output
actions to a certain step as in the simplified steps, but are stored separately from the steps and can be
reused many times within a POU. For this they must be associated to the single steps with the command
'Extras''Associate action'.
An associated boolean variable is set or reset with each call of the SFC block. That means, that with each
call the value changes from TRUE or FALSE or back again.
The actions associated with an IEC step are shown at the right of the step in a two-part box. The left field
contains the qualifier, possibly with time constant, and the right field contains the action name.
In order to make it easier to follow the processes, all active actions in on-line mode are shown in blue like the
active steps. After each cycle a check is made to see which actions are active.
Pay attention here also to the restrictions on the use of time-qualifiers in actions that are repeatedly re-used
within the same cycle.
If an action has been inactivated, it will be executed once more. That means, that each action is executed at
least twice (also an action with qualifier P). In case of a call first the deactivated actions, then the active
actions are executed, in alphabetical order each time.
Whether a newly inserted step is an IEC step depends upon whether the menu command "Extras" "Use
IEC-Steps" has been chosen.
In the Object Organizer the actions hang directly underneath their respective SFC POUs. New actions can
be created with "Project" "Add Action". In order to use IEC steps you must include in your project the special
SFC library lecsfc.lib .
In order to associate the actions with IEC steps the following qualifiers are available:
If the same action is used with qualifiers in two straight sequently steps, which influence the time flow, the
time qualifier can´t become operative at the second use. To avoid this, an intermediate step has to be
inserted. Thus the action status can be initialised anewd in the additional passing through cycle.
There are implicitly declared variables in the SFC which can be used. A flag belongs to each step which
stores the state of the step. The step flag (active or inactive state of the step) is called <StepName>.x for IEC
steps or <StepName> for the simplified steps. This Boolean variable has the value TRUE when the
associated step is active and FALSE when it is inactive. It can be used in every action and transition of the
SFC block. One can make an enquiry with the variable <ActionName>.x. as to whether an IEC action is
active or not.
Alternative branch
Two or more branches in SFC can be defined as alternative branches. Each alternative branch must begin
and end with a transition. Alternative branches can contain parallel branches and other alternative branches.
An alternative branch begins at a horizontal line (alternative beginning) and ends at a horizontal line
(alternative end) or with a jump.
If the step which precedes the alternative beginning line is active, then the first transition of each alternative
branch is evaluated from left to right. The first transition from the left whose transition condition has the value
TRUE is opened and the following steps are activated.
For IEC steps the implicit variables <StepName>.t can be used to enquire about the active time of the steps.
Implicit variables can also be accessed by other programs. Example: boolvar1:=sfc.step1.x; Here, step1.x is
the implicit boolean variable representing the state of IEC step step1 in POU sfc1.
Parallel branch
Two or more branches in SFC can be defined as parallel branches. Each parallel branch must begin and end
with a step. Parallel branches can contain alternative branches or other parallel branches. A parallel branch
begins with a double line (parallel beginning) and ends with a double line (parallel end) or with a jump.
If the parallel beginning line of the previous step is active and the transition condition after this step has the
value TRUE, then the first steps of all parallel branches become active (see active step). These branches
are now processed parallel to one another. The step after the parallel end line becomes active when all
previous steps are active and the transition condition before this step produces the value TRUE.
Jump
A jump is a connection to the step whose name is indicated under the jump symbol. Jumps are required
because it is not allowed to create connections which lead upward or cross each other.
An example of a typical network in the function block diagram as it could appear in TwinCAT PLC Control :
On the one hand, the ladder diagram is suitable for constructing logical switches, on the other hand one can
also create networks as in FBD. Therefore the LD is very useful for controlling the call of other POUs. More
about this later. The ladder diagram consists of a series of networks. A network is limited on the left and right
sides by a left and right vertical current line. In the middle is a circuit diagram made up of contacts, coils, and
connecting lines.
Each network consists on the left side of a series of contacts which pass on from left to right the condition
"ON" or "OFF" which correspond to the Boolean values TRUE and FALSE. To each contact belongs a
Boolean variable. If this variable is TRUE, then the condition is passed from left to right along the connecting
line. Otherwise the right connection receives the value OFF.
Example of a typical network in the ladder diagram as it could appear in TwinCAT PLC Control :
Contact
Each network in LD consists on the left side of a network of contacts (contacts are represented by two
parallel lines: | |) which from left to right show the condition "On" or "Off". These conditions correspond to the
Boolean values TRUE and FALSE. A Boolean variable belongs to each contact. If this variable is TRUE,
then the condition is passed on by the connecting line from left to right, otherwise the right connection
receives the value "Out". Contacts can be connected in parallel, then one of the parallel branches must
transmit the value "On" so that the parallel branch transmits the value "On"; or the contacts are connected in
series, then contacts must transmit the condition "On" so that the last contact transmits the "On" condition.
This therefore corresponds to an electric parallel or series circuit. A contact can also be negated,
recognizable by the slash in the contact symbol: |/|. Then the value of the line is transmitted if the variable is
FALSE.
Coil
On the right side of a network in LD there can be any number of so-called coils which are represented by
parentheses:( ). They can only be in parallel. A coil transmits the value of the connections from left to right
and copies it in an appropriate Boolean variable. At the entry line the value ON (corresponds to the Boolean
variable TRUE) or the value OFF (corresponding to FALSE) can be present. Contacts and coils can also be
negated (in the example the contact SWITCH1 and the coil %QX3.0 is negated). If a coil is negated
(recognizable by the slash in the coil symbol: (/)), then it copies the negated value in the appropriate Boolean
variable. If a contact is negated, then it connects through only if the appropriate Boolean value is FALSE.
Along with contacts and coils you can also enter function blocks and programs. In the network they must
have an input and an output with Boolean values and can be used at the same places as contacts, that is on
the left side of the LD network
Set/Reset coils
Coils can also be defined as set or reset coils. One can recognize a set coil by the "S" in the coil symbol: (S))
It never writes over the value TRUE in the appropriate Boolean variable. That is, if the variable was once set
at TRUE, then it remains so. One can recognize a reset coil by the "R" in the coil symbol: (R)) It never writes
over the value FALSE in the appropriate Boolean variable: If the variable has been once set on FALSE, then
it remains so.
LD as FBD
When working with LD it is very possible that you will want to use the result of the contact switch for
controlling other POUs. On the one hand you can use the coils to put the result in a global variable which
can then be used in another place. You can, however, also insert the possible call directly into your LD
network. For this you introduce a POU with EN input. Such POUs are completely normal operands,
functions, programs, or function blocks which have an additional input which is labeled with EN. The EN
input is always of the BOOL type and its meaning is: The POU with EN input is evaluated when EN has the
value TRUE. An EN POU is wired parallel to the coils, whereby the EN input is connected to the connecting
line between the contacts and the coils. If the ON information is transmitted through this line, this POU will be
evaluated completely normally. Starting from such an EN POU, you can create networks similar to FBD.
The sampling trace allows you to trace the value sequence of variables, depending upon the so-called
trigger event. This is the rising edge or falling edge of a previously defined Boolean variable (trigger
variable). TwinCAT PLC Control permits the tracing of up to 20 variables. There is a 64 kB ring buffer.
Debugging [} 104]
The debugging functions of TwinCAT PLC Control make it easier for you to find errors.
Breakpoint
A breakpoint is a place in the program at which the processing is stopped. Thus it is possible to look at the
values of variables at specific places within the program.
Breakpoints can be set in all editors. In the text editors breakpoints are set at line numbers, in FBD and LD at
network numbers, and in SFC at steps.
No breakpoints can be set in function block instances.
Single step
By proceeding step by step you can check the logical correctness of your program.
Single cycle
If Single cycle has been chosen, then the execution is stopped after each cycle.
During operations variables can be set once at a certain value (write value) or also described again with a
certain value after each cycle (force value). In online mode one also can change the variable value by double
click on the value. By that boolean variables change from TRUE to FALSE or the other way round, for each
other types of variables one gets the dialog Write Variable xy, where the actual value of the variable can be
edited.
Monitoring
In Online mode, all displayable variables are read from the controller and displayed in real time. You will find
this display in the declarations and program editor; you can also read out current values of variables in the
watch and recipe manager and in a visualization. If variables from instances of function blocks are to be
monitored, the corresponding instance must first be opened.
In monitoring VAR_IN_OUT variables, the de-referenced value is output. With a simple click on the cross
or a double-click on the line, the display is either expanded or truncated.
In monitoring pointers, both the pointer and the de-referenced value are output in the declaration portion.
In the program portion, only the pointer is output:
+ --pointervar = '<'pointervalue'>'
Simulation
During the simulation the created PLC program is not processed in the PLC, but rather in the calculator on
which TwinCAT PLC Control is running. All online functions are available. That allows you to test the logical
correctness of your program without PLC hardware.
Simulation mode is only available for the Buscontroller (BCxx00). If you use TwinCAT on the PC (Code
generation i386) you can simulate the program direct in the runtime system without having physical I/O.
Log
The log chronologically records user actions, internal processes, state changes and exceptions during
Online mode processing. It is used for monitoring and for error tracing.
• R. W. Lewis: Programming industrial control systems using IEC 1131-3, London: IEC Publishing, 1998.
ISBN 0 85296 950 3
3 Sample Program
Let us now start to write a small example program. It is for a small traffic signal unit which is supposed to
control two trafficsignals at an intersection. The red/green phases of both trafficsignals alternate and, in order
to avoid accidents, we will insert between the phases yellow or yellow/red transitional phases. The latter will
be shorter than the former. In this example you will see how time dependent programs can be shown with
the language ressources of the IEC61131-3 standard, how one can edit the different languages of the
standard with the help of TwinCAT PLC Control.
Create POU
First start TwinCAT PLC Control and choose "File" "New". In the dialog box which appears, the first POU
should have the name PLC_PRG. The type of POU should definitely be a program. In this case we choose
as the language of this POU the sequential function chart (SFC). Now create two more objects with the
command "Project" "Object Add" with the menu bar or with the context menu (press right mouse button in the
Object Organizer). A function block in the language Function Block Diagram (FBD) by the names of
TRAFFICSIGNAL, along with a POU WAIT, also of the type function block, which we want to program as an
instruction list (IL).
In the POU TRAFFICSIGNAL we will assign the individual trafficsignal phases to the lights, i.e. we will make
sure that the red light is lit red in the red phase and in the yellow/red phase, the yellow light in the yellow and
yellow/red phases, etc.
In WAIT we will program a simple timer which as input will receive the length of the phase in milliseconds,
and as output will produce TRUE as soon as the time period is finished.
PLC_PRG will combine everything at the end so that the right light lights up at the right time for the desired
time period.
Let us now turn to the POU TRAFFICSIGNAL. In the declaration editor you declare as input variable
(between the keywords VAR_INPUT and END_VAR) a variable named STATUS of the type INT. STATUS
will have five possible conditions, that is one for the TRAFFICSIGNAL phases green, yellow, yellow/red, red,
and off.
Therefore our TRAFFICSIGNAL has four outputs, that is RED, YELLOW, GREEN, and OFF. You should
declare these four variables. Then the declaration part of our function block TRAFFICSIGNAL will look like
this:
Now it is time to determine from the input STATUS of the POU the values of the output variables. For this go
into the body of the POU. Click on the field to the left beside the first network (the gray field with the number
1). You have now selected the first network. Now choose the menu item "Insert" "Operator". In the first
network a box is inserted with the operator AND and two inputs:
Click on the text AND with the mouse pointer and change the text into EQ. Select the three question marks
from the upper of the two inputs and enter the variable STATUS. Then select the lower of the three question
marks and put a 1 underneath it. You get the following network:
Click now on a place behind the EQ Box. Now the output of the EQ operation is selected. Choose "Insert"
"Assignment". Change the three question marks ??? to GREEN. You now have created a network with the
following structure:
STATUS is compared with 1, the result is assigned to GREEN. This network thus switches to GREEN if the
preset state value is 1.For the other TRAFFICSIGNAL colors or for OFF we need three more net-works. You
create them with the command "Insert" "Network (after)". These networks should be set up as in the
example. The finished POU now is as follows:
In order to insert an operator in front of another operator, you must select the place where the input to which
you want to attach the operator feeds into the box. Then use the command "Insert" "Operator". Otherwise
you can setup these networks in the same way as the first network. Now our first POU has been finished.
TRAFFICSIGNAL, according to the input of the value STATUS, controls whichever light color we wish.
For the timer in the POU WAIT we need a POU from the standard library. Therefore, open the library
manager with "Window" "Library Manager". Choose "Insert" "Additional library". The dialog box appears for
opening files. From the list of the libraries choose standard.lib.
Now let us turn to the POU WAIT. This POU is supposed to become a timer with which we can determine the
length of the time period of each TRAFFICSIGNAL phase. Our POU receives as input variable a variable
TIME of the type TIME, and as output it produces a Boolean value which we want to call OK and which
should be TRUE when the desired time period is finished. We set this value with FALSE by inserting at the
end of the declaration (before the semicolon, however) " := FALSE ".
For our purposes we need the POU TP, a clock generator. This has two inputs (IN, PT) and two outputs (Q,
ET). TP does the following:
As long as IN is FALSE, ET is 0 and Q is FALSE. As soon as IN provides the value TRUE, the time is
calculated at the output ET in milliseconds. When ET reaches the value PT, then ET is no longer counted.
Meanwhile Q produces TRUE as long as ET is smaller than PT. As soon as the value PT has been reached,
then Q produces FALSE again. In addition you will find a short description of all POUs from the standard
library in the appendix.
In order to use the POU TP in the POU WAIT we must create a local instance from TP. For this we declare a
local variable ZAB (for elapsed time) of the type TP (between the keywords VAR, END_VAR). The
declaration part of WAIT thus looks like this:
In order to create the desired timer, the body of the POU must be programmed as follows:
At first the question is posed whether Q has already been set at TRUE (as though the counting had already
been executed), in this case we change nothing with the occupation of ZAB, but rather we call the function
block ZAB without input (in order to check whether the time period is already over).
Otherwise we set the variable IN in ZAB at FALSE, and therefore at the same time ET at 0 and Q at FALSE.
In this way all variables are set at the desired initial condition. Now we assign the necessary time from the
vari-able TIME into the variable PT, and call ZAB with IN:=TRUE. In the function block ZAB the variable ET
is now calculated until it reaches the value TIME, then Q is set at FALSE.
The negated value of Q is saved in OK after each execution of WAIT. As soon as Q is FALSE, then OK
produces TRUE.
The timer is finished at this point. Now it is time to combine our two function blocks WAIT and
TRAFFICSIGNAL in the main program PLC_PRG.
First we declare the variables we need. They are two instances of the function block TRAFFICSIGNAL
(TRAFFICSIGNAL1, TRAFFICSIGNAL2) and one of the type WAIT (DELAY as delay). PLC_PRG now
appears as follows:
The beginning diagram of a POU in SFC always consists of an action "Init" of a following transition "Trans0"
and a jump back to Init. We should expand that somewhat.
First let us determine the structure of the diagrams before we program the individual action and transitions.
First we need for each TRAFFICSIGNAL phase a step.. Insert it by marking Trans0 and choosing "Insert"
"Step transition (behind)". Repeat this procedure three more times.
If you click directly on the name of a transition or a step, then this is marked and you can change it. Name
the first transition after Init "TRUE", and all other transitions "DELAY.OK".
The first transition always switches through, and all others switch through when DELAY in OK produces
TRUE, i.e. when the set time period is finished.
The steps (from top to bottom) receive the names Switch1, Green2, Switch2, Green1, whereby Init of course
keeps its Name. "Switch" should mean each time a yellow phase, at Green1 TRAFFICSIGNAL1 at Green2
TRAFFICSIGNAL2 will be green. Finally change the return address of Init after Switch1. If you have done
everything right, then the diagram should be as follows:
Now we have to finish programming the individual steps. If you doubleclick on the field of a step, then you
open a dialog to open a new action. In our case we will use IL (Instruction list).
In the action of the step Init the variables are initialized, the STATUS of TRAFFICSIGNAL1 should be 1
(green). The state of TRAFFICSIGNAL2 should be 3 (red). The action Init then is as follows:
Action Init
Switch1 changes the State of TRAFFICSIGNAL1 to 2 (yellow), and that of TRAFFICSIGNAL2 to 4 (yellow-
red). In addition, a time delay of 2000 milli-seconds is now set. The action is now as follows:
Action Switch1
With Green2 TRAFFICSIGNAL1 is red (STATUS:=3), TRAFFICSIGNAL2 green (STATUS:=1), and the delay
time is at 5000.
Action Green2
Action Switch2
With Green1 TRAFFICSIGNAL1 is green (STATUS:=1), TRAFFICSIG-NAL2 is red (STATUS:=3), and the
time delay is set at 5000.
Action Green1
The first expansion phase of our program is completed. Now you can com-pile it and also test the simulation.
In order to ensure that our diagram has at least one alternative branch, and so that we can turn off our traffic
light unit at night, we now include in our program a counter which, after a certain number of
TRAFFICSIGNAL cycles, turns the unit off.
At first we need a new variable COUNTER of the type INT. Declare this as usual in the declaration part of
PLC_PRG, and initialize it in Init with 0.
Now select the transition after Switch1 and insert a step and then a transition. Select the resulting transition
and insert an alternative branch to its left. After the left transition insert a step and a transition. After the
resulting new transition insert a jump after Switch1. Select the transition below the new step. Open the
context menu and select "Zoom action/transition". Select IL for the language of the transition.
Name the new parts as follows: the upper of the two new steps should be called "Count" and the lower "Off".
The transitions are called (from top to bottom and from left to right) EXIT, TRUE and DELAY.OK. The new
part should therefore look like the part with the black border:
Now two new actions and a new transition condition are to be implemented. At the step Count, the only thing
that happens is that COUNTER is increased by one:
The EXIT transition checks whether the counter is greater than a certain number, let us say 7:
At Off the state of both lights is set at (OFF), the COUNTER is reset to 0, and a time delay of 10 seconds is
set:
In our hypothetical situation, night falls after seven TRAFFICSIGNAL cycles, for ten seconds the
TRAFFICSIGNAL turns itself off, then we have daylight again, the traffic light unit turns itself on again, and
the whole process starts again from the beginning.
Now test your program. For this you must compile it ("Project" "Rebuild all") login ("Online" "Login" and then
load it "Online" "Download"). If you now select "Online" "Run", the chronological order of the individual steps
of your main program can be followed. The window of the POU PLC_PRG has now changed to the monitor
window. Click twice on the plus sign in the declaration editor, the variable display drops down, and you can
see the values of the individual variables.
4 Individual Components
The following elements are found in the main window of TwinCAT PLC Control (from top to bottom):
• The menu bar
• The tool bar (optional); with buttons for faster selection of menu commands.
• The Object Organizer with register cards for POUs, Data types, and Ressources
• A vertical screen divider between the Object Organizer and the Work space of TwinCAT PLC Control
• The Work space in which the editor windows are located
• The message window (optional)
• The Status bar (optional); with information about the current status of the project
Menu bar
The menu bar is located at the upper edge of the main window. It contains all menu commands.
Tool bar
By clicking with the mouse on a symbol you can select a menu command more quickly. The choice of the
available symbols automatically adapts itself to the active window. The command is only carried out when
the mouse button is pressed on the symbol and then released. If you hold the mouse pointer for a short time
on a symbol in the tool bar, then the name of the symbol is shown in a Tooltip. In order to see a description
of each symbol on the tool bar, select in Help the editor about which you want information and click on the
tool bar symbol in which you are interested. The display of the tool bar is optional (see "Project" "Options"
category Desktop).
Object Organizer
The Object Organizer is always located on the left side of TwinCAT PLC Control. At the bottom there are four
register cards with symbols for the four types of objects POUs, Data types, and Ressources. In order to
change between the respective object types click with the mouse on the corresponding register card or use
the left or right arrow key.
You will learn in chapter Objects [} 88], how to work with the objects in the Object Organizer.
Object Organizer
Screen divider
The screen divider is the border between two non-overlapping windows. In TwinCAT PLC Control there are
screen dividers between the Object Organizer and the Work space of the main window, between the
interface (declaration part) and the implementation (instruction part) of POUs and between the Work space
and the message window.
You can move the screen divider with the mouse pointer. You do this by moving the mouse with the left
mouse button pressed.
Make sure the the screen divider always remains at its absolute position, even when the window size has
been changed. If it seems that the screen divider is no longer present, then simply enlarge your window.
Work space
The Work space is located on the right side of the main window in TwinCAT PLC Control. All editors for
objects and the library manager are opened in this area. You find the description of the editors in the chapter
Editors in TwinCAT PLC Control, The Ressources, and Library Manager. Under the menu item "Window"
you find all commands for window management.
Message window
The message window is separated by a screen divider underneath the work space in the main window. It
contains all messages from the previous compilations, checks , or comparisons. If you doubleclick with the
mouse in the message window on a message or press <Enter>, the editor opens with the object. The
relevant line of the object is selected. With the commands "Edit" "Next error" and "Edit" "Previous error" you
can can quickly jump between the error messages. The display of the message window is optional (see
"Window" "Messages").
Status bar
The status bar at the bottom of the window frame of the main window in TwinCAT PLC Control gives you
information about the current project and about menu commands. If an item is relevant, then the concept
appears on the right side of the status bar in black script, otherwise in gray script. When you are working in
online mode, the concept Online appears in black script. If you are working in the offline mode it appears in
gray script. In Online mode you can see from the status bar whether you are in the simulation (SIM), the
program is being processed (RUNS), a breakpoint is set (BP), or variables are being forced (FORCE).
With text editor the line and column number of the current cursor position is indicated (e.g. Line:5, Col.:11). If
you have chosen a menu command but haven't yet confirmed it, then a short description appears in the
status bar. The display of the statusbar is optional (see "Project" "Options" category Desktop).
Instead of using the menu bar for executing a command, you can use the right mouse button. The menu
which then appears contains the most frequently used commands for a selected object or for the active
editor. The choice of the available commands adapts itself automatically to the active window.
4.2 Options
About TwinCAT PLC Control there can be of course only one viewpoint. In TwinCAT PLC Control, however,
you can configure the view of the main window (and have more than one viewpoint). In addition you can
make other settings. For this you have the command "Project" Options" at your disposal. The settings you
make thereby are, unless determined otherwise, saved in the file "TwinCAT PLC Control.ini" and restored at
the next TwinCAT PLC Control startup.
'Project' 'Options'
With this command the dialog box for setting options is opened. The options are divided into different
categories. Choose the desired category on the left side of the dialog box by means of a mouse click or
using the arrow keys and change the options on the right side.
If the runtime system is a bus controller, then the TwinCAT category will be replaced by these options:
If you choose this category, then you get the following dialog box:
Create Backup
When activating an option, a check appears before the option. If you choose the option Create Backup, then
TwinCAT PLC Control creates a backup file at every save with the extension ".bak". In this way you can
always restore the versions before the last save.
Auto Save
If you choose the option Auto Save, then while you work your project is constantly saved to a temporary file
with the extension ".asd" according to a set time interval (Auto Save Interval). This file is erased at a normal
exit from the program. If for any reason TwinCAT PLC Control is not shut down "normally" (e.g. due to a
power failure), then the file is not erased.
When you open the file again the following message appears: