You are on page 1of 33

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

Beckhoff Training Series


Module 3: TwinCAT PLC Programming

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

2007 Beckhoff Automation GmbH


This document is not to be replicated in part or in
whole, either electronically, by copy machine,
photographically, or by scanning without the written
consent of Beckhoff USA.
Beckhoff Automation LLC
12150 Nicollet Avenue South
Burnsville, MN 55337
877 894-6228
beckhoff.usa@beckhoff.com
Version: 09242007

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

Table of Contents
Introduction ........................................................................................................ 5
IEC and Programming for PLCs .................................................................................................. 5

IEC ....................................................................................................................... 6
IEC 61131 ............................................................................................................ 6
IEC 61131-3 ......................................................................................................... 7
Successful Project Process .............................................................................. 8
Basic System Design ................................................................................................................... 9
Lab 1: Design Basic System Operations ................................................................................... 10

Program Components...................................................................................... 14
POU ........................................................................................................................................... 14
Function Block ........................................................................................................................... 14
Function ..................................................................................................................................... 14
Program ..................................................................................................................................... 14
Data Types ................................................................................................................................ 14
Array .......................................................................................................................................... 15
Enumeration .............................................................................................................................. 15
Range ........................................................................................................................................ 15
Structure .................................................................................................................................... 15
Resources.................................................................................................................................. 16
Libraries ..................................................................................................................................... 16

Working with Functions, Function Blocks and Programs ............................ 17


Lab 2: Designing Function Blocks ............................................................................................. 18

Writing the Program ......................................................................................... 21


Choosing which language to use............................................................................................... 21
Language breakdown ................................................................................................................ 22
Conventions ............................................................................................................................... 23
Comments ................................................................................................................................. 23
Naming Conventions ................................................................................................................. 23
Lab 3: Writing the Program........................................................................................................ 26

Connecting the PLC Program to the Hardware ............................................. 28


Documentation ................................................................................................. 28
Beckhoff Information System..................................................................................................... 28

Other resources ............................................................................................... 31


www.beckhoff.com..................................................................................................................... 31
PC Control ................................................................................................................................. 31
Main Catalog.............................................................................................................................. 31
Products & Solutions ................................................................................................................. 31
General PLC Information ........................................................................................................... 31

Glossary ............................................................................................................ 32
Index .................................................................................................................. 33

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

Introduction
IEC and Programming for PLCs
Software plays an ever increasing factor in the quality of any product. Software errors at minimum
will cause loses of time and waste of salary but in the extreme, can mean destruction of the
system it controls.
The increasing complexity of industrial control have complicated software code by a hundredfold.
Where in the past a machine might require 100 lines of code, it is not uncommon for major
installations to require 10,000 lines now. As one can imagine, more code means more possibility
for errors and makes 100% testing impossible. With tightening deadlines and increased
programmer turnover, expecting a single programmer to work on a project is a fallacy.
Modern programming tools combined with time-tested methods provide the environment for
higher quality software, i.e. reliability, robustness, integrity, persistence, and safety. Beckhoff s
PLC Control with the international standard IEC 61131-3 creates the perfect environment to
achieve the highest quality in software.
Following IEC recommendations will increase efficiency. More time will be available to tweak logic
because time will not be eaten-up by bug hunting, making code compatible from other
programmers and rewriting instead of simply reusing existing code blocks.
Everyone will benefit from the adoption of IEC Standards. To recap, here are the advantages
mentioned above plus more:
Code is immediately understandable by multiple programmers
Code can be worked on by programmers worldwide
Code will be usable far into the future
Program can be broken into smaller, reusable modules
Access to 3rd party modules and tools
Strong datatyping prohibits programming errors
Data structures for easy exchange of data elements
Flexible language selection, matching different backgrounds
Vendor independent software development possible
Supplier independent courses possible
Product independent courses possible
Better matching of theory and praxis, esp. at schools / educational level
Based upon up-to-date programming techniques and structural thinking

NOTE: This manual assumes basic to intermediate knowledge of Windows based computers and
basic programming knowledge. Familiarity with Module 1 of this series may also be helpful.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

IEC
The International Electrotechnical Commission (IEC) is an international standards organization
dealing with electrical, electronic and related technologies. Some of its standards are developed
jointly with ISO.
The IEC started on 26 June 1906 in London, the commission moved to its current headquarters in
Geneva in 1948. Today, the IEC is the world's leading international organization in its field, and
its standards are adopted as national standards by its members. The work is done by some
10,000 electrical and electronics experts from industry, government, academia, test labs and
others with an interest in the subject.
The IEC was instrumental in developing and distributing standards for units of measurement,
particularly the gauss, hertz, and weber. They also first proposed a system of standards, the
Giorgi System, which ultimately became the SI, or Systme International d units (the
International System of Units).
IEC standards have numbers in the range 60000 79999 and their titles take a form such as IEC
60417: Graphical Symbols for use on Equipment. The numbers of older IEC standards were
converted in 1997 by adding 60000, for example IEC 27 became IEC 60027.
Standards developed jointly with ISO such as ISO/IEC 26300, Open Document Format for Office
Applications (OpenDocument) v1.0 carry the acronym of both organizations. The use of the
ISO/IEC prefix is limited to publications from ISO/IEC Joint Technical Committee 1 on Information
Technology, as well as some ISO/IEC guides. ISO/IEC JTC1 is described in more detail under
ISO.

IEC 61131
IEC 61131 deals with PLCs. Development for the 61131 standard started in 1979 and Parts 1 and
2 were made standard in 1990 with part 3 being standardized in 1993.
Note: The standard for programmable logic controllers (PLCs) used to be 1131 but
because of the IEC s change in the numbering scheme starting January 1, 1997, this was
changed to 61131.
The standard is broken up into eight parts:
Part 1: General information
Part 2: Equipment requirements and tests
Part 3: Programming languages
Part 4: User guidelines
Part 5: Messaging service specification
Part 6: Communications via fieldbus (Awaiting completion of fieldbus standards.)
Part 7: Fuzzy control programming
Part 8: Guidelines for the application and implementation of programming languages
Therefore, IEC 61131-3 is the designator for standards concerning programming languages.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

IEC 61131-3
The purpose of any standardization is to achieve consistency. With PLC programming this means
that the languages, methods and structure of existing programs should be easily understood by
any PLC programmer with IEC 61131-3 techniques experience.
The 61131-3 Standards committee has specified the following requirements and
recommendations for programming:
1. Well Structured: Top down or bottom up programming development. Top down describes
starting with the complete requirements of the project then breaking those needs into individual
tasks. Bottom up starts with the independent tasks and builds up to the complete project.
Beckhoff recommends a top down approach as the project needs should define the tasks
required.
2. Strong Data Typing: Program should detect when the wrong type of data is written to a
variable.
3. Full Execution Control: Different parts of a program can run at different times, at different
rates and in parallel.
4. Complex Sequential Behavior: The steps, actions and transition of program sequences can
be described graphically. Also sequences can initiate other sequences and can run in parallel.
5. Data Structures: Program elements that are related can be shared among different POUs as
a complete unit. E.g. once a pump is completely described with all its I/O, that collection of code
becomes a virtual object that can be passed and reused.
6. Flexible Language Selection: The programmer is free to choose among IEC sanctioned
graphical and textual programming languages that best fit the task, and different parts of the
program can utilize different languages.
7. Vendor-Independent Software: PLC code that adheres to IEC 61131-3 standards should run
on any PLC from any vendor with minimal rewriting.
One final note is that the IEC 61131-3 standard is constantly growing and changing to meet
current challenges and new advances in technology and programming. Though the core of the
standard is not likely to change drastically, expect changes to the programming languages, file
formats and other aspects that guarantee interoperability among PLC vendors in the future.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

Successful Project Process


Though there are many ways to approach a project, Beckhoff Automation s experience has
shown that considering and fully evaluating the needs of the system (hardware and software)
before beginning the PLC programming will yield the best code and will do so in the most timeeffective manner.
This is what is meant by a Top-Down approach. Look at the big picture, then consider the toplevel elements that satisfy the goal and continue to break elements down until you get the basic
code itself.
For the purposes of this demonstration we will think about a high-tech soft-serve ice cream
machine (essentially representing a compact factory) and how
we would plan and program the PLC to handle all the aspects
of its operation. We will look at all the needs of making the
2
product as well as safety and user interaction.
Our machine is equipped with:
1. A lid to access the interior of the machine (for cleaning
and maintenance)
2. An automatic fill option
3. A level gauge to measure the amount of product in the
machine
4. A temperature gauge to measure the temperature of
the product
5. A fan to decrease the temperature of the product
6. A prop to mix the product
7. A spout to dispense the product
8. A light that indicates that product is not ready for
dispensing

7
6

In thinking about the overall necessity of the machine, as with any project the safety of the users
is paramount. Second to that, it needs to always dispense properly made product.
Starting with the product, the system needs to maintain a proper amount of properly cooled and
mixed product. This involves activating the auto fill feature, maintaining a temperature threshold
and mixing when appropriate.
It should also restrict dispensing when the product is not ready and restrict internal access when
the system is operating. This means shutting off the spout (and lighting the Not Ready light) if the
product is not optimum and locking the lid when the stirrer is operational.
Design Approach
We can describe the overall project by breaking it down into smaller components. We will look at
the following pieces through the next three sections:
1. Interface this includes the sensors as well as the user control.
2. Signals messages that are passed between the interfaces and the rest of the system (or
plant in larger systems).
3. User Interactions all operator interactions (larger systems may also include overrides and
supervisory data).
4. Control Analysis the macro systems that can be described in terms of POUs.
5. Function Blocks low level control
6. Scan Cycles any time requirements for the different programs and function blocks.
7. Detailed Design Specifics of the program and function blocks.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

Basic System Design


To make programming time the most efficient, one really should think of the overall project in a
hierarchical design. That is, decide what the major system pieces look like before breaking them
into smaller segments.
If you were designing a car manufacturing plant, would it make sense to begin programming for a
single robot or would it be better to think about the result of the entire assembly line? By
visualizing the entire system first, one begins to see where code can be reused and what
sequences of code make more sense than others, all leading to less waste and more of a logical
flow.
So, even before the first line of code is written, the system should be conceived and laid out in
plain English. This will not only allow the designer to begin to arrange components before
spending time on code that is inefficient, but it will create a document that non-programmers can
use to begin their part the project.
In the following lab, begin thinking about the SoftServe project in the abstract. Don t get bogged
down by thinking about how to code for it; that will come naturally as you will see later.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

10

Lab 1: Design Basic System Operations


Purpose: In this lab, you will need to think about what is necessary to fully describe the system.
This stage of development specifies all the requirements of the system: how it functions and how
users interact with it.
1. Interface start by describing the interface. Keep in mind that interface goes beyond the
buttons etc. that controls the system, but also includes the sensors (pressure gauges etc.) that
might be embedded within the system that gives users and other parts of the system necessary
information.
Given the SoftServe dispenser system, list at least three interface elements:

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

2. Signals describe the messages that need to be passed by each of the interface elements
above. E.g. if there is a pressure gauge, the message might be, Amount of pressure in PSI.

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

11

3. User Interactions describe every way that a human will interact with the system. This can be
as basic as, Switch system on or complex such as, Place material in crimper and pull handle.

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

4. Control Analysis write plain English explanations of sequences of operations. A simple


safety example might be, If an Emergency cord is pulled, cut power to the line and sound the
alarm.

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

_____________________________________________________________________________

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

12

Here are some potential answers to the lab questions.


1. Interfaces
Temperature sensor
Level sensor
Dispenser
2. Signals
Product Temperature
Product Level
Dispensing
Mixer State
3. User Interactions
Dispense product
Get report of dispensing record
4. Control Analysis note that the sequences of operations can be used to begin thinking about
the structure of the code itself.
Plain Language
Main program that includes
all the following functions.
When the product level is
too low to properly dispense
then lock the spout, turn on
the Not Ready light and
start filling the machine.
When the machine is full of
product, then stop filling,
unlock the spout and turnoff
the Not Ready light.
When the temperature of
the product is too warm
then lock the spout, turn on
the Not Ready light and
start cooling the product.
When the product is cooled
to some amount below the
maximum allowable
temperature then stop
cooling the product, unlock
the spout and turn off the
Not Ready light.

Data Type

Language Recommendation

Series of Boolean constructs

A text based language such


as ST or even SFC.
Simple Boolean functions are
quickly done in a graphic
language such as LD or FBD.

Series of Boolean constructs


but complicated by the
multiple inputs

This can be done in a graphic


language but would be more
efficient if written in ST.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

13

Plain Language

Data Type

Language Recommendation

When someone starts


dispensing the product,
start stirring the product.
Also, lock the lid so no one
can get in the machine with
the stirring prop in
operation.

Boolean

Simple Boolean functions are


quickly done in a graphic
language such as LD or FBD.

Boolean plus timer (TOF)


Stop stirring 10 seconds
after the patron stops
dispensing the product, fill if
necessary. Verify that the
stirring has stopped before
unlocking the lid.
Report of the amount of
product dispensed

Storage, analysis and transfer


of data is best left to textual
languages such as ST.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

14

Program Components
Now that we have a basic overview of the project we can begin to think about it in terms of code.
As has been mentioned, smaller components make for better code. Here we will begin to
familiarize ourselves with these components and the standard IEC nomenclature.
A complete TwinCAT program is called a Project. A Project can contain three kinds of objects:
Program Organizational Units (POUs), data types and resources, plus libraries which are
collections of the afore mentioned objects which can speed the writing of new code and give the
Project added power such as connecting to third party hardware.
A POU is a Program, Function Block or Function. The important factor is that the POU can be
used repeatedly in different parts of a Project.

POU
POUs are complete packages of code that can be reused throughout a Project or with separate
Projects. Unlike some other (high-level) languages, POU names are always global, that is, they
are not like local subroutines.

Function Block
Function Blocks are the most common POU. Function Blocks are encapsulated code describing a
reusable function all the way up to a virtual device. They can be written in any programming
language and their interoperability makes them compatible with programs from any IEC compliant
vendor program.
Function Blocks can be assigned to specific tasks. By default, a Function Block runs in the same
task as its parent Program. To assign a Function Block to a specific task, use the keyword WITH
(described later).

Function
Functions are the most restricted of the POUs because they can only contain local and input
variables.

Program
A program has all the features of a Function Block plus the ability to access the physical I/O
addresses of the PLC. Programs can contain declarations of global variables (VAR_GLOBAL),
which can then be referenced with Function Blocks. Programs can contain access variables
(VAR_ACCESS) which allow variables to be to be read and written to remote devices using
communication services. One limitation is that a Program can not contain an instance of another
Program.

Data Types
The data type determines what form information is saved in or passed out of variables. For
example, if the variable receives a number with a decimal (e.g. 3.14159) and the variable is set to
INT, then the value retained in the variable will lose the decimal (i.e. 3). To retain a decimal, the
variable would need to be set to REAL.
Data types can also limit how large a saved value will be. INT can only be 16 bits, so if the
received value is expected to be greater than +/-32767 than DINT or LINT should be used. Keep

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

15

in mind that enough memory will be reserved to hold the maximum variable size, so if the
expected values will be small, use smaller Data Types to limit memory waste.
Boolean/
Bit String

Signed
Integer

Unsigned
Integer

Floatingpoint (Real)

BOOL

Bits

Time, Duration,
Date & Character String

TIME

BYTE

SINT

USINT

DATE

WORD

INT

UINT

16

TIME_OF_DAY

DWORD

DINT

UDINT

REAL

32

DATE_AND_TIME

LWORD

LINT

ULINT

LREAL

64

STRING

Prefix meanings: S=short, D=double, L=long, U=unsigned.

Length of data type is variable

Besides the common data types above, the IEC standard allows for customized data types.
Called Derived Data Types, these data types are user definable, that is, the programmer can
create a data model that is customized for the specific application.
One caveat is that the IEC standard currently does not make mention of graphical representation
of derived data types. This means that defined data types must be created using textual
representation.
Use TYPE
END_TYPE to define a derived data type. Within the derived statement, varieties
of derived data types can be used, specifically: arrays, enumerations, ranges and structures.

Array
An array (AKA multi-element variable) is a group of data elements that all have the same data
type. Another restriction is that IEC 61131-3 states that an array cannot contain FB instances.

Enumeration
An enumeration is a list of names which can be applied to a variable. One possible use is to have
a list of machine states (ready, active, paused, etc.) that a variable can assume. One benefit is
that enumerations tend to be self commenting as the state is more easily determined.

Range
A range is the difference between the highest and lowest value a variable can be. A standard
data type, such as INT or REAL, can be specified to control the type of data allowed.

Structure
A structure is a composite data type defined using existing (basic or derived) data types. They
utilizes a STRUCT
END_STRUCT form and can be nested within the TYPE
END_TYPE.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

16

Examples of data types:


TYPE
Color
: (red, amber, green);
Sensor
: INT (-56..128);
Measure
: ARRAY [1..45] OF Sensor;
Measure-2D
: ARRAY [1..10,1..45] OF Sensor;
TestBench
:
STRUCT
Place
: UINT;
Light
: Color:= red;
Meas1 : Measure;
Meas2 : Measure-2D;
END_STRUCT;
END_TYPE

(* enumeration *)
(* range *)
(* 1-dimensional array *)
(* 2-dimensional array *)
(* structure *)
(* basic IEC data type *)
(* enumerated data type with initial value *)
(* array type *)
(* array type *)

Resources
Resources provide support for all the features needed to execute a program. You can think of a
resource as a virtual machine, that is, it embodies all the capabilities of the hardware for which
you are programming. So, not only does a resource allow for the possibility of a simulated or
virtual PLC control, but in fact, one of the main functions is to provide an interface between a
program and the physical I/O.

Libraries
Libraries are collections of code that programmers can access to facilitate programming. Often
these libraries support specific hardware. Beckhoff offers libraries for all their bus couplers and
other manufacturers generally have libraries that compliment their hardware offerings.
A library can be a complete POU or simply a snippet of code. In addition to hardware
communication, Beckhoff provides libraries to help with specific tasks such as motion or building
automation.
In TwinCAT PLC Control, the
Library Manager is employed
to access libraries. Two ways
to access the Library
Manager in PLC Control are
the Window menu and the
Resources tab.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

17

Working with Functions, Function Blocks and Programs


Even though it s been covered already, it would be good to revisit the differences between
Function and Function Block.
First off, don t confuse these with Function Block Diagram (FBD) which is a graphical
programming language. Although FBD is great for writing Functions and Function Blocks, it is not
the only choice for doing so and subsequently, Function Block Diagram and a Function Block are
not mutually exclusive.
A Function is a block of code that can be used repeatedly within a program and with different
programs of a project but it can only return a value without storing it. On the other hand a
Function Block can store the returned value. What this means is that every time a Function is
used (called an instance ), the returned value is always the default or null even when the
instance is called within the same program. Conversely, every instance of a Function Block will
return the values captured on the LAST cycle that the Function Block was called, regardless of
which program called the instance.
Functions and Function Blocks basically work by defining one or more inputs and one or more
outputs. Inputs are how information is brought into the Function or Function Block and outputs are
how information is delivered to other POUs. These inputs and outputs are described as variables,
e.g. place holders of changeable (i.e. variable) information.
The best way to understand the interrelationship between Functions, Function Blocks and
variables inside Programs is see how information flows between them. Understanding how these
elements are tied together is key to understanding how advanced PLC projects work.
Think of the MAIN Program as a house: P_House to follow our naming convention. The house
uses light switches in every room in the house but they all work the same so there is no reason to
program the light switch over and over again.
So now we might have a Function Block called FB_LightSwitch and there is an instance
(fbLightSwitch) in each room. That is, each room makes reference to a light switch. The light
switch Function Block will at minimum require input from the wall switch to determine when to turn
on, and will output to the ceiling light; each of these elements are variables.
But, we can simplify P_House further by having a Function: F_Room which contains an instance
fbLightSwitch of FB_LightSwitch. Then there may be many instances of fRoom in P_House and
each one will automatically have an instance fbLightSwitch.
So putting it all together, we have P_House containing instances of
F_Room, each of which has an instance of FB_LightSwitch which is
influenced by the input variable bWallSwitch (notice that the icons next
to the POUs show that each is written in a different language):

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

18

Lab 2: Designing Function Blocks


Purpose: In this lab, you will begin to think about the best and most economical (least number of
lines of code) way to write a Function Block for each task that you explored in the Control
Analysis of Lab 1.
Function Block Name
(*
Description
VAR_IN

*)

Function Block Name


(*
Description
VAR_IN

*)

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

END_VAR
VAR_OUT

END_VAR
VAR_OUT

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

END_VAR

Function Block Name


(*
Description
VAR_IN

END_VAR

*)

Function Block Name


(*
Description
VAR_IN

*)

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

END_VAR
VAR_OUT

END_VAR
VAR_OUT

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

END_VAR

END_VAR

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

19

Function Block Name


(*
Description
VAR_IN

*)

Function Block Name


(*
Description
VAR_IN

*)

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

END_VAR
VAR_OUT

END_VAR
VAR_OUT

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

END_VAR

Function Block Name


(*
Description
VAR_IN

END_VAR

*)

Function Block Name


(*
Description
VAR_IN

*)

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

END_VAR
VAR_OUT

END_VAR
VAR_OUT

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

____________________________

END_VAR

END_VAR

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

20

5. Function Blocks
Here are some possible Function Blocks. Variable naming is completely up to the programmer,
but having readable names goes far to make the code immediately readable.
Functionality

Function Block

Check product level

FB_LevelCheck
VAR_IN
ProductLevel : INT;
MaxLevel : INT;
END_VAR
VAR_OUT
LockSpout : BOOL;
NotReady : BOOL;
FillState : BOOL;
END_VAR
FB_TempCheck
VAR_IN
CurrentTemp : INT;
MaxTemp : INT;
OpTemp : INT;
END_VAR
VAR_OUT
RunFan : BOOL;
LockSpout : BOOL;
NotReady : BOOL;
END_VAR
FB_Dispense
VAR_IN
SpoutState : BOOL;
END_VAR
VAR_OUT
SetStir : BOOL;
LockLid : BOOL;
END_VAR

Check product temperature

Dispense product

Finishes with a call to the


FB_LevelCheck function
block.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

21

Writing the Program


Now we are ready to write the program to control the SoftServe machine. So let s finish with the
last two aspects of a top-down design approach.
6. Scan Cycles
We need to determine how often the system is going to check states of different parts of the
system. This includes both the regular functions of the machine as well as watching for safety
concerns. Here are some things to consider for scanning:
Temperature is checked every 5 minutes.
Dispenser is checked every second
Access door is checked every second.
7. Detailed Design
Now we are ready to actually write the program. Everything we have do to this point was in
preparation of composing the actual system PLC.
By taking the time to specify all the requirements of the system, we can more easily deduce and
organize the individual steps to accomplish the task. If we had just started coding, it is likely that
steps would have been missed, especially user interaction and safety requirements.
Before we begin, let s talk about the benefits of the different languages available. This will help
you decide which language to use for each section of the program.
And lastly we will set some guidelines and conventions to the structuring and naming of the
program components. These final thoughts should give you the tools necessary to effectively
complete the system.

Choosing which language to use


Deciding which language to use for a specific part of the project is perhaps the most confusing
aspect of IEC based PLC programming. Certainly there are strengths and weaknesses to each
language but the programmer s language familiarity should not be ignored.
Many programmers successfully write all components of complicated projects in a single
language. And while this may offer consistency it does not necessarily provide the best efficiency.
The rule of thumb is that the smaller the program (the least lines of code) the quicker and more
efficiently it runs. Furthermore, less code means quicker troubleshooting as obviously there are
less lines of code to digest.
The target audience might also play into which language to select. If EEs (Electrical Engineers)
are going to be working with the code then LD or FBD might be most appropriate as these
resemble electrical schematics. If the client representative in charge of modifying the code is
accustomed to high level languages (C+, Pascal, etc.) then ST might be the easiest to
understand and modify.
Though graphic languages may require more processor usage, the benefits of visualization may
be worth it. And of course the fact that graphic languages may require less learning means that a
workable program can be made quicker by inexperienced programmers.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

22

Language breakdown
Language

Type

Pros

Cons

LD
Ladder Description

Graphical

Developed to use the


most commonly used
symbols and terminology
of mainstream PLCs.

EN and ENO functions


cannot be translated to
ST.

Familiar to anyone
practiced in RLL.
Decent translation to
and from FBD

ST
Structured Text

Textual

Particularly useful for


complex arithmetic
calculations.

Depending on the PLC,


programs in LD may be
limited in how many
function block instances
and the number of
functions that can be
supported. As well there
may be a limit on the
number of contacts and
coils in a single rung and
the number of rungs in a
system.
Compiled programs can
be longer and slower than
ones written in IL.

Might be easier to learn


for programmers familiar
with high-level
languages (PASCAL, C,
etc.)
FBD
Function Block Diagram

Graphical

Might be easier for


programmers familiar
with electrical circuits.
Good stepping stone
from LD (many concepts
and elements are shared
between the two).
Most constructs can be
translated into ST.

IL
Instruction List

Textual

Very simple and easy to


learn.

Can t handle more


complex problems.

All other languages can


be translated into it.

Least documented
language.

Can be directly
downloaded to some
PLC without compiling.

Difficult to translate into


other languages.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

23

Language

Type

Pros

SFC
Sequential Function
Chart

Textual
and
Graphical

Very flexible in that both


textual and graphical
coding is possible.

Cons

Support for top down


design.
Can be used for top
level or low level parts of
the program.
CFC
Continuous Function
Chart
(Currently not an IEC
standard language.)

Graphical

Shows the resource and


task assignments as well
as everything else with
FBD.

Notes: German programmers prefer IL and ST. US seems to prefer a combination of SFC and
Ladder. France s PLC experts tend to use SFC.

Conventions
Conventions are protocols that help to standardize written code. This makes it is easier to work
with code that someone else started or even dig into code you may have written long ago. IEC
only gives recommendations on this topic. Your company may have specific conventions to use
when writing code. Following are Beckhoff suggested conventions which if followed will make
your code readable by a vast majority of PLC programmers and will make working with Beckhoff
even easier.

Comments
The best habit you can adopt is to comment you code. Commenting is often seen as the last step
in programming but when the coding is completed, commenting is usually forgotten. It is far better
to comment as you code as it will then be done when the code is done and won t be neglected.
Plus, if you were to leave the project before completion, it will reduce the time it takes for the
programmer assuming responsibility of the project to get up to speed.
Comments in graphic programming languages is usually in the form of added lines to the element
name. In textural languages, the comment is in-line with the code being commented. Also, in the
Declaration part of the PLC Control window, the comments are in-line with the code being
commented. In both of the latter situations, comments are marked with parentheses and
asterisks, i.e. (* this is a comment and will be ignored when the code is run *).

Naming Conventions
In addition to commenting, naming conventions also help to clue a programmer in as to what the
code is doing as any given point. Naming conventions should be used in both naming POUs and
also variables within POU objects.
Starting with POUs or Object Names, the following is a good beginning guide:

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

24

Object

Prefix

Description

Example

FUNCTION_BLOCK

FB_

Function Block

FB_GetData

STRUCT

ST_

Structure

ST_BufferEntry

ENUM

E_

Type of Enumeration

E_SignalStates

TYPE

T_

Reference

T_Nibble

PROGRAM

P_

Program

P_Axis

FUNCTION

F_

Function

F_Convert

When you add a new object to a project, you are


encouraged to use the above naming convention to
name that object. No help will be offered to you when
creating a new object, and as you may name an object
anything you wish, you are able to conform to any
naming conventions your company may have in place.

There really isn t a reason to add a code to identify the language in which
the POU is written since PLC Control marks each POU with a
representative icon; FBD, ST and LD respectively in the example shown.
Furthermore, as has been stated many times, the language choice is only
important in writing the POU not using it. You might think that identifying
the type of POU is not necessary as it too is marked by PLC Control, but changing the prefix
allows for similar named variables that have different functionality. Plus, it will be helpful when
trying to understand the function of a particular instance in the code when printed out or viewed in
raw text.
Instance names should also follow a convention. The markers are similar to the POU conventions
but lowercase is used to provide on-sight identification that the item is an instance and not the
original POU. Compare to the POU convention table above.
Object

Prefix

Description

Example

Function block

fb

Instance of a function block

fbGetData

Struct

st

Instance of a Structure

stBufferEntry

Enum

Instance of Enumeration

eSignalStates

Alias type

<none>

Instance of a reference type

Nibble

Finally, conventions can optionally be used for variables. Some programmers like to mark the
variable with the type of data it can contain. Below are the most common data types:
Data Type

Prefix

Example

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

25

Data Type

Prefix

Example

BOOL

bDoorOpen

INT

iMaxSpeed

REAL

rMaxTemp

See the Beckhoff Information System for the complete list.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

26

Lab 3: Writing the Program


Purpose: In this lab, you will bring together the Function Blocks into one cohesive program.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

27

Here is a possible way to program the system. The structure can be different and the languages
chosen to complete the components can be different, but this shows how to make code very
efficient, intuitive and safety conscience as well as making the system function.
[ Finished program]

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

28

Connecting the PLC Program to the Hardware


The System Manger is the bridge between a PLC program and the hardware being controlled. It
assigns which hardware input is controlled by which software input. It also connects the hardware
outputs to software outputs so the PLC programs can monitor and react to the changes in the
hardware states.
Information on connecting the PLC Program to I/O is included in Module 1: Introduction to
TwinCAT. Please go through that manual if you haven t already.

Documentation
A number of sources of information are available when learning about, using specific Beckhoff
tools, Beckhoff products and services and company information. As a customer of Beckhoff, all of
this information will be at your disposal.

Beckhoff Information System


By far, the most complete source of information is the Beckhoff Information System. It includes
information about every Beckhoff product, its use and interoperability. When TwinCAT is installed
from the CD, the complete Information System is automatically installed. If TwinCAT was installed
from a download, a slimmed-down version may have been installed to save download time. The
full version can also be downloaded from the Beckhoff site.
Arguably, Information System s greatest asset is in its help with troubleshooting. Information
System includes explicit details of programming and hardware elements. This includes error
codes plus their causes and potential remedies.
To access Information System, click the Start button, then Programs (or All Programs) then
BECKHOFF, then Information System and finally the language of your choice.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

29

There are three main ways to find information in the Information System:
Contents shows a tree of topics that can be browsed.

Index takes a keyword and shows items specified as being related to that keyword.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

30

Search returns every page that contains the entered search term.

If you find something close to what you are looking for in a search, try clicking on the Contents
tab to see where the selected page falls in the tree. You can then browse from there to pinpoint
the information you require.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

31

Other resources
www.beckhoff.com
This is the official website of Beckhoff Automation. At this site you will have access to company
information, including news, training locations, contact information, products and services.

PC Control
This printed, monthly magazine, published by Beckhoff offers stories about companies that are
benefiting from the incorporation of Beckhoff products plus tips, new product announcements and
general news. It can also be read online at www.pc-control.net/english.

Main Catalog
This printed document contains all of Beckhoff s products and services and also includes some
company information. See the I/O section in this manual for a description of model numbering
and color scheme.

Products & Solutions


This CD set includes a CD with the entire website, Main Catalog, documentation, all of the
publications of PC Control available at the time plus a second, installation CD of Beckhoff
software products.

General PLC Information


For non-company specific information on the PLC standards, programming and more, visit
www.plcopen.org.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

32

Glossary
CFC (Continuous Function Chart), a version
of FBD that is not yet an IEC standard PLC
programming language.

Library, a collection of POUs, data types


and resources - makes writing programs
quicker.

DLL (dynamic-link library), a block of code


that is called by a program but remains
separate, generally written in higher-level
languages.

OCX, a DLL that contains one or more


ActiveX controls. Mainly used when linking a
program to code written in Microsoft Visual
Basic or .net.

FBD (Function Block Diagram), an IEC


standard PLC programming language.

OS (Operating System), the software that


runs a computer or is embedded in and runs
Fieldbuses.

IEC (International Electrotechnical


Commission), the world standards
organization for electrical and electronic
international standards.
IEC 61131-3, the global standard for
common industrial control programming.
IL (Instruction List), an IEC standard PLC
programming language.
I/O (Input/Output), communication between
a computer and its users, its storage
devices, other computers (via a network) or
attached hardware.
LD (Ladder Diagram), an IEC standard PLC
programming language.

PLC (Programmable Logic Controller), a


small special-purpose computer used to
automate machines.
POU (Program Organization Unit), functional
elements within a PLC program as
described by IEC 1131-1.
RLL (Relay Ladder Logic).
SFC (Structured Function Chart), an IEC
standard PLC programming language.
ST (Structured Text), an IEC standard PLC
programming language.
TwinCAT (The Windows Control and
Automation Technology), all the PLC tools
and system modification components
offered by Beckhoff Automation GmbH.

12150 Nicollet Avenue South / Burnsville, MN 55337 / 877 TWIN-CAT (877 894-6228)

33

Index
data type, 14
DLL, 32
error, 28
I/O, 31, 32
Information System, 28, 29

library, 14, 32
OCX, 32
PLC, 28, 32
POU, 14, 32
Scan, 10, 18, 26

You might also like