04.12.2019 Views

BECKHOFF-TwinCAT 2 Manual v3.0.1 2013 [en]

BECKHOFF AUTOMATION Manual training TwinCAT v2 Da empresa BRESIMAR AUTOMAÇÃO (Aveiro / Portugal) Autoria: BECKHOFF AUTOMATION USA

BECKHOFF AUTOMATION
Manual training TwinCAT v2
Da empresa BRESIMAR AUTOMAÇÃO (Aveiro / Portugal)
Autoria: BECKHOFF AUTOMATION USA

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Beckhoff New Automation Technology<br />

<strong>TwinCAT</strong> 2<br />

Revised: November 8, <strong>2013</strong><br />

Brian McClure<br />

b.mcclure@beckhoff.com


2


Preface<br />

This <strong>Manual</strong> is int<strong>en</strong>ded for anyone who is interested in the <strong>TwinCAT</strong> software. From<br />

electricians, to electrical <strong>en</strong>gineers, and ev<strong>en</strong> computer sci<strong>en</strong>tists; all levels of experi<strong>en</strong>ce can b<strong>en</strong>efit<br />

from the material covered in this manual.<br />

The material is a result of the combined efforts of many <strong>en</strong>gineers within Beckhoff Automation.<br />

We have reviewed and revised the information in an effort to make it as precise and correct as possible;<br />

however, nothing is perfect. But, we would like for it to be. If you find any issues, or items that you think<br />

need more explanation, please let us know by contacting the author at b.mcclure@beckhoff.com.<br />

3


Revision Notes<br />

V3.0.0<br />

Added – Chapter Digital I/O<br />

Index Added<br />

This chapter covers the first section of “The Inspection Conveyor” utilizing Digital Inputs<br />

and Outputs to control the conveyor.<br />

Table of Cont<strong>en</strong>ts and Page numbering modified<br />

V3.0.1<br />

Added – Code Changes to PLC Overview<br />

Added – Lamp Test to Trouble shooting<br />

Index Updated<br />

Page Number Wrapping Fixed<br />

Added - Labs<br />

4


I. Cont<strong>en</strong>ts<br />

II. TWINCAT OVERVIEW 11<br />

1.<br />

2.<br />

3.<br />

4.<br />

OVERVIEW 11<br />

SYSTEM SERVICE 18<br />

SYSTEM MANAGER 26<br />

PLC CONTROL 44<br />

III. TWINCAT SOFTWARE INSTALLATION 45<br />

5.<br />

6.<br />

7.<br />

TWINCAT VERSIONS 45<br />

SOFTWARE, DOWNLOAD & INSTALLATION 47<br />

LICENSING AND REGISTRATION 62<br />

IV. PLC OVERVIEW 64<br />

8.<br />

9.<br />

10.<br />

11.<br />

12.<br />

13.<br />

14.<br />

15.<br />

16.<br />

17.<br />

18.<br />

19.<br />

20.<br />

21.<br />

IDE 64<br />

PROGRAMS 68<br />

DATA TYPES AND CONVERSIONS 69<br />

VARIABLES 72<br />

LANGUAGES 77<br />

FUNCTIONS 83<br />

FUNCTION BLOCKS 87<br />

ACTIONS 96<br />

STRUCTURES 97<br />

ENUMERATIONS 99<br />

ARRAYS 102<br />

BOOT PROJECT 106<br />

SOURCE CODE DOWNLOAD 108<br />

CODE CHANGES 112<br />

V. PLC PROGRAMMING “THE INSPECTION CONVEYOR” 130<br />

5


22.<br />

23.<br />

MACHINE CONTROL WITH TOP-DOWN PROGRAMMING 130<br />

DIGITAL I/O 206<br />

VI. TROUBLE SHOOTING 241<br />

24.<br />

25.<br />

26.<br />

27.<br />

28.<br />

29.<br />

30.<br />

LAMP TEST 241<br />

CODE SEQUENCING 256<br />

BREAK POINTS 260<br />

FLOW CONTROL 265<br />

GLOBAL SEARCH 271<br />

CROSS REFERENCE 277<br />

SCOPE VIEW 283<br />

VII. LABS 290<br />

31.<br />

32.<br />

33.<br />

LANGUAGES 290<br />

LINEAR SCALING USING A RATIO 301<br />

LINEAR SCALING USING AN EQUATION 302<br />

VIII. CAMMING 305<br />

34. PREFACE 305<br />

35. INTRO TO TCMC2.LIB 306<br />

A. OVERVIEW 306<br />

B. MIGRATION FROM TCMC TO TCMC2 310<br />

C. STATUS INFORMATION 313<br />

36. WHEN TO USE A CAM TABLE 314<br />

A. OVERVIEW 314<br />

B. GEARING 315<br />

C. LINEARLY INCREASING GEAR RATIO (DYNAMIC) 316<br />

D. CAM TABLE 317<br />

37. CREATING A CAM TABLE WITH FUNCTION BLOCKS 318<br />

A. OVERVIEW 318<br />

B. DEFINING THE POINTS ON THE CAM TABLE 318<br />

I. MOTION FUNCTION POINT 318<br />

II. SAMPLE CODE: 320<br />

38. DEFINING THE CAM TABLE IN THE PLC 322<br />

A. OVERVIEW 322<br />

B. MC_CAM_REF 322<br />

I. EXAMPLE 1: POSITION TABLE STRUCTURE DESCRIPTION 322<br />

II. EXAMPLE 2: STRUCTURE DESCRIPTION OF A MOTION FUNCTION 323<br />

6


C. MC_TABLETYPE 324<br />

I. SAMPLE CODE: 324<br />

39. CREATING THE CAM TABLE 325<br />

A. OVERVIEW 325<br />

B. MC_CAMTABLESELECT 325<br />

I. SAMPLE CODE: 326<br />

40. IMPORTING A CAM TABLE FOR VERIFICATION 327<br />

A. OVERVIEW 327<br />

B. CREATING A BLANK TABLE 327<br />

C. IMPORTING THE CAM TABLE 330<br />

41. CAMMING THE TWO AXES TOGETHER 333<br />

A. OVERVIEW 333<br />

ONCE THE CAM TABLE HAS BEEN DEFINED, VERIFIED, AND CREATED; THE TWO AXES ARE NOW READY TO BE CAMMED<br />

TOGETHER. 333<br />

B. MC_CAMIN 333<br />

I. SAMPLE CODE: 335<br />

42. CHANGING A TABLE POINT VIA THE PLC 336<br />

A. OVERVIEW 336<br />

B. MC_WRITEMOTIONFUNCTIONPOINT 336<br />

C. MC_SETCAMONLINECHANGEMODE 337<br />

D. MC_CAMACTIVATIONMODE 339<br />

I. SAMPLE CODE: 340<br />

43. MOTION FUNCTIONS VS. POSITION TABLES 342<br />

A. POSITION TABLES 342<br />

B. MOTION FUNCTIONS 344<br />

C. DEFINITION OF A POINT 345<br />

D. POINT STRUCTURE 345<br />

E. POINT TYPES 346<br />

44. CAM DESIGN TOOL 347<br />

A. OVERVIEW 347<br />

B. CREATING A CAM TABLE 348<br />

I. MASTER TAB 353<br />

II. SLAVE TAB 354<br />

C. GRAPHIC WINDOW 355<br />

D. TABLES WINDOW 357<br />

I. FUNCTION TYPES 358<br />

II. COMMANDS 359<br />

45. CAM TABLE SCALING 361<br />

A. OVERVIEW 361<br />

B. MC_CAMSCALING 361<br />

C. MC_CAMSCALINGMODE 363<br />

I. EXAMPLE: 364<br />

7


II. SAMPLE CODE: 366<br />

46. CYCLIC CAM PLATES WITH LIFT 367<br />

A. MC_STARTMODE 369<br />

47. CAM OUT AND RESTARTING 371<br />

A. OVERVIEW 371<br />

B. MC_CAMOUT 372<br />

C. MC_HALT 373<br />

48. MC_CAMIN APPENDIX 375<br />

A. AXIS COUPLING WITH CAM PLATES 375<br />

B. LINEAR CAM PLATES 375<br />

C. CYCLIC CAM PLATES WITHOUT LIFT 377<br />

D. CYCLIC CAM PLATES WITH LIFT 378<br />

E. UNCOUPLING AND RE-COUPLING FOR CYCLIC CAM PLATES WITH LIFT 379<br />

49. DIAGNOSTICS 380<br />

A. OVERVIEW 380<br />

B. ERROR FORMAT 380<br />

IX. REMOTE CONNECTIONS 385<br />

50.<br />

EMBEDDED CONTROLLERS 385<br />

X. APPENDIX I – VARIABLE NAMING CONVENTION 398<br />

51. SCOPE 398<br />

52. PROGRAMMING SYSTEM SETTINGS 399<br />

A. FONT 399<br />

B. TAB WIDTH 399<br />

53. NAMING 400<br />

A. GENERAL 400<br />

B. CASE SENSITIVITY 400<br />

C. VALID CHARACTERS 400<br />

D. PREFIX TYPES 401<br />

E. SCOPE PREFIX 402<br />

F. TYPE PREFIX 403<br />

G. PROPERTY PREFIX 405<br />

H. POU PREFIX 407<br />

I. STRUCTURES 408<br />

J. LIST TYPES 409<br />

K. LIBRARIES 410<br />

54.<br />

A.<br />

GOOD PROGRAMMING PRACTICES<br />

COMMENTS<br />

411<br />

411<br />

8


B. ARRAY INDEXING 411<br />

C. PROGRAM CALLS 411<br />

9


1<br />

0


Chapter: <strong>TwinCAT</strong> Overview<br />

II.<br />

<strong>TwinCAT</strong> Overview<br />

1. Overview<br />

The Windows Control and Automation Technology<br />

• The Beckhoff <strong>TwinCAT</strong> software system turns any compatible PC into a real-time controller with<br />

a multi-PLC system, NC axis control, programming <strong>en</strong>vironm<strong>en</strong>t and operating station. <strong>TwinCAT</strong><br />

replaces conv<strong>en</strong>tional PLC and NC/CNC controllers as well as operating devices with:<br />

• op<strong>en</strong>, compatible PC hardware<br />

• embedded IEC 61131-3 software PLC, software NC and software CNC in Windows<br />

NT/2000/XP/Vista, Windows 7, NT/XP Embedded, CE<br />

• programming and run-time systems optionally together on one PC or separated<br />

• connection to all common fieldbuses<br />

• PC interface support<br />

• data communication with user interfaces and other programs by means of op<strong>en</strong><br />

Microsoft standards (OPC, OCX, DLL, etc.)<br />

Architecture<br />

• <strong>TwinCAT</strong> consists of run-time systems that execute control programs in real-time and the<br />

developm<strong>en</strong>t <strong>en</strong>vironm<strong>en</strong>ts for programming, diagnostics and configuration. Any Windows<br />

programs; for instance, visualization programs or MS Office programs, can access <strong>TwinCAT</strong> data<br />

via Microsoft interfaces, or can execute commands.<br />

A practical ori<strong>en</strong>ted software solution<br />

• <strong>TwinCAT</strong> offers a precise time base in which programs are executed with the highest<br />

deterministic features, indep<strong>en</strong>d<strong>en</strong>tly of other processor tasks. The real-time load on a PC is set<br />

with <strong>TwinCAT</strong>; defined operating behavior is achieved in this way. <strong>TwinCAT</strong> indicates the system<br />

load for programs that are running. A load threshold can be set in order to assure a defined<br />

computing capacity for the operating programs and for Windows NT/2000/XP/Vista. If this<br />

threshold is exceeded, a system message is g<strong>en</strong>erated.<br />

11


Chapter: <strong>TwinCAT</strong> Overview<br />

<strong>TwinCAT</strong> supports system diagnosis<br />

• The g<strong>en</strong>eral use of hardware and software from the op<strong>en</strong> PC world requires some checking:<br />

Unsuitable compon<strong>en</strong>ts can upset the PC system. Beckhoff has integrated a practical indicator of<br />

the real-time jitter, giving administrators an easy way to evaluate the hardware and software. A<br />

system message during operation can draw att<strong>en</strong>tion to incorrect states.<br />

Start/Stop behavior<br />

• Dep<strong>en</strong>ding on the setting, <strong>TwinCAT</strong> is started and stopped manually or automatically. Since<br />

<strong>TwinCAT</strong> is integrated into Windows NT/2000/XP/Vista and Windows 7as a service, an operator<br />

is not needed to start the system: switching on is <strong>en</strong>ough.<br />

Restarting and data backup<br />

• Wh<strong>en</strong> a program is started or restarted, <strong>TwinCAT</strong> loads programs and remnant data. To back up<br />

data and to shut down Windows NT/2000/XP/Vista and Windows 7 correctly, a UPS<br />

(uninterruptible power supply) is of great value.<br />

World-wide connection through message routing – “remote” connection is inher<strong>en</strong>t to the<br />

system<br />

• According to the requirem<strong>en</strong>t for operating resources, the <strong>TwinCAT</strong> software devices can be<br />

distributed: <strong>TwinCAT</strong> PLC programs can run on the PCs or on Beckhoff Bus Terminal Controllers.<br />

A “message router” manages and distributes all the messages, both in the system and via TCP/IP<br />

connections. PC systems can be connected with each other via TCP/IP; Bus Terminal Controllers<br />

are integrated via serial interfaces and fieldbuses (EtherCAT, Lightbus, PROFIBUS DP, CANop<strong>en</strong>,<br />

RS232, RS485, Ethernet TCP/IP).<br />

World-wide access<br />

• Since standard TCP/IP services of NT/2000/XP/Vista/CE and Windows 7 can be used, this data<br />

can be exchanged across the world. The system offers scalable communication capacity and<br />

timeout periods for the supervision of communications. OPC provides a standardized means for<br />

accessing many differ<strong>en</strong>t SCADA/MES/ERP packets.<br />

12


Chapter: <strong>TwinCAT</strong> Overview<br />

PLC and Motion Control on the PC<br />

<strong>TwinCAT</strong> I/O – universal I/O interface for all common fieldbuses<br />

• Many PC fieldbus cards from various manufacturers are supported. It is possible to operate<br />

more than one fieldbus card per PC. Master and slave functionality is supported, dep<strong>en</strong>ding on<br />

the selected fieldbus card. The fieldbus cards can be configured and diagnosed conv<strong>en</strong>i<strong>en</strong>tly via<br />

the <strong>TwinCAT</strong> System Manager. <strong>TwinCAT</strong> I/O includes the <strong>TwinCAT</strong> real-time system for<br />

operating the fieldbuses and a DLL interface to application programs.<br />

<strong>TwinCAT</strong> PLC – the c<strong>en</strong>tral pillar of automation software<br />

• Conceived as a pure software PLC, <strong>TwinCAT</strong> PLC allows up to four virtual “PLC CPUs”, each<br />

running up to four user tasks, on one PC. The PLC program can be writt<strong>en</strong> in one or more of the<br />

languages provided for in the IEC 61131-3 standard:<br />

• IL (Instruction List),<br />

• LD (Ladder Diagram),<br />

• FBD/CFC (Function Block Diagram),<br />

• SFC (Sequ<strong>en</strong>tial Function Chart) and<br />

• ST (Structured Text).<br />

• <strong>TwinCAT</strong> PLC running under the Windows NT/2000/XP/Vista operating systems includes both<br />

the programming <strong>en</strong>vironm<strong>en</strong>t and the run-time system, so that an additional programming<br />

device is not required. Under the CE operating system and the embedded operating systems for<br />

the series BX and BC controllers, only <strong>TwinCAT</strong> run-time is available. Program modifications are<br />

implem<strong>en</strong>ted via network-capable powerful communication with the run-time system.<br />

Programming can be done<br />

• locally,<br />

• via TCP/IP or<br />

• via the fieldbus (BXxxxx and BCxxxx).<br />

13


Chapter: <strong>TwinCAT</strong> Overview<br />

IEC 61131-3 – advanced programming standard for all Beckhoff controllers<br />

• The <strong>TwinCAT</strong> PLC is programmed in accordance with IEC 61131-3 indep<strong>en</strong>d<strong>en</strong>tly of the<br />

manufacturer. <strong>TwinCAT</strong> supports all the IEC 61131-3 programming languages with conv<strong>en</strong>i<strong>en</strong>t<br />

editors and a fast, effective compiler, so that the developm<strong>en</strong>t cycle for the creation ev<strong>en</strong> of<br />

large PLC programs of several megabytes can be short. Increm<strong>en</strong>tal compilation prev<strong>en</strong>ts long<br />

turnaroand times. Only g<strong>en</strong>uinely new sections are compiled. Powerful editor features, such as<br />

“autoformat”, “autodeclare” or “find” and “replace” <strong>en</strong>able fast programming. For all<br />

programming languages, the project comparison function facilitates differ<strong>en</strong>ces to be id<strong>en</strong>tified<br />

and accepted if appropriate. If a project (comm<strong>en</strong>ts, directories, etc.) is to be translated into a<br />

language other than the original language, all terms can be exported into a table, translated and<br />

re-imported. If a team is dealing with the developm<strong>en</strong>t, all objects (blocks, data types, lists) can<br />

be managed within a source code managem<strong>en</strong>t tool via the <strong>TwinCAT</strong> Engineering Interface. This<br />

<strong>en</strong>ables changes to be traced back and differ<strong>en</strong>ces betwe<strong>en</strong> individual versions to be displayed.<br />

• The concept of the “instantiation” of function blocks, in which each instance is associated with<br />

its own data, leads naturally to object-ori<strong>en</strong>ted and structured programming styles. All common<br />

data types specified in IEC 61131-3 are supported. Multi-dim<strong>en</strong>sional fields and structures are<br />

possible, as are <strong>en</strong>umeration and subrange types.<br />

• <strong>TwinCAT</strong> PLC is certified for the languages IL and ST (base level). The online change function can<br />

be used for code and/or data modifications while the PLC is running, providing maximum data<br />

ret<strong>en</strong>tion. Source code can be stored in the target system (except for BCxxxx series controllers).<br />

The criteria analysis function is very helpful for the detection of process errors.<br />

• Code can very easily be reused via the conv<strong>en</strong>i<strong>en</strong>t library manager. For know-how protection,<br />

multi-stage password protection can be applied to programs and libraries.<br />

Many target platforms – one tool<br />

• The PLC programs created with <strong>TwinCAT</strong> PLC can be executed on a number of target platforms.<br />

Apart from Industrial PCs and the Embedded PCs, the PLC project can also be loaded into the BC<br />

and BX series fieldbus controllers from Beckhoff. Program developm<strong>en</strong>t and debugging proceed<br />

in the same working <strong>en</strong>vironm<strong>en</strong>t, regardless of which unit is executing the program.<br />

Ext<strong>en</strong>sive supplem<strong>en</strong>tary libraries<br />

• As an ext<strong>en</strong>sion to the blocks defined by the IEC language standard, Beckhoff offers a wide<br />

range of supplem<strong>en</strong>tary libraries for the execution of tasks typical in automation technology:<br />

e.g. libraries for controlling electrical and hydraulic axes via <strong>TwinCAT</strong> NC, serial communication<br />

libraries, system libraries for message outputs, write/read files, control technology blocks, etc.<br />

14


Chapter: <strong>TwinCAT</strong> Overview<br />

Helpful practice tools<br />

• Ext<strong>en</strong>sive fault finding functions in <strong>TwinCAT</strong> PLC facilitate the solution of problems either on site<br />

or via remote maint<strong>en</strong>ance. For this purpose, the PLC programming <strong>en</strong>vironm<strong>en</strong>t in <strong>TwinCAT</strong><br />

offers:<br />

• Online Monitoring<br />

• Power Flow (flow control)<br />

• Break Points<br />

• Sampling trace of PLC variables<br />

• Single step<br />

• Watchlist<br />

• Call hierarchy<br />

• Forcing of variables.<br />

• In addition, the <strong>TwinCAT</strong> ScopeView (a software oscilloscope) can be used to record one or<br />

several variables simultaneously.<br />

<strong>TwinCAT</strong> NC – Motion Control on the PC<br />

• A software NC consists of:<br />

• positioning (set value g<strong>en</strong>eration and position control)<br />

• integrated PLC with NC interface<br />

• operating programs for commissioning purposes<br />

• I/O connection for axes via fieldbus<br />

• With <strong>TwinCAT</strong> NC, the position controller is calculated on the PC processor as standard. It<br />

exchanges data cyclically with drives and measurem<strong>en</strong>t systems via the fieldbus.<br />

C<strong>en</strong>tral NC positioning on the PC<br />

• The computing capacity of a PC <strong>en</strong>ables axis motion simultaneously with the PLC, whereby the<br />

position controller is usually calculated on the PC: The computing capacity of a PC <strong>en</strong>ables many<br />

axes to be positioned simultaneously.<br />

• <strong>TwinCAT</strong> <strong>en</strong>ables a PC to process the operating programs, the PLC and the NC at the same time.<br />

The division of the system load is supported by <strong>TwinCAT</strong> with appropriate functions.<br />

15


Chapter: <strong>TwinCAT</strong> Overview<br />

Analytical path calculation<br />

• The algorithms that <strong>TwinCAT</strong> NC/NC I/CNC uses to control axes take account of the dynamic<br />

parameters of the axis: speed, acceleration and jerk. In this way, the axes are moved at any time<br />

within the limits of what is dynamically possible, and are precisely analytically coordinated. A<br />

range of differ<strong>en</strong>t regulation algorithms are available in order to reduce the deviations from the<br />

ideal trajectory that will occur in practice.<br />

Individual or joint<br />

• Based on the normal methods for positioning an individual electrical axis, moving from its<br />

starting point to its destination (point-to-point positioning), <strong>TwinCAT</strong> NC also allows the<br />

coordinated movem<strong>en</strong>t of a number of axes in multi-stage master-slave operation (e.g. gearing<br />

functions or cam plates) to be executed. <strong>TwinCAT</strong> NC I further allows the interpolated path<br />

sequ<strong>en</strong>cing described in accordance with DIN 66025 to be carried out involving up to three axes.<br />

Software PLC included<br />

• <strong>TwinCAT</strong> combines software NC and software PLC to form a powerful controller. The<br />

communication betwe<strong>en</strong> the two packages is a pure software/software channel with minimum<br />

delay times. The NC functionalities are called from the PLC program via standardized, PLCop<strong>en</strong>certified<br />

function blocks.<br />

• Axis movem<strong>en</strong>ts can be simulated without hardware; the actual value is instructed to ideally<br />

track the set value, and the complete machine flow is checked. <strong>TwinCAT</strong> ScopeView is helpful<br />

for commissioning and maint<strong>en</strong>ance. It records all axis variables such as position, speed,<br />

acceleration and jerk.<br />

Conv<strong>en</strong>i<strong>en</strong>t commissioning<br />

• Commissioning is simplified significantly by the configuration and diagnostic dialogs offered in<br />

the <strong>TwinCAT</strong> System Manager. For each axis, all main data are displayed at a glance. The axes<br />

can be moved via function keys. Special functions such as couplings, cam plates or distance<br />

comp<strong>en</strong>sation can be triggered and observed via the System Manager. A conv<strong>en</strong>i<strong>en</strong>t dialog<br />

<strong>en</strong>ables the dynamic parameters of an axis to be determined.<br />

16


Chapter: <strong>TwinCAT</strong> Overview<br />

<strong>TwinCAT</strong> NC I – axis interpolation in three dim<strong>en</strong>sions<br />

• <strong>TwinCAT</strong> NC I (interpolation) is the NC system for linear and circular interpolated path<br />

movem<strong>en</strong>ts of axis groups each involving two or three drives. The system includes interpreter,<br />

set value g<strong>en</strong>eration and position controller. PLC functionality is integrated, as is the connection<br />

of the axes with the fieldbus.<br />

• The interpreter interprets the code described in DIN 66025. Compreh<strong>en</strong>sive PLC libraries <strong>en</strong>able<br />

interaction betwe<strong>en</strong> NC and PLC. NC programs, for example, can be loaded directly from the PLC<br />

program into the interpreter.<br />

<strong>TwinCAT</strong> CNC – the software CNC for toughest requirem<strong>en</strong>ts<br />

• <strong>TwinCAT</strong> CNC expands <strong>TwinCAT</strong> NC I with classic CNC features: Up to 32 interpolating axes and<br />

compreh<strong>en</strong>sive coordinate and kinematic transformations are possible. Parts programming is<br />

carried out according to DIN 66025 using high-level language ext<strong>en</strong>sions. <strong>TwinCAT</strong> CNC can<br />

operate with up to 64 axes or 32 path axes and controlled spindles that can be distributed<br />

across up to twelve CNC channels. In a CNC channel, up to 32 axes can be interpolated<br />

simultaneously, <strong>en</strong>abling ev<strong>en</strong> the most difficult motion tasks to be solved.<br />

17


Chapter: <strong>TwinCAT</strong> Overview<br />

2. System Service<br />

• The <strong>TwinCAT</strong> System Service is repres<strong>en</strong>ted by the <strong>TwinCAT</strong> icon in the Windows system tray.<br />

• The <strong>TwinCAT</strong> System Service can be accessed through the <strong>TwinCAT</strong> icon in the windows system<br />

tray (Right-Click and Left-Click provides the same m<strong>en</strong>u)<br />

• From this m<strong>en</strong>u the other parts of the <strong>TwinCAT</strong> system can be accessed and the <strong>TwinCAT</strong><br />

System Properties can be changed<br />

18


Chapter: <strong>TwinCAT</strong> Overview<br />

• The G<strong>en</strong>eral tab of the system properties provides the version number and registration<br />

information of <strong>TwinCAT</strong><br />

• Note that the 30 day counter has started and the Reg. Key is empty<br />

19


Chapter: <strong>TwinCAT</strong> Overview<br />

• The upper half of the System Tab shows which <strong>TwinCAT</strong> servers are installed<br />

• The lower half provides settings for how <strong>TwinCAT</strong> will act wh<strong>en</strong> windows boots up<br />

• Auto Boot:<br />

• Disable – The <strong>TwinCAT</strong> System Service will boot in Stop Mode<br />

• Enable – The <strong>TwinCAT</strong> System Service will boot in Run Mode<br />

• This would be the preferred setting on a running machine<br />

• Config Mode – The <strong>TwinCAT</strong> System Service will boot in Config Mode<br />

• ADS services are running, remote communication is possible<br />

• Auto Logon:<br />

• Enabling this option and providing a User Name and Password will allow for the<br />

Windows Logon scre<strong>en</strong> to be bypassed, this is ideal for a running machine but not for a<br />

developm<strong>en</strong>t laptop as this information is stored in plain text in the windows registry.<br />

Note: See the security section for protecting the windows registry.<br />

20


Chapter: <strong>TwinCAT</strong> Overview<br />

• AMS Router – Automation Machine Specification<br />

• AMS Router – Automation Machine Specification<br />

• The AMS Router is the communication router for <strong>TwinCAT</strong><br />

• Every piece of information that travels from one piece of software to another must go<br />

through the AMS Router<br />

• AMS NetID xxx.xxx.xxx.xxx.1.1<br />

• The address of the local <strong>TwinCAT</strong> Service<br />

• Every address on the network should be unique<br />

• The default address is g<strong>en</strong>erated by the IP address of the network card with an<br />

additional .1.1 added to the <strong>en</strong>d<br />

• The first four octets of the address can be changed to any number betwe<strong>en</strong> 0 and 255.<br />

They do not have to match the IP address<br />

• The last two octets should not be changed as .1.1 repres<strong>en</strong>ts the external address and<br />

other values are used internally<br />

21


Chapter: <strong>TwinCAT</strong> Overview<br />

• Remote Computers<br />

• The lower section provides a list of remote computers than have be<strong>en</strong> previously<br />

configured for AMS communication<br />

• Remote Computers can be manually added or removed from here<br />

• The list of computers is loaded wh<strong>en</strong> <strong>TwinCAT</strong> <strong>en</strong>ters either Config or Run mode,<br />

therefore if a computer is added or removed from here, <strong>TwinCAT</strong> must be restarted to<br />

update the list of Target Computers in the System Manager<br />

22


Chapter: <strong>TwinCAT</strong> Overview<br />

• PLC<br />

• Up to 4 PLC Run-Times can be configured<br />

• The path of the Boot Project can be changed<br />

• The selection to <strong>en</strong>able the Boot Project and Retain Data can be made<br />

23


Chapter: <strong>TwinCAT</strong> Overview<br />

• Registration<br />

• The System ID is needed for lic<strong>en</strong>sing<br />

• It is advised that on a running machine the customer should record the System ID and<br />

Registration Key. In the ev<strong>en</strong>t of a Hard Disk failure these two numbers and the new<br />

System ID can be used to g<strong>en</strong>erate a new Registration Key Otherwise the original PO is<br />

needed to g<strong>en</strong>erate a new Registration Key<br />

24


Chapter: <strong>TwinCAT</strong> Overview<br />

• The System Manager and PLC Control can also be accessed through this m<strong>en</strong>u or the Windows<br />

Start m<strong>en</strong>u<br />

• Additionally the local <strong>TwinCAT</strong> System can be placed into its differ<strong>en</strong>t modes<br />

• Stop Mode<br />

• The system is not capable of communication and no services are running<br />

• Config Mode<br />

• The ADS Router is running and communication is possible<br />

• Scanning of hardware is done is this mode only<br />

• I/O values are updated at the hardware level<br />

• Run Mode (Requires Lic<strong>en</strong>se beyond 30 day Trial)<br />

• All services are <strong>en</strong>abled and running if configured to do so (i.e. Boot Project)<br />

25


Chapter: <strong>TwinCAT</strong> Overview<br />

3.<br />

System Manager<br />

• The <strong>TwinCAT</strong> System Manager is used to configure the links betwe<strong>en</strong> Hardware and<br />

Software<br />

• I/O Configuration – All Fieldbus Hardware<br />

• PLC Configuration – PLC Run-Times (up to 4)<br />

• NC Configuration – Axes (real and virtual), Cam Tables, Interpolation Channels<br />

• System Configuration – Properties of the Target System and Real-Time Usage<br />

26


Chapter: <strong>TwinCAT</strong> Overview<br />

M<strong>en</strong>us and Controls<br />

• File M<strong>en</strong>u – Allows for creating a new file or op<strong>en</strong>ing a saved file.<br />

• Additionally provides a way to op<strong>en</strong> the Curr<strong>en</strong>tConfig.tsm file from the Boot folder, by<br />

using ‘Op<strong>en</strong> from Target’ also referred to as ‘The Red Folder’.<br />

27


Chapter: <strong>TwinCAT</strong> Overview<br />

• Actions – Any time a change is made to the System Manager, the ‘Activate Configuration’ must<br />

be done to implem<strong>en</strong>t this change into the running system.<br />

Note: The first 6 commands in the ‘Actions’ m<strong>en</strong>u will be s<strong>en</strong>t to the Target system either local<br />

or remote.<br />

28


Chapter: <strong>TwinCAT</strong> Overview<br />

The tree view on the left provides access to the configurations of the system manager. Wh<strong>en</strong> an<br />

item on the left is selected its information will be displayed on the right. Items can be added to<br />

the System Manager be ‘Right-Clicking’ on an existing item. Become familiar with this, almost<br />

every item you wish to add in both the system manager and the PLC will be done by ‘Right-<br />

Clicking’ and select ‘Add...’ or ‘App<strong>en</strong>d…’<br />

• System Configuration – Provides information and settings for the overall <strong>TwinCAT</strong> System<br />

• The settings available from the ‘Properties’ of the <strong>TwinCAT</strong> icon can be accessed from here on a<br />

remote system.<br />

29


Chapter: <strong>TwinCAT</strong> Overview<br />

G<strong>en</strong>eral – The <strong>TwinCAT</strong> version is provided here in bold<br />

The ‘Choose Target…’ button can be used to access a remote <strong>TwinCAT</strong> system.<br />

30


Chapter: <strong>TwinCAT</strong> Overview<br />

• Boot Settings – can be used to set the <strong>TwinCAT</strong> Mode on startup and the Auto Logon<br />

• Wh<strong>en</strong> pointed to a remote system these setting will be applied to the remote system. The<br />

‘Apply’ button must be used, and an Administrator level user name and password must be<br />

provided.<br />

31


Chapter: <strong>TwinCAT</strong> Overview<br />

• Real-Time Settings<br />

• Settings – Here the Base Time is set; no task can be set to a faster interval than the base time.<br />

• The CPU limit of 80% means that <strong>TwinCAT</strong> will consume no more than 80% to run all of its tasks.<br />

32


Chapter: <strong>TwinCAT</strong> Overview<br />

• Online – The ‘Real Time Usage’ is graphed and the limit from the ‘Settings’ tab is indicated by<br />

the thick gre<strong>en</strong> line<br />

• System Lat<strong>en</strong>cy should be no more than 5 micro seconds<br />

• Note: Image tak<strong>en</strong> from a laptop with power save features and CPU throttling <strong>en</strong>abled, both of<br />

these create lat<strong>en</strong>cy problems.<br />

33


Chapter: <strong>TwinCAT</strong> Overview<br />

• Priorities – The list of tasks and their priorities can be se<strong>en</strong> here<br />

34


Chapter: <strong>TwinCAT</strong> Overview<br />

• Additional Tasks<br />

• Task 1 (added by ‘Right-Clicking’ on ‘Additional Tasks’)<br />

• These additional tasks are used by C++ code to talk to variables that are linked to hardware I/O<br />

• They can also be used for simulation<br />

35


Chapter: <strong>TwinCAT</strong> Overview<br />

Wh<strong>en</strong> used for simulation the ‘Auto start’ must be checked<br />

36


Chapter: <strong>TwinCAT</strong> Overview<br />

• Route Settings<br />

• Curr<strong>en</strong>t Routes – The Remote Computers shown in this list are the same as in the ‘Properties’ of<br />

the <strong>TwinCAT</strong> icon.<br />

37


Chapter: <strong>TwinCAT</strong> Overview<br />

• NC Configuration (Numerical Control) – This is the software based motion controller of <strong>TwinCAT</strong>.<br />

The software side of all axes are configured here.<br />

Axes – The software limits the total number of axes to 255, the real limit is the amount of CPU and<br />

RAM in the computer.<br />

38


Chapter: <strong>TwinCAT</strong> Overview<br />

The ‘Online’ tab provides an overview of the status of all axes<br />

39


Chapter: <strong>TwinCAT</strong> Overview<br />

• Axes 1 – Online<br />

• The ‘Online’ tab of each axis provides a useful interface to setup and troubleshoot an axis<br />

40


Chapter: <strong>TwinCAT</strong> Overview<br />

• PLC Configuration<br />

• IEC Project – The PLC editor will create a “.tpy” file that contains addressed variables that can be<br />

linked to hardware. The name of the PLC project file is shown directly below the ‘PLC-<br />

Configuration’<br />

• The ‘IEC1131’ Tab shows the path of where the “.tpy” file was located wh<strong>en</strong> it was added to the<br />

project. If addressed variables are added to the PLC program the ‘ReScan’ button can be used to<br />

update the list of variables in the System Manager<br />

41


Chapter: <strong>TwinCAT</strong> Overview<br />

• Standard Task – The default task in the PLC is the ‘Standard’ task and runs every 10ms<br />

• Inputs of the PLC Program – Input variables have a yellow icon, Output variables have a red icon<br />

42


Chapter: <strong>TwinCAT</strong> Overview<br />

Once a variable has be<strong>en</strong> linked (connected) to hardware the icon changes as below<br />

43


Chapter: <strong>TwinCAT</strong> Overview<br />

4. PLC Control<br />

• The PLC Control provides the user with a combination of tools.<br />

• The IEC 61131-3 Language editors<br />

• A Visualization Editor<br />

• Task Configuration Utility<br />

• The Beckhoff Compilers specific to the Target Hardware (BC, BX, CX-ARM, X86)<br />

44


Chapter: <strong>TwinCAT</strong> Software Installation<br />

III.<br />

<strong>TwinCAT</strong> Software Installation<br />

5.<br />

<strong>TwinCAT</strong> Versions<br />

There are several builds within each version<br />

New builds are released primarily to accommodate new hardware<br />

New versions are released wh<strong>en</strong> features are added<br />

A Brief History<br />

• <strong>TwinCAT</strong> 2.6 Build 315 August 2, 1999<br />

• <strong>TwinCAT</strong> 2.7<br />

• <strong>TwinCAT</strong> 2.8<br />

• Change from wsm to tsm<br />

• Use of XML for system configuration<br />

• Config Mode for scanning hardware<br />

• <strong>TwinCAT</strong> 2.9<br />

• <strong>TwinCAT</strong> 2.10<br />

• TcMC2.lib<br />

• <strong>TwinCAT</strong> 2.11 Build 1552<br />

• <strong>TwinCAT</strong> 2.11 R2<br />

• Change in preparation for <strong>TwinCAT</strong> 3<br />

• Required for CX5000<br />

• <strong>TwinCAT</strong> 2.11 R3<br />

45


Chapter: <strong>TwinCAT</strong> Software Installation<br />

Release Notes:<br />

Changes from 2.10 to 2.11<br />

<strong>TwinCAT</strong> Base System<br />

Integration of MDP (Modular Device Profile – a g<strong>en</strong>eric interface for device information)<br />

Integration of configuration tool for AX5xxx drives<br />

Optimized behavior for use with Windows Vista and Windows 7<br />

Optimization for <strong>TwinCAT</strong> running on Quad-core and Octo-core CPUs<br />

Time synchronization with EL6692 (EtherCAT bridge)<br />

Time synchronization with EL6688 (IEEE 1588/Precision Time Protocol)<br />

New modular structure of I/O drivers<br />

Base for new supplem<strong>en</strong>t products like <strong>TwinCAT</strong> Kinematic Transformation<br />

In addition to the features available in 2.11, the following new features were implem<strong>en</strong>ted in Release 2 (2.11 R2):<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

support for CX50xx controllers<br />

support for CU2508 (port multiplier)<br />

support for AX5805 (safety card for AX5xxx)<br />

support for EP1908<br />

new Motion Control feature: multi-cam<br />

ext<strong>en</strong>ded slave error handling for NC<br />

multi-linear coupling (multi-GearIn)<br />

In addition to the features available in 2.11 R2, the following new features were implem<strong>en</strong>ted in Release 3 (2.11<br />

R3):<br />

<br />

<br />

<br />

<br />

CX50xx, additional interfaces like EtherCAT Slave<br />

EL7201 support (NC PTP)<br />

Supports new PCIe fieldbus adapters<br />

New Phasing functionality for NC PTP<br />

46


Chapter: <strong>TwinCAT</strong> Software Installation<br />

6. Software, Download & Installation<br />

• The <strong>TwinCAT</strong> software can be downloaded from www.beckhoff.com<br />

• Select ‘Download’ from the top of the page<br />

47


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Scroll down to the Software section and select <strong>TwinCAT</strong> 30 days version<br />

• Select <strong>TwinCAT</strong><br />

48


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• The form must be filled in with a valid email address<br />

• Below the form you can select the version and build of <strong>TwinCAT</strong> you would like to download<br />

• After selecting the “Registration” button an email will be s<strong>en</strong>t; to the address provided,<br />

containing a link to download the software<br />

49


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Selecting the link in the email will start the download<br />

• Double-Click the exe file to start the installation process<br />

• The file name will match the version number and build that you selected during the registration<br />

process<br />

50


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• If you receive the following warning select Run<br />

• Select your preferred language and th<strong>en</strong> select next<br />

51


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• The InstallShield Wizard will begin the install process<br />

52


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Wh<strong>en</strong> prompted select next<br />

53


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Accept the lic<strong>en</strong>se agreem<strong>en</strong>t and select next<br />

54


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Fill in the User Name and Company Name (This information will be viewable in the software)<br />

• Use ‘DEMO’ for the serial number<br />

55


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Selecting the level of <strong>TwinCAT</strong> to install (All levels are inclusive of lower levels)<br />

• CP – Includes the ADS driver, used for OPC Server, Beckhoff Control Panels, and other<br />

ADS communication<br />

• I/O – Includes the system manager for configuring hardware, used wh<strong>en</strong> writing C/C++<br />

code to control the I/O<br />

• PLC – Includes the IEC 61131-3 PLC editor and the Beckhoff compilers<br />

• NC PTP – Numerical Control for Point to Point motion with associated libraries<br />

• NC – I Numerical Control for Interpolated motion with associated libraries<br />

56


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Registration Type<br />

• 30 Day demo – Full functionality for 30 days, after 30 days <strong>TwinCAT</strong> will no longer go<br />

into run mode. Developm<strong>en</strong>t and Remote connections are still possible. Re-installing<br />

will provide another 30 days<br />

• Register now – A System ID will be provided for you to call in with<br />

• The recomm<strong>en</strong>ded practice is to select the 30 Demo and th<strong>en</strong> s<strong>en</strong>d scre<strong>en</strong>shots of the<br />

System ID via email. Lic<strong>en</strong>ses can be provided within 24 hours except week<strong>en</strong>ds and<br />

holidays<br />

57


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Select the additional features to install with <strong>TwinCAT</strong><br />

• The desired features should be selected here, afterwards select Next to continue<br />

• <strong>TwinCAT</strong> I/O – Allows the direct access to IO via a DLL. Can be installed with <strong>TwinCAT</strong><br />

PLC or <strong>TwinCAT</strong> NC PTP.<br />

• <strong>TwinCAT</strong> Scope View – A software Oscilloscope for monitoring variables in real time<br />

• <strong>TwinCAT</strong> Cam Server – A Cam tool for setting outputs on Lightbus, has never be<strong>en</strong> sold<br />

in North America, replaced by newer technology<br />

• <strong>TwinCAT</strong> EDS and GSD files – files for DeviceNet and Profibus hardware<br />

• <strong>TwinCAT</strong> Remote Manager – For managing differ<strong>en</strong>t versions of <strong>TwinCAT</strong> on one PC.<br />

• <strong>TwinCAT</strong> Drive Manager – Used for Configuring the AX5000 servo drives<br />

• <strong>TwinCAT</strong> BACnet/IP – BACnet Server for building Automation and HVAC systems.<br />

58


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Specify the path for the <strong>TwinCAT</strong> installation<br />

• The default path is highly recomm<strong>en</strong>ded, project files that the user creates can be<br />

stored in any desired location<br />

59


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• Specify the Program Folder for the <strong>TwinCAT</strong> installation<br />

• The default path is highly recomm<strong>en</strong>ded, project files that the user creates can be<br />

stored in any desired location<br />

• The installer will now install the needed compon<strong>en</strong>ts<br />

60


Chapter: <strong>TwinCAT</strong> Software Installation<br />

• You must reboot the PC after the installer has completed<br />

• After rebooting the PC you will see the <strong>TwinCAT</strong> icon in the Windows System Tray<br />

• <strong>TwinCAT</strong> is in ‘Stop Mode’ by default<br />

61


Chapter: <strong>TwinCAT</strong> Software Installation<br />

7.<br />

Lic<strong>en</strong>sing and Registration<br />

Single left click the <strong>TwinCAT</strong> Icon in the system tray, and select properties<br />

62


Chapter: <strong>TwinCAT</strong> Software Installation<br />

Once properties is selected the ‘<strong>TwinCAT</strong> System Properties’ window will appear. Select the last tab<br />

(Registration) on the top of the window. At this point you can take a scre<strong>en</strong> capture of the curr<strong>en</strong>t<br />

System ID and report it to your Inside Sales Repres<strong>en</strong>tative.<br />

63


Chapter: PLC Overview<br />

IV.<br />

PLC Overview<br />

8. IDE<br />

The Integrated Developm<strong>en</strong>t Environm<strong>en</strong>t (IDE) of <strong>TwinCAT</strong> provides a complete set of developm<strong>en</strong>t<br />

tools for the PLC. <strong>TwinCAT</strong> PLC Control puts a simple approach to the powerful IEC languages at<br />

the disposal of the PLC programmer. Use of the editors and debugging functions is based upon<br />

the prov<strong>en</strong> developm<strong>en</strong>t program <strong>en</strong>vironm<strong>en</strong>ts of advanced programming languages.<br />

The Left column provides four tabs at the bottom.<br />

64


Chapter: PLC Overview<br />

POUs – Program Organizational Units – This will contain the code writt<strong>en</strong> by the programmer,<br />

Programs, Function Blocks, and Functions<br />

Data Types – Here the programmer can create Structures and Enumerations to be used in the PLC<br />

code<br />

Visualizations – Interface scre<strong>en</strong>s for use by Maint<strong>en</strong>ance personnel or Operators can be created.<br />

65


Chapter: PLC Overview<br />

Resources – The resources tab contains several items. The Global Variable Lists, Library Manager,<br />

PLC Configuration, and Task Configuration are all accessible from this tab.<br />

A POU is op<strong>en</strong>ed by double-clicking on it.<br />

66


Chapter: PLC Overview<br />

The POU contains 2 parts, the Declaration section, and the Code section. The first line of the<br />

declaration section defines the type of POU and the name of the POU. Following this is the local<br />

variable declaration, the variables that are local to this POU are defined betwe<strong>en</strong> the Keywords<br />

VAR and END_VAR. Below the Declaration section is the Code section, this part of the window<br />

will contain the PLC code of the POU.<br />

Additionally there is a Message Window at the bottom.<br />

The Message Window can be hidd<strong>en</strong> or shown, from the ‘Window’ m<strong>en</strong>u select ‘Messages’ or the<br />

keyboard shortcut ‘Ctrl + ESC’<br />

The Message window will show Errors, Warnings, and compile information.<br />

67


Chapter: PLC Overview<br />

9. Programs<br />

A program is a POU which returns several values during operation. Programs are recognized globally<br />

throughout the project. All values are retained from the last time the program was run until the next.<br />

Programs are called from either a PLC Task or another Program. If a one program calls another program,<br />

and if the values of the program are changed, th<strong>en</strong> these changes are retained the next time the<br />

program is called, ev<strong>en</strong> if the program has be<strong>en</strong> called from within a differ<strong>en</strong>t program.<br />

Programs can call all types of POUs, they can call Functions, Function Blocks, and other<br />

Programs. By default wh<strong>en</strong> a new Project is started, a Standard Task is created that calls the Program<br />

MAIN, from MAIN all other POUs are called. Because Programs are recognized globally, the local<br />

variables declared inside of them will refer<strong>en</strong>ced by first using the name of the program and th<strong>en</strong> the<br />

name of the variable, separated by a dot ‘.’. In the below example; the variable bStart is defined with an<br />

address as a local variable in MAIN, in the PLC-Configuration of the <strong>TwinCAT</strong> System Manager the<br />

variable will be MAIN.bStart, whereas a variable defined globally will only show the name of the<br />

variable.<br />

68


Chapter: PLC Overview<br />

10.<br />

Data Types and Conversions<br />

Elem<strong>en</strong>tary data types form the foundation of the programmer’s tools to repres<strong>en</strong>t and use<br />

information.<br />

The elem<strong>en</strong>tary data types within <strong>TwinCAT</strong> Plc Control are below.<br />

69


Chapter: PLC Overview<br />

The BOOL data type is used to define a Boolean or Bit-wise variable.<br />

The BOOL data type takes the value of either TRUE or FALSE at runtime.<br />

The conversion operator BOOL_TO_INT may be used to convert a TRUE/FALSE into ‘1/0’,<br />

respectively.<br />

Declaration syntax:<br />

VariableName : BOOL := InitialValue ;<br />

Example:<br />

pushButton01 : BOOL ;<br />

Declaration with Initial Value:<br />

drainValveOp<strong>en</strong> : BOOL := TRUE ;<br />

Use the {BYTE, WORD, DWORD, SINT, USINT, INT, UINT, REAL, LREAL} data set to define<br />

an appropriate value range for a variable.<br />

Declaration syntax:<br />

VariableName : DataType { :=


Chapter: PLC Overview<br />

The STRING data type is utilized to define and use ASCII character strings.<br />

Declaration Example:<br />

VariableName : STRING { := ‘StringValue’ } ;<br />

(* Declares STRING-type variable MyString with initialized value of “This is my string” *)<br />

MyString : STRING := ‘This is my string’ ;<br />

A STRING always occupies a memory size equal to the string size plus one byte for a null termination<br />

character. The default size for a STRING is 80 bytes + one byte for a null terminating character, the<br />

maximum size is 255 bytes + one byte for a null terminating character.<br />

The {TIME, TIME_OF_DAY, DATE, DATE_TIME} data set supports duration measurem<strong>en</strong>t and/or time<br />

stamping. The necessary data type is selected dep<strong>en</strong>ding on scope of measurem<strong>en</strong>t. For example,<br />

DATE_TIME for a time stamp vs. TIME for, say, the duration of a timer.<br />

The Standard attempts to remove a major source of errors compared to conv<strong>en</strong>tional Ladder-Language<br />

PLC programming errors with a mandate of Strong Data Types. The Plc Program Compiler should be<br />

able to detect wh<strong>en</strong> a programmer, for example, attempts to assign a WORD variable to another variable<br />

of type TIME. As such, Conversion Functions are integrated within Plc Control to provide explicit<br />

conversion from one elem<strong>en</strong>tary data type to another. The conversion operation is defined as a function.<br />

The function returns the argum<strong>en</strong>t’s value as the desired, converted data type. The g<strong>en</strong>eral scheme is<br />

defined as DataType1_TO_DataType2 ( VariableToConvert ) Where DataType1 is the data type of the<br />

variable being converted and DataType2 is the desired data type. For example, the code snippet<br />

converts MyWordVariable from WORD to INT (integer).<br />

WORD_TO_INT(MyWordVariable)<br />

The variable, MyReturnedInt, is assigned to this converted value.<br />

MyReturnedInt := WORD_TO_INT(MyWordVariable) ;<br />

71


Chapter: PLC Overview<br />

11.<br />

Variables<br />

• A Variable is a name giv<strong>en</strong> to a location in memory that stores a value<br />

• A Variable has up to 5 properties<br />

1. Name<br />

2. Size (Defined by the Type)<br />

3. Value<br />

4. Memory Location<br />

5. PLC Address<br />

• In accordance with IEC 61131-3 a variable name must adhere to the following rules<br />

1. Must begin with a Letter or an Underscore<br />

2. Can followed by Letters, Underscores, or Numbers<br />

• No distinction is made betwe<strong>en</strong> Uppercase and Lowercase Letters<br />

• Special characters cannot be used (!@#$%^&*)<br />

• Blanks or Spaces are not allowed<br />

• Repeated or Sequ<strong>en</strong>tial Underscores are not allowed<br />

Descriptive abbreviations aid in understanding the value that is held by the variable<br />

72


Chapter: PLC Overview<br />

The use of abbreviated data types in the name of the variable help in the understanding of what the<br />

variable is. By placing a lower case b in front of all BOOLEAN variables the person reading the program<br />

will know that this variable is of type BOOL without having to refer to the variables declaration.<br />

Additionally using a Capital letter at the beginning of each word in the variable name will aid in<br />

understanding<br />

For example:<br />

bStartConveyor is much easier to read and understand than bstartconveyor<br />

Declaration<br />

• All variables must be defined betwe<strong>en</strong> VAR and END_VAR<br />

• Place the name of the variable to the left of the colon<br />

• Place the data type to the right of the colon<br />

• VariableName : VariableType ;<br />

• bStart : BOOL ; (*bStart is of type BOOL*)<br />

• iProductNumber : INT; (*iProduct Number is of type INT*)<br />

• lrPressure : LREAL ; (*lrPressure is of type LREAL*)<br />

Variable Scope<br />

• Global Variables can be read and writt<strong>en</strong> to from anywhere in the PLC program<br />

73


Chapter: PLC Overview<br />

• Local Variables can only be writt<strong>en</strong> to from within the POU where they are defined<br />

• The local variable of any POU can be read by first accessing the POU instance that the variable is<br />

defined in and th<strong>en</strong> using the ‘.’ to access the local variables defined within that POU<br />

• Local variables cannot be writt<strong>en</strong> to from another POU<br />

74


Chapter: PLC Overview<br />

Initial Values<br />

• All Variables have the option of assigning an initial value<br />

• This value will be writt<strong>en</strong> to memory wh<strong>en</strong> the PLC starts, after which the code of the PLC will<br />

control the value<br />

• bStart : BOOL := FALSE ; (*bStart is of type BOOL and has an initial value of FALSE*)<br />

• iProductNumber : INT := 1 ; (*iProduct Number is of type INT and has an initial value of 1*)<br />

• lrPressure : LREAL := 2.3 ; (*lrPressure is of type LREAL and has an initial value of 2.3*)<br />

It is also possible to assign an initial value to a variable in an instance of a function block<br />

• fbTON1 : TON := (PT := T#1s) ; (*fbTON1 is of type TON and the PT input has an initial value of 1<br />

second*)<br />

Constants<br />

• Variables defined as Constants cannot be writt<strong>en</strong> to by the PLC<br />

• Constants are declared similar to initial values<br />

• Use of the keyword ‘Constant’ at the beginning of the declaration section signals the compiler<br />

that the variable is a constant.<br />

75


Chapter: PLC Overview<br />

Remnant Variables<br />

• Remnant variables can retain their value throughout the usual program run period. These<br />

include Retain variables and Persist<strong>en</strong>t variables.<br />

• Retained Data<br />

• These variables maintain their value ev<strong>en</strong> after an uncontrolled shutdown of the<br />

controller as well as after a normal switching off and on of the controller or at the<br />

command 'Online', 'Reset‘. Wh<strong>en</strong> the program is run again, the stored values will be<br />

processed further. A concrete example would be a piece-counter in a production line<br />

that recomm<strong>en</strong>ces counting after a power failure. Retain-Variables are reinitialized at a<br />

new download of the program unlike persist<strong>en</strong>t variables. Variables stored with RETAIN<br />

are initialized after a "Rebuild all" of the PLC program. With a “Reset all” RETAIN<br />

variables are initialized.<br />

• Persist<strong>en</strong>t Data<br />

• These variables are stored with the complete symbol. Therefore symbol g<strong>en</strong>eration<br />

must be selected. Persist<strong>en</strong>t variables conserve their old values after a "Rebuild all" of<br />

the PLC program. To initialize the PERSISTENT variables choose Reset all. On a <strong>TwinCAT</strong><br />

shutdown the persist<strong>en</strong>t variables are writt<strong>en</strong> in a special file. This file contains the old<br />

values of the persist<strong>en</strong>t variables and is read on a <strong>TwinCAT</strong> start.<br />

76


Chapter: PLC Overview<br />

12.Languages<br />

The IEC 61131-3 specifies 5 languages for writing PLC code. <strong>TwinCAT</strong> provides these plus 1 extra<br />

• IL – Instruction List<br />

• LD – Ladder Diagram<br />

• FBD – Function Block Diagram<br />

• SFC – Sequ<strong>en</strong>tial Function Chart<br />

• ST – Structured Text<br />

• CFC – Continuous Function Chart (Non-IEC)<br />

IL – Instruction List<br />

• IL has a similar structure to assembly language and is comparable to the statem<strong>en</strong>t list language<br />

provided by Siem<strong>en</strong>s.<br />

• In IL only 1 command can be processed per line of code.<br />

• The command is th<strong>en</strong> followed by a variable or a literal value.<br />

• For example the following will increase the variable Speed by a value of 5<br />

77


Chapter: PLC Overview<br />

LD – Ladder Diagram<br />

• LD was created with the int<strong>en</strong>tion of repres<strong>en</strong>ting the electrical wiring diagrams of relay logic<br />

• LD is a graphical language that displays a power rail on each side that repres<strong>en</strong>ts the supply and<br />

the common of the wiring diagram<br />

• The below examples shows a common latching circuit in LD<br />

78


Chapter: PLC Overview<br />

FBD – Function Block Diagram<br />

• FBD is a graphical language that is similar to an electronic circuit diagram<br />

• The below example has the same functionality as the above latching circuit<br />

79


Chapter: PLC Overview<br />

SFC – Sequ<strong>en</strong>tial Function Chart<br />

• SFC; although defined as a language, is better thought of as a way to organize code and control<br />

the sequ<strong>en</strong>ce of operation<br />

• Each Step and Transition in SFC has code inside of it that can be writt<strong>en</strong> in any of the other<br />

languages including SFC<br />

80


Chapter: PLC Overview<br />

ST – Structured Text<br />

• ST is a high level language which looks similar in syntax to PASCAL<br />

• ST is the most powerful and flexible of all the languages<br />

• Wh<strong>en</strong> using ST it is important to remember that the variable being writt<strong>en</strong> to (the output) is on<br />

the left<br />

• The below example provides the same latching circuit operation as the ones above<br />

81


Chapter: PLC Overview<br />

CFC – Continuous Function Chart (Non-IEC)<br />

• CFC is an additional language provided within <strong>TwinCAT</strong>, yet it is not a part of the IEC 61131-3<br />

Standard<br />

• CFC is a graphical language very similar to FBD<br />

• The order of execution is determined by the number, and is able to be modified by the<br />

programmer<br />

82


Chapter: PLC Overview<br />

13.Functions<br />

• A Function is a re-useable piece of code that will process the defined inputs and return a single<br />

result<br />

• AND, OR, SQRT, SIN, COS, GT, LE are all examples of Functions<br />

• The programmer can also create their own Functions that normally involve more complicated<br />

tasks, such as converting a temperature value from Celsius to Fahr<strong>en</strong>heit or scaling an analog<br />

input value from 0-32767 to 0-10<br />

• Functions can be called from any other POU type, but are only capable of calling other functions<br />

• Note: Functions have no memory space and therefore they do not retain any values from one<br />

PLC scan to the next. Each function starts new each PLC scan.<br />

Declaration<br />

• The Declaration of a Function contains 4 parts<br />

• The Name of the Function<br />

• The Return type of the Function<br />

• The Variables to be passed into the Function<br />

• The local variables used by the Function<br />

• The Name of the Function<br />

• Following the Beckhoff coding conv<strong>en</strong>tion, the name of the Function starts with F_<br />

• The same IEC rules for naming of variables apply to the naming of Functions<br />

• Following the Name of the Function is the Return Type<br />

• A Function can only Return one variable<br />

83


Chapter: PLC Overview<br />

• The Variables to be passed into the Function<br />

• In the below example iTempInCelsius is the Variable that is being passed into the<br />

function<br />

84


Chapter: PLC Overview<br />

Code<br />

• The working code of the Function<br />

• Tf := 9/5 * Tc + 32<br />

• In the example code the integer value iTempInCelsius is converted to a real number.<br />

This is a Function that is built into <strong>TwinCAT</strong><br />

• The literal values of 9 and 5 both have a decimal point to signify them as REAL numbers<br />

and not integers.<br />

• Before writing the calculated value to the output the number is converted back to an<br />

integer. (Yes, this does cause inaccuracy due to rounding.)<br />

85


Chapter: PLC Overview<br />

Implem<strong>en</strong>tation<br />

• iTempC is declared as an INT with an initial value of 100<br />

• iTempF is declared as an INT with no initial value<br />

• In the code the Function F_CtoF is called and iTempC is passed into it.<br />

• The result of the Function is th<strong>en</strong> stored in iTempF.<br />

86


Chapter: PLC Overview<br />

14.Function Blocks<br />

• A Function Block is a re-useable piece of code that can have multiple inputs and outputs.<br />

Function Blocks are instantiated; therefore each time a Function Block is used it must be<br />

assigned a unique instance name. Each instance receives its own space in memory and<br />

therefore will retain its values from one PLC scan to the next.<br />

• TON, CTU, R_Trig, FB_FileOp<strong>en</strong>, ADSREAD, are just a few examples of Function Blocks<br />

• The programmer can also create their own Function Blocks to perform a variety of tasks.<br />

• Function Blocks can be called by Programs or other Function Blocks. Function Blocks can all<br />

other Function Blocks and Functions.<br />

• Note: It is possible to call a Program from a Function Block. Just because you can doesn’t mean<br />

you should. <strong>TwinCAT</strong> provides you with the flexibility to do many things (some good, some not<br />

so good), once you understand the inner workings of the software you will understand why<br />

doing this can cause problems, all of which must be handled by the programmer.<br />

87


Chapter: PLC Overview<br />

Declaration<br />

• The Declaration of a Function Block contains 4 parts<br />

• The Name of the Function Block<br />

• The Variables to be passed into the Function Block<br />

• The Variables to be passed out of the Function Block<br />

• The Variables that are internal to the Function Block<br />

• The Name of the Function Block<br />

• Following the Beckhoff coding conv<strong>en</strong>tion, the name of the Function Block starts with<br />

FB_<br />

• The same IEC rules for naming of variables apply to the naming of Function Blocks<br />

88


Chapter: PLC Overview<br />

• The Variables to be passed into the Function Block<br />

• Below the Enable, Time On, and Time Off values are being passed into the Function Block<br />

89


Chapter: PLC Overview<br />

• The Variables to be passed out of the Function Block<br />

• Below the Output variable has be<strong>en</strong> added<br />

90


Chapter: PLC Overview<br />

• The Variables that are internal to the Function Block<br />

• Below the two timers to be used have be<strong>en</strong> instantiated<br />

• fbTON is of type TON<br />

• fbTOF is of type TOF<br />

91


Chapter: PLC Overview<br />

Code<br />

• The working Code of the Function Block<br />

• Below the two timers are called with their instance name<br />

• The := symbol signifies that a value of the variable is being passed into the FB and the => symbol<br />

signifies that a value of the variable is being passed out of the FB<br />

92


Chapter: PLC Overview<br />

• The IN of fbTON is TRUE if bEnable is TRUE and fbTOF.Q is FALSE<br />

• What is fbTOF.Q?<br />

• Anytime the ‘.’ symbol is used it signifies that the variable on the right exists inside of the<br />

variable on the left.<br />

• Q is an output of a TOF, therefore calling the instance name fbTOF followed by ‘.’ will allow<br />

access to the variables that are declared inside of fbTOF<br />

93


Chapter: PLC Overview<br />

• Also notice that fbTON.Q is passed into fbTOF, this will cause the two timers to toggle based on<br />

the values of tTimeOff and tTimeOn<br />

• Finally the output of fbTOF is passed to bPulse. bPulse is the output of FB_Pulse<br />

• This could have be<strong>en</strong> done with the following<br />

• bPulse := fbTOF.Q;<br />

94


Chapter: PLC Overview<br />

Implem<strong>en</strong>tation<br />

• fbPulse1 is of type FB_Pulse fbPulse1 is an instance of FB_Pulse<br />

• bSwitch is passed into the bEnable input of fbPulse1<br />

• tTimeOn and tTimeOff are assigned literal values in the proper TIME format<br />

• bPulse is passed out of fbPulse1 into bLight1<br />

• fbPulse2 is a second instance of FB_Pulse. It is coded differ<strong>en</strong>tly but works exactly the same.<br />

In the above example of fbPulse2 the input variables are first assigned; followed by a call of the Function<br />

Block instance on line 6. This is extremely important to understand; if line 6 was removed from the code<br />

th<strong>en</strong> the Function Block would never run. The line of code that calls the instance name and uses the<br />

par<strong>en</strong>theses is the line of code that updates the values inside of the Function Block.<br />

95


Chapter: PLC Overview<br />

15.Actions<br />

Actions are used to organize code. Both Programs and Function Blocks can use Actions (They are not<br />

allowed with Functions).<br />

Actions share their local declaration section with the POU they are attached to.<br />

To add an Action to a POU, right-click on the POU and select ‘Add Action’<br />

The name of the Action must follow the rules of the IEC Standard, the language can be of any type<br />

In the below example the Program MAIN has four Actions. A_Enable is called from the code of<br />

MAIN. The instance of fbMC_Power_Ax1 is called inside of the action A_Enable, but is declared<br />

locally in MAIN<br />

96


Chapter: PLC Overview<br />

16.Structures<br />

• Structures are used to define elem<strong>en</strong>ts of a larger item and are commonly referred to as custom<br />

data types<br />

• A temperature s<strong>en</strong>sor; for example, is more than just the temperature value<br />

• The status of the Analog input card, the scaling parameters, and the offset are all possible<br />

elem<strong>en</strong>ts that are directly related to the temperature s<strong>en</strong>sor<br />

• In order to keep these elem<strong>en</strong>ts together and make the code more re-useable a structure of<br />

these elem<strong>en</strong>ts can be created<br />

Declaration<br />

• The structure is created with its elem<strong>en</strong>t names and data types<br />

• Initial values can be giv<strong>en</strong><br />

• A structure can also contain other structures<br />

97


Chapter: PLC Overview<br />

Implem<strong>en</strong>tation<br />

• A structure must be instantiated just like a Function Block<br />

• After typing the instance name of the structure place a ‘.’ immediately after it and the intellis<strong>en</strong>se<br />

window will appear, showing what elem<strong>en</strong>ts exist inside of the structure<br />

• The elem<strong>en</strong>ts in a structure can be writt<strong>en</strong> to and/or read from<br />

98


Chapter: PLC Overview<br />

17.Enumerations<br />

• Enumerations can be used to assign a variable name to a number.<br />

• Enumerations can be used in two differ<strong>en</strong>t ways; with or without being instantiated.<br />

• If the Enumeration is not instantiated th<strong>en</strong> the Enumeration works similar to a list of constants.<br />

• If the Enumeration is instantiated th<strong>en</strong> the instance of the <strong>en</strong>umeration will hold the variable of<br />

the curr<strong>en</strong>t value of the Enumeration<br />

• Wh<strong>en</strong> the Enumeration is defined the first variable in the list will be assigned a value of 0, the<br />

variables following will be assigned their values in asc<strong>en</strong>ding order<br />

• <strong>Manual</strong> = 0<br />

• Semi_Auto = 1<br />

• Auto = 2<br />

• If a variable in the list is explicitly assigned a value th<strong>en</strong> the following variables will be<br />

increm<strong>en</strong>ted from this value<br />

• <strong>Manual</strong> = 1<br />

• Semi_Auto = 2<br />

• Auto = 3<br />

99


Chapter: PLC Overview<br />

• <strong>Manual</strong> = 1<br />

• Semi_Auto = 2<br />

• Auto = 3<br />

• Maint<strong>en</strong>ance = 10<br />

• Unknown = 11<br />

• Using Enumerations in this manner allows for easier understanding of the code wh<strong>en</strong> it is being<br />

read<br />

• In this Case statem<strong>en</strong>t the Variables in the Enumeration are used to repres<strong>en</strong>t the number<br />

equival<strong>en</strong>t of iStep1.<br />

• As iStep1 changes in value the Case statem<strong>en</strong>t will change states<br />

• iStep1 can be assigned a numerical value or an Enumeration variable<br />

• The displayed online value of iStep1 will always be an INT value because iStep1 is declared as an<br />

INT<br />

100


Chapter: PLC Overview<br />

• If an instance of the Enumeration is declared th<strong>en</strong> the instance of the Enumeration holds the<br />

variable name of the value of the Enumeration<br />

• If iStep2 is of type E_Mode th<strong>en</strong> iStep2 holds either ‘<strong>Manual</strong>’, ‘Semi_Auto’, or ‘Auto’<br />

101


Chapter: PLC Overview<br />

18.Arrays<br />

• An Array is a list of data, the data in the Array can be of any type<br />

• An Array can contain more than one dim<strong>en</strong>sion<br />

• Think of a notebook of graph paper<br />

• The column on a single sheet of paper would be a 1 dim<strong>en</strong>sional array<br />

• The <strong>en</strong>tire sheet with its rows and columns would be a 2 dim<strong>en</strong>sional array<br />

• The notebook with all of its sheets would be a 3 dim<strong>en</strong>sional array<br />

1 Dim<strong>en</strong>sional Array<br />

• The Array is defined from 1 to 10 of type INT<br />

• This Array will hold 10 integer values<br />

• The position in the Array is referred to as the index<br />

• The Array name along with an index can be used just like any other variable<br />

102


Chapter: PLC Overview<br />

2 Dim<strong>en</strong>sional Array<br />

• The Array is defined from 1 to 10 and 1 to 3 of type String<br />

• This Array will hold 30 (3*10) String values<br />

• The comma ‘,’ is used to d<strong>en</strong>ote the multiple dim<strong>en</strong>sions of the array<br />

3 Dim<strong>en</strong>sional Array<br />

103


Chapter: PLC Overview<br />

• Initializing each index of an array<br />

• Initializing multiple indexes with the same value<br />

• 2(3) indicates that the first 2 Indexes will be giv<strong>en</strong> a value of 3<br />

• The above 2 examples can be mixed together<br />

104


Chapter: PLC Overview<br />

• Indexing through an Array with a FOR loop<br />

• A FOR loop can be used to easily fill an Array or read the values in an array<br />

• The following will set all values in the Array to 0<br />

105


Chapter: PLC Overview<br />

19. Boot Project<br />

• The <strong>TwinCAT</strong> Boot Project is used on a production machine as the PLC code to be run wh<strong>en</strong><br />

<strong>TwinCAT</strong> starts.<br />

• The Boot Project must be <strong>en</strong>abled and also created.<br />

Enabling<br />

• Enabling the Boot Project is done through the <strong>TwinCAT</strong> System Service<br />

• Right Click on the <strong>TwinCAT</strong> icon in the Windows system tray and select properties<br />

• Click on the PLC tab and place a check mark in the Run-Time<br />

106


Chapter: PLC Overview<br />

Creation<br />

• To create the Boot Project: login with the PLC and select ‘Create Boot Project’ from the ‘Online’<br />

m<strong>en</strong>u<br />

107


Chapter: PLC Overview<br />

20.Source code Download<br />

• The use of the Source Code Download allows for a copy of the code to be placed on the device.<br />

• This copy of the code can be op<strong>en</strong>ed later either directly on the PC or through a remote<br />

connection.<br />

• To create the Source Code Download file you must be logged in to the PLC<br />

• From the ‘Online’ m<strong>en</strong>u select ‘Sourcecode Download’<br />

108


Chapter: PLC Overview<br />

• The Source Code file will be created in the C:\<strong>TwinCAT</strong>\Boot folder<br />

• The name of the file will be TCPLC_S_x.wbp where x will be a number from 1 to 4 which<br />

repres<strong>en</strong>ts the runtime number.<br />

• To op<strong>en</strong> the Source Code Download file, Select Op<strong>en</strong> from the File M<strong>en</strong>u<br />

• On the Op<strong>en</strong> file dialog select the ‘PLC’ button<br />

109


Chapter: PLC Overview<br />

• Select the correct Target System Type<br />

• Select the Run-Time on the Target<br />

110


Chapter: PLC Overview<br />

• The files will be copied in to your local Upload folder<br />

• C:\<strong>TwinCAT</strong>\PLC\Upload<br />

• If any of the files already exist you will be asked if you would to overwrite these files<br />

• The code will th<strong>en</strong> op<strong>en</strong><br />

• If the source code download has not be<strong>en</strong> performed you will get the following error message<br />

111


Chapter: PLC Overview<br />

21. Code Changes<br />

To make changes on an existing system, use the following steps wh<strong>en</strong> making changes to a<br />

PLC program to <strong>en</strong>sure the best results.<br />

• Verify PLC program file matches running code<br />

• Edit Code<br />

• Compile Code<br />

• Load Changes<br />

• Save File<br />

• Create Boot project<br />

• Perform a Source Code Download<br />

Verify the PLC Program<br />

• To <strong>en</strong>sure the correct version of the code is being edited you should first verify the PLC<br />

Program file matches the PLC Code that is running in <strong>TwinCAT</strong>.<br />

• Op<strong>en</strong> the file<br />

• From the ‘Online’ m<strong>en</strong>u select ‘Login’<br />

• If the PLC Program goes online without prompt, th<strong>en</strong> you can be certain that the code<br />

matches exactly.<br />

• You will also see in the bottom right corner of the PLC Control the curr<strong>en</strong>t status of the PLC<br />

112


Chapter: PLC Overview<br />

• Wh<strong>en</strong> logging in to the PLC, if you receive a prompt; pay close att<strong>en</strong>tion to the question<br />

being asked, and the available options.<br />

• ‘Online Change’<br />

• Notice at the <strong>en</strong>d of the question you are notified that this will be an (ONLINE CHANGE)<br />

• Yes – This will perform the ‘Online Change’ described in more detail on next page<br />

• No – Don’t use this option. If you accid<strong>en</strong>tally press it, simply Log Out of the PLC<br />

• Cancel – Cancels the operation<br />

• Load all – Stops the execution of the PLC and Loads all of the Code including the changes.<br />

The PLC must be started again.<br />

Online Change<br />

• The following is a description of the internal process for an Online Change that is only<br />

suitable for your understanding. The actual process is much more intricate and complicated<br />

• Imagine the below repres<strong>en</strong>ts the RAM of the Computer and the programs that are<br />

curr<strong>en</strong>tly using it<br />

• The PLC Code runs from the first line to the last line and th<strong>en</strong> repeats.<br />

113


Chapter: PLC Overview<br />

• Wh<strong>en</strong> an Online Change is performed<br />

• The New PLC Code is loaded into a separate memory location<br />

• Wh<strong>en</strong> the curr<strong>en</strong>t scan of the PLC Code has completed, instead of looping back around. The<br />

PLC will start running the New PLC Code on the next scan.<br />

• The New code is now repeated each PLC Scan and the memory where the old code was<br />

located is released, to be used by another process<br />

114


Chapter: PLC Overview<br />

Load Changes<br />

• The other possible option wh<strong>en</strong> logging in to the PLC is that the code is differ<strong>en</strong>t <strong>en</strong>ough<br />

that the PLC is not able to do an ‘Online Change’<br />

• In the below prompt notice that it does not say Online Change.<br />

• It simply asks if you would like to ‘Download the new program?’<br />

• Yes – Will stop the PLC and load the code. The PLC must be started after this.<br />

• No - Don’t use this option. If you accid<strong>en</strong>tally press it, simply Log Out of the PLC<br />

• Cancel – Cancels the operation<br />

• At this point we are still trying to verify that we have the correct version of the PLC program<br />

• One of 3 possibilities have happ<strong>en</strong>ed<br />

1. The PLC logged in without prompt<br />

2. Online Change<br />

3. Download the Program<br />

• If you are able to Login without a prompt th<strong>en</strong> you can go to the next section about Editing<br />

the Code<br />

• If an Online Change or a Download of the Program is required th<strong>en</strong> a couple of things need<br />

to be considered.<br />

• In both situations the first choice should be to look for another copy of the program.<br />

• An ‘Online Change’ is required for many things. Anything from adding a variable to changing<br />

the value of a timer.<br />

115


Chapter: PLC Overview<br />

• If a change was made, but the PLC Program was closed without saving the change, th<strong>en</strong> an<br />

‘Online Change’ will be required to Login. However, this will be loading the older version of<br />

the code.<br />

• A ‘Download’ will be required if the computer has be<strong>en</strong> restarted and the Boot Project was<br />

not updated.<br />

• Also, if the auxiliary files for the PLC Project do not exist (someone emailed only the .pro file)<br />

th<strong>en</strong> a ‘Download’ of the program will be required.<br />

• Locating the PLC Project can be done by searching for the .pro file on the hard drive.<br />

• Press the ‘Start’ button or the Windows key on the keyboard, th<strong>en</strong> press the ‘F3’ key<br />

• In the Search Box type in *.pro and press the ‘Enter’ key<br />

• Dep<strong>en</strong>ding on the size of the hard drive this might take a few minutes<br />

Source Code Download File<br />

• The last option is to op<strong>en</strong> the Source Code Download file<br />

• Wh<strong>en</strong> created this file is saved in the C:\<strong>TwinCAT</strong>\Boot directory as TCPLC_S_1.wbp for the<br />

first PLC Run-Time<br />

• To op<strong>en</strong> this file, op<strong>en</strong> the PLC Control, th<strong>en</strong> select ‘Op<strong>en</strong>’ from the ‘File’ m<strong>en</strong>u<br />

116


Chapter: PLC Overview<br />

• In the Op<strong>en</strong> File Dialog window, select the ‘PLC’ button<br />

• Select the CPU type, and click ‘OK’<br />

117


Chapter: PLC Overview<br />

• Select Run-Time1, and click ‘OK’<br />

• Click ‘Yes, all’<br />

• If the file exists it will be op<strong>en</strong>ed<br />

• If this file has be<strong>en</strong> kept up to date and matches with the PLC Code that is running inside of<br />

<strong>TwinCAT</strong>, th<strong>en</strong> you should be able to Login with this Code.<br />

• If it does not match exactly th<strong>en</strong> you will have to perform either an ‘Online Change’ or a<br />

complete ‘Download’ of the PLC Program.<br />

118


Chapter: PLC Overview<br />

Edit the Code<br />

• Now the we have a program that matches with the running code, we can make the required<br />

changes.<br />

• We will start with a simple Ladder program that needs a contact changed from ‘Normally<br />

Op<strong>en</strong>’ to ‘Normally Closed’<br />

• Left-Click on the symbol of the Contact to select it. Notice the dotted selection box around<br />

the symbol<br />

• Hold the ‘Ctrl’ key and press ‘N’<br />

• This will ‘Negate’ or invert the Contact<br />

• This same command will work for changing a NC contact to NO<br />

119


Chapter: PLC Overview<br />

• It is also possible to Right-Click on a symbol and select one of the options from the context<br />

m<strong>en</strong>u<br />

• Wh<strong>en</strong> making changes to code in FBD (Function Block Diagram) the same steps apply.<br />

• In FBD the location of the cursor is extremely important<br />

• The options in the context m<strong>en</strong>u will change based on the location of the cursor<br />

120


Chapter: PLC Overview<br />

• Cursor inside the box<br />

• Changes here effect the box itself<br />

• Cursor on the input of the box<br />

• Changes here are for the way the input interacts with the box<br />

121


Chapter: PLC Overview<br />

• Cursor on the right side of the box<br />

• Changes here effect what will be to the right of the box, typically an Assignm<strong>en</strong>t to another<br />

variable or another box<br />

• Cursor on the Assignm<strong>en</strong>t<br />

• Changes here will affect the specific output or add more outputs<br />

122


Chapter: PLC Overview<br />

Compile Code<br />

• Once the changes have be<strong>en</strong> made, it is time to Compile the code and check for errors.<br />

• From the ‘Project’ m<strong>en</strong>u select ‘Build’<br />

• This will compile the code<br />

• In the message window you should see<br />

• If you have any warnings they can typically be ignored.<br />

• Note: If you use the ‘Rebuild All’ command, your ‘Retain Data’ will be initialized.<br />

• If you have an error, press the ‘F4’ key<br />

• The ‘F4’ key will take you to the location of the first error in the message window and also<br />

op<strong>en</strong> the code to the location where the error was found.<br />

123


Chapter: PLC Overview<br />

• Sometimes error messages can be misleading. Most of the time 1 problem will cause<br />

multiple error messages.<br />

• The problem with the below line of code is that the ; is missing from the <strong>en</strong>d of the line<br />

• The error message says the problem is on Line 3. The reason for this is that the compiler<br />

ignores spaces. After the variable c the compiler is expecting to find a ; (End of Line) or an :=<br />

(Assignm<strong>en</strong>t). It doesn’t find it so it continues to line 2 and th<strong>en</strong> line 3<br />

• Line 3 is the last line of code so this is where the compiler is at wh<strong>en</strong> the error is detected<br />

• The second error is caused by the first error<br />

• Wh<strong>en</strong> the first error is corrected the second error will no longer exist<br />

124


Chapter: PLC Overview<br />

Load Changes<br />

• Once all of the errors have be<strong>en</strong> corrected, the changes can be loaded into the PLC<br />

• From the ‘Online’ m<strong>en</strong>u, select ‘Login’<br />

• Click ‘Yes’ to perform an ‘Online Change’<br />

• If additional changes need to be made<br />

• First ‘Logout’ of the PLC and th<strong>en</strong> repeat the process<br />

125


Chapter: PLC Overview<br />

Save File<br />

• Wh<strong>en</strong> you are done making changes the new File should be saved<br />

• From the ‘File’ m<strong>en</strong>u, select ‘Save’<br />

• This will replace the existing file on the hard drive with the curr<strong>en</strong>t file and the changes<br />

Boot Project<br />

• Once all changes have be<strong>en</strong> made, and before restarting <strong>TwinCAT</strong> a new ‘Boot Project’ must<br />

be created.<br />

• From the ‘Online’ m<strong>en</strong>u, select ‘Create Boot Project’<br />

• If a new Boot Project is not created, th<strong>en</strong> the next time that <strong>TwinCAT</strong> is restarted or the<br />

computer is rebooted, the old Boot Project will be loaded. If this happ<strong>en</strong>s th<strong>en</strong> a ‘Download’<br />

of the program will be required before you can log in again.<br />

• It is extremely important that the ‘Boot Project’ be kept up to date and match the PLC<br />

Program.<br />

126


Chapter: PLC Overview<br />

Source Code Download<br />

• From the ‘Online’ m<strong>en</strong>u select ‘Sourcecode Download’<br />

• This will create a file in the C:\<strong>TwinCAT</strong>\Boot directory that can be op<strong>en</strong>ed later<br />

• If this file is kept up to date, and matches the ‘Boot Project’ th<strong>en</strong> this file can also be used to<br />

‘Login’ to the PLC<br />

• This file is also useful for keeping a copy of the code on a CX device that only has the<br />

<strong>TwinCAT</strong> Run-Time and not the full developm<strong>en</strong>t<br />

Options<br />

• From the ‘Project’ m<strong>en</strong>u, select ‘Options’<br />

• In the left column select ‘Source download’<br />

127


Chapter: PLC Overview<br />

• Implicit at load<br />

• Create a new source code download file every time a change is loaded<br />

• Notice at load<br />

• Every time a change is loaded, ask the user if they would like to create a new source<br />

code download<br />

• Implicit on create boot project<br />

• Each time a new boot project is created, also create an new source code download<br />

• Note: If this option is selected th<strong>en</strong> the source code download and the boot project will<br />

always match<br />

• Only on demand<br />

• The source code download command must be manually giv<strong>en</strong> from the ‘Online’ m<strong>en</strong>u<br />

128


Chapter: PLC Overview<br />

• How much data should be placed in the file<br />

• All Files<br />

• This will place everything inside the file, including all bitmaps for any visualizations<br />

• If you have <strong>en</strong>ough room on the hard drive, th<strong>en</strong> this is the best option<br />

• Source code only<br />

• This will only place the code and other auxiliary files needed for logging in to the PLC on<br />

the hard drive<br />

• Source code only(exclude compile info)<br />

• Only the code<br />

• A download must be performed to login to the PLC<br />

129


Chapter: PLC Programming “The Inspection Conveyor”<br />

V. PLC Programming “The Inspection Conveyor”<br />

22.Machine Control with Top-Down Programming<br />

Intro<br />

This section is going to cover the design and programming of a modular conveyor. With each<br />

module a new concept and/or topic will be introduced. As the saying goes “Prior proper<br />

planning, prev<strong>en</strong>ts poor performance”. With that in mind the first topic will cover the<br />

overall machine control and the use of a state machine for automatic or manual operation.<br />

The first conveyor module will be for adding product to the system using only digital Inputs<br />

and Outputs. The second module will use an analog input to measure the size of the<br />

product. Next an analog output will be added to control the conveyor speed using a Variable<br />

Frequ<strong>en</strong>cy Drive (VFD).<br />

Machine Control/State Machine<br />

There are many ways to do overall machine control and to implem<strong>en</strong>t a state machine, both<br />

of which are outside the scope of this docum<strong>en</strong>t. For the purpose of this docum<strong>en</strong>t I have<br />

chos<strong>en</strong> to use a state machine that best serves the purpose of learning to use the <strong>TwinCAT</strong><br />

software. The overall machine control will be handled in a CASE statem<strong>en</strong>t. The machine<br />

will have the following States:<br />

Undefined: Wh<strong>en</strong> no State is defined by the PLC this will be the default State. This State is<br />

not allowed to be set by the operator. This State will be used wh<strong>en</strong> the machine is first<br />

powered on and wh<strong>en</strong> a problem in the PLC code occurs.<br />

Maint<strong>en</strong>ance: Used for making adjustm<strong>en</strong>ts to the machine or for troubleshooting<br />

individual compon<strong>en</strong>ts. Operations will be allowed in this State that could be harmful to the<br />

equipm<strong>en</strong>t. Access to this mode will be restricted.<br />

<strong>Manual</strong>: Used to start up the machine and prepare for operation, or to shut down the<br />

machine after Automatic operation. Requires operator interv<strong>en</strong>tion for all functions of the<br />

machine.<br />

Automatic: Used for routine production. The machine will process product based on the<br />

conditions of the I/O with minimal operator interv<strong>en</strong>tion.<br />

130


Chapter: PLC Programming “The Inspection Conveyor”<br />

Modular Conveyor System<br />

Each conveyor module will need to work as a standalone piece and also in conjunction with<br />

other modules in front of and/or after it. Using a photo eye at each <strong>en</strong>d of the conveyor will<br />

aid in this process. For the programming of this system each conveyor module will be a<br />

Function Block; therefore, if multiples of a module are needed they can be easily<br />

instantiated. Additionally, standard data Structures for all conveyor modules will be used by<br />

each of the Function Blocks to aid in communication betwe<strong>en</strong> modules.<br />

Machine data Structure: contains status information for the overall machine including the<br />

curr<strong>en</strong>t State.<br />

Module data Structure: contains information about the configuration of the module,<br />

including information about the previous and following module.<br />

Creating the program<br />

Op<strong>en</strong> the PLC Control by selecting the <strong>TwinCAT</strong> icon in the Windows System Tray and the<br />

select PLC Control<br />

131


Chapter: PLC Programming “The Inspection Conveyor”<br />

From the ‘File’ m<strong>en</strong>u, select ‘New’<br />

For most of this project we will not be connecting to hardware. Therefore everything will<br />

run in simulation on the computer you are using.<br />

Note: The <strong>TwinCAT</strong> 2 Run-Time is only available on Windows 32-bit Operating Systems<br />

In the ‘Choose Target System Type’ window, select ‘PC or CX (x86), th<strong>en</strong> click on ‘OK’<br />

132


Chapter: PLC Programming “The Inspection Conveyor”<br />

In the ‘New POU’ window the Type of POU should be a ‘Program’<br />

The ‘Name of the new POU:’ should be ‘MAIN’<br />

The ‘Language of the POU’ should be set to ‘ST’ for Structured Text<br />

Note: Ev<strong>en</strong> if you are an experi<strong>en</strong>ced programmer in one of the other languages, it is my<br />

recomm<strong>en</strong>dation that wh<strong>en</strong> starting a new project the MAIN program should always be<br />

done in ST. This will allow the programmer to easily call other programs and also easily<br />

comm<strong>en</strong>t out large parts of the program. Additionally I would advise that the MAIN<br />

program never be done in SFC, doing so will make using the special SFC flags much more<br />

difficult, if not impossible.<br />

133


Chapter: PLC Programming “The Inspection Conveyor”<br />

You should now have the following<br />

Place a semicolon on Line 1 of MAIN. This is the smallest program you can write.<br />

134


Chapter: PLC Programming “The Inspection Conveyor”<br />

From the ‘Project M<strong>en</strong>u’, select ‘Rebuild All’<br />

135


Chapter: PLC Programming “The Inspection Conveyor”<br />

In the ‘Message Window’ at the bottom, you should receive 0 Errors and 1 Warning.<br />

The Warning is because we have not saved the file with a name.<br />

136


Chapter: PLC Programming “The Inspection Conveyor”<br />

From the ‘File M<strong>en</strong>u’, select ‘Save As’<br />

The file can be saved anywhere you would like. I would recomm<strong>en</strong>d against saving it on the<br />

desktop, the PLC Control will also create other supporting files that will clutter your desktop<br />

quickly. I have created a folder called ‘<strong>TwinCAT</strong> 2 <strong>Manual</strong> Samples’ directly on the root of my<br />

C:\ drive.<br />

Give your project a name and press the ‘Save’ button. I would recomm<strong>en</strong>d that you use the<br />

same file name that I have used.<br />

137


Chapter: PLC Programming “The Inspection Conveyor”<br />

Adding a version number to your project name is an easy way to have multiple versions of<br />

the program, so that you can go back to a previous version later on.<br />

You will now see that the file name of the project is placed across the top of the PLC Control<br />

Before writing any real code we will first declare all known variables that will later be<br />

connected to hardware.<br />

Select the ‘Resources’ tab at the bottom of the left column<br />

138


Chapter: PLC Programming “The Inspection Conveyor”<br />

Expand the ‘Global Variables’ folder by clicking on the + sign<br />

In the ‘Global Variables’ folder there are two lists by default.<br />

The ‘Global_Variables’ and the ‘Variable_Configuration’<br />

The ‘Variable_Configuration’ list is only used for the BC line of controllers.<br />

The ‘Global_Variables’ list is included by default; however, on large machines it is good<br />

practice to create multiple lists to help organize the variables into smaller more manageable<br />

lists. Therefore, we are going to start by creating a couple of Global Variable Lists.<br />

Right Click on the ‘Global Variables’ folder, select ‘Add Object’<br />

139


Chapter: PLC Programming “The Inspection Conveyor”<br />

Change the name of the list by adding ‘_IO’ to the <strong>en</strong>d of the name, and th<strong>en</strong> click on ‘OK’<br />

Note: The name of this list must follow the IEC 61131-3 naming rules, the same as variable<br />

names. If it does not, or the name has already be<strong>en</strong> used the ‘OK’ button will be grayed out.<br />

Double-Click on ‘Global_Variables_IO’<br />

This will op<strong>en</strong> the Global Variable list.<br />

Place the cursor at the <strong>en</strong>d of line 1 and press the <strong>en</strong>ter key a couple of times.<br />

140


Chapter: PLC Programming “The Inspection Conveyor”<br />

Betwe<strong>en</strong> the key words ‘VAR_GLOBAL’ and ‘END_VAR’ is where we will declare our<br />

variables.<br />

Note: Please refer to App<strong>en</strong>dix I “Variable Naming Conv<strong>en</strong>tion” for a better understanding<br />

of the variable names used throughout this project.<br />

Comm<strong>en</strong>ts can be added to the code by placing (* at the beginning of the comm<strong>en</strong>t, and *)<br />

at the <strong>en</strong>d of the comm<strong>en</strong>t. All comm<strong>en</strong>ts will turn gre<strong>en</strong>.<br />

(*Machine Control*)<br />

The following will be Boolean inputs of type BOOL, therefore wh<strong>en</strong> the hardware detects 24<br />

Volts DC the PLC will repres<strong>en</strong>t this with TRUE, wh<strong>en</strong> the hardware detects 0 Volts DC the<br />

PLC will repres<strong>en</strong>t this with FALSE.<br />

gati_xMan_Auto_SS will be a two position Selector Switch betwe<strong>en</strong> <strong>Manual</strong> and Auto. Wh<strong>en</strong><br />

the switch is in the ‘<strong>Manual</strong>’ position the input will be off, wh<strong>en</strong> the switch is in the ‘Auto’<br />

position the input will be on.<br />

gati_xMaint<strong>en</strong>ance will be a push button to request the State Machine to go into<br />

‘Maint<strong>en</strong>ance’<br />

gati_xReset will be a push button for resetting faults<br />

141


Chapter: PLC Programming “The Inspection Conveyor”<br />

(*Stack Lights*)<br />

The use of Stack Lights allows everyone in the area of the machine to easily know the status<br />

of the machine. The definitions of what the colors repres<strong>en</strong>t vary betwe<strong>en</strong> industries and<br />

countries.<br />

For this project the following colors will be used as defined here:<br />

‘Yellow’ will be used wh<strong>en</strong> the machine is in Automatic<br />

‘Gre<strong>en</strong>’ will be used wh<strong>en</strong> the machine is in <strong>Manual</strong><br />

‘Red’ will be used wh<strong>en</strong> a Fault is active<br />

‘Blue’ will indicate that the machine is in Maint<strong>en</strong>ance<br />

Betwe<strong>en</strong> ‘Yellow’, ‘Gre<strong>en</strong>’, and ‘Blue’ only one of the can be on at any giv<strong>en</strong> time.<br />

‘Red’ can be on in addition to any of the others<br />

gatq_xAutoLight will be writt<strong>en</strong> with a value of TRUE wh<strong>en</strong> the machine is in Auto, thereby<br />

applying 24 Volts DC to the output and turning on the light.<br />

gatq_x<strong>Manual</strong>Light will be writt<strong>en</strong> with a value of TRUE wh<strong>en</strong> the machine is in <strong>Manual</strong>,<br />

thereby applying 24 Volts DC to the output and turning on the light.<br />

gatq_xFaultLight will be writt<strong>en</strong> with a value of TRUE wh<strong>en</strong> the machine is Faulted, thereby<br />

applying 24 Volts DC to the output and turning on the light.<br />

gatq_xMaint<strong>en</strong>anceLight will be writt<strong>en</strong> with a value of TRUE wh<strong>en</strong> the machine is in<br />

Maint<strong>en</strong>ance, thereby applying 24 Volts DC to the output and turning on the light.<br />

142


Chapter: PLC Programming “The Inspection Conveyor”<br />

Next we will create an Enumeration that will be used to repres<strong>en</strong>t the possible States of the<br />

State Machine.<br />

Select the ‘Data Types’ tab at the bottom of the left column<br />

143


Chapter: PLC Programming “The Inspection Conveyor”<br />

Right-Click on the ‘Data Types’ folder and select ‘Add Object’<br />

Type in ‘E_MachineState’ as the ‘Name of the new data type’, and click ‘OK’<br />

You should now have the following<br />

144


Chapter: PLC Programming “The Inspection Conveyor”<br />

Data Types always default to a ‘STRUCT’, this can be changed to an Enumeration by simply<br />

removing ‘STRUCT’ and ‘END_STRUCT’ from lines 2 and 3 and replacing them with ();<br />

Wh<strong>en</strong> creating an Enumeration the first Variable will receive a value of zero by default, each<br />

value after that will be increm<strong>en</strong>ted by one. The variables of the Enumeration must be<br />

placed betwe<strong>en</strong> ( and ) and each one separated by a comma ‘,’.<br />

145


Chapter: PLC Programming “The Inspection Conveyor”<br />

Now would be a good time to save the changes that have be<strong>en</strong> made. From the ‘File’ m<strong>en</strong>u,<br />

select ‘Save’. Or simply press and hold the ‘Ctrl’ key and the press the ‘S’ key.<br />

Notice that the asterisk * and the <strong>en</strong>d of the file name disappears. The asterisk is there to<br />

indicate that changes have be<strong>en</strong> made but not saved.<br />

To check the Enumeration and the Global Variables for any possible typing errors go to the<br />

‘Project’ m<strong>en</strong>u, and select ‘Rebuild All’<br />

If you have any errors, they should be fixed before moving on.<br />

As an example I have removed the semicolon from the <strong>en</strong>d of one of the Global Variable<br />

declarations.<br />

Wh<strong>en</strong> preforming a ‘Rebuild All’ this g<strong>en</strong>erates 2 errors, which can be se<strong>en</strong> in the ‘Message<br />

Window’<br />

146


Chapter: PLC Programming “The Inspection Conveyor”<br />

Place your mouse at the top of the ‘Message Window’<br />

Click and Drag the bar upwards to see more of the ‘Message Window’<br />

It is best to start with the first error in the list, many times one problem will create others<br />

for the compiler.<br />

The easiest way to find the first error in the list is to press the ‘F4’ key. Repeatedly pressing<br />

‘F4’ will go to the next error in the list. You could also scroll through the error list and<br />

Double-Click on the error.<br />

147


Chapter: PLC Programming “The Inspection Conveyor”<br />

Wh<strong>en</strong> the error is selected, the location of the error will be shown, and the line of code that<br />

has the problem will be highlighted. Repeatedly pressing ‘F4’ will go to the next error in the<br />

list.<br />

The full error message states that the complier is ‘Expecting the <strong>en</strong>d of line character or an<br />

assignm<strong>en</strong>t before seeing a new variable name. To the compiler the problem occurred on<br />

line 9, the appropriate way to fix the problem is to find the variable declared before line 9<br />

and place the semicolon at the <strong>en</strong>d of the line.<br />

After fixing any errors you may have had, preform another ‘Rebuild All’ from the ‘Project’<br />

m<strong>en</strong>u.<br />

Once, you have zero errors, you will get 7 warnings. G<strong>en</strong>erally speaking warnings can be<br />

ignored. These 7 warnings are created by the use of %I* and %Q* variables. The warning<br />

simply states that the VAR_CONFIG file has not be<strong>en</strong> created for these variables. ‘F4’ will<br />

scroll through the warnings. Ignore them for now and continue on.<br />

Now would be a good time to ‘Save’ your project.<br />

148


Chapter: PLC Programming “The Inspection Conveyor”<br />

Finally, it is time to write some code. Click on the POUs tab at the bottom of the left column.<br />

149


Chapter: PLC Programming “The Inspection Conveyor”<br />

Double-Click on the MAIN program.<br />

Note: You may or may not have the small blue arrow next to the icon for MAIN. This blue<br />

arrow simply indicates that changes have be<strong>en</strong> made to this POU that have not be<strong>en</strong><br />

downloaded into the running PLC.<br />

In the local declaration section of MAIN define a variable called eStep as of type<br />

E_MachineState<br />

The best way to do this is to first type in the new variable name eStep, th<strong>en</strong> place a colon<br />

after it, th<strong>en</strong> press the F2 key which op<strong>en</strong>s the Input assistant.<br />

150


Chapter: PLC Programming “The Inspection Conveyor”<br />

Select ‘User defined Types’ from the left column and th<strong>en</strong> E_MachineState, press ‘OK’<br />

This will bring you back to the declaration section; place a semicolon at the <strong>en</strong>d of the line.<br />

By declaring eStep to be of type E_MachineState the value of the variable eStep will be the<br />

text in the Enumeration. eStep will be used as the condition variable of the CASE statem<strong>en</strong>t<br />

that will control the State Machine.<br />

151


Chapter: PLC Programming “The Inspection Conveyor”<br />

The g<strong>en</strong>eral layout of a CASE statem<strong>en</strong>t is as follows:<br />

The variable betwe<strong>en</strong> CASE and OF must use an integer value (INT,DINT,SINT,USINT).<br />

Enumerations hold an integer value.<br />

The numbers that follow on the next lines repres<strong>en</strong>t the possible values of that variable.<br />

Therefore wh<strong>en</strong> iStep is equal to 0 the code betwe<strong>en</strong> 0 and the next number will be run.<br />

The code following all other numbers will not be run. For example if iStep is equal to 10 th<strong>en</strong><br />

the code on lines 5 and 6 would be run the next line of code would be line 12, or the first<br />

line after the END_CASE command.<br />

The ELSE case is a safeguard, if iStep is ever set to a value that is not defined the code in the<br />

ELSE command will be run.<br />

The values of the condition variable are limited to integer values. In the above picture,<br />

values are skipped to allow for the possibility to easily add steps in betwe<strong>en</strong>. It is g<strong>en</strong>erally a<br />

good practice to do this, otherwise wh<strong>en</strong> a step has to be added th<strong>en</strong> all following steps<br />

must be changed.<br />

The value of iStep is set by conditions in the PLC code. The value can be changed from<br />

within the CASE statem<strong>en</strong>t or from outside the CASE statem<strong>en</strong>t.<br />

For our project the Enumeration is declared as having 4 possible values, therefore the need<br />

for skipping numbers is not necessary. However the ELSE command should always be<br />

included.<br />

152


Chapter: PLC Programming “The Inspection Conveyor”<br />

Note: wh<strong>en</strong> using an Enumeration both of the above are valid; however, the use of the<br />

variable name from within the Enumeration makes the code easier to read.<br />

By default wh<strong>en</strong> the PLC starts all values are 0, unless giv<strong>en</strong> an initial value. To <strong>en</strong>sure that<br />

our state machine starts at zero, an initial value will be placed on the variable eStep.<br />

To do this, double-click on the variable eStep in the declaration section of MAIN. This will<br />

highlight the variable name<br />

153


Chapter: PLC Programming “The Inspection Conveyor”<br />

Press and hold the ‘Shift’ key th<strong>en</strong> press ‘F2’. The ‘Declare Variable’ window will op<strong>en</strong><br />

Place a zero in the ‘Initial Value’ box, and click ‘OK’<br />

The declaration of eStep now has an initial value of 0.<br />

The first thing we will setup is the control of the value of eStep.<br />

We have a Selector Switch for <strong>Manual</strong> or Auto and a pushbutton for Maint<strong>en</strong>ance.<br />

With the initial value of eStep being 0 the case statem<strong>en</strong>t will be in E_Undefined. Inside this<br />

step we will set eStep to go to E_<strong>Manual</strong>.<br />

154


Chapter: PLC Programming “The Inspection Conveyor”<br />

However, we should also look at the condition of the Selector Switch. The input is negated<br />

with the NOT command because the switch being in the ON position is for Auto.<br />

Remember to use ‘F2’ for the Input Assistant to select gati_xMan_Auto_ss from the Global<br />

Variables<br />

155


Chapter: PLC Programming “The Inspection Conveyor”<br />

We now are able to put the machine into <strong>Manual</strong> Operation. From <strong>Manual</strong>, there needs to<br />

be a way to go into either Maint<strong>en</strong>ance or Auto.<br />

Now would be a good time to ‘Save’ your project.<br />

It would also be a good time to check for errors. Go to the ‘Project’ M<strong>en</strong>u and select<br />

‘Rebuild All’<br />

You should get one error. Press ‘F4’ to go to the error.<br />

156


Chapter: PLC Programming “The Inspection Conveyor”<br />

Each value for the CASE statem<strong>en</strong>t must have some code in it. Wh<strong>en</strong> the complier sees two<br />

values for eStep with no code in betwe<strong>en</strong> them it causes an error. The easy way to avoid this<br />

is to place a semicolon after the colon. It should be removed later, but if you forget it won’t<br />

hurt anything.<br />

You will also need to do this after E_Auto and ELSE<br />

If you have any other errors, please address them before moving on.<br />

157


Chapter: PLC Programming “The Inspection Conveyor”<br />

As the programmer it is your duty to <strong>en</strong>sure that all possible conditions are accounted for.<br />

Curr<strong>en</strong>tly it is possible to get into the Auto state but it is not possible to get out of it.<br />

The selector switch will place the machine into the <strong>Manual</strong> state.<br />

This is the same code that was used to go from E_Undefined to E_<strong>Manual</strong>.<br />

From the Maint<strong>en</strong>ance mode, pressing the Maint<strong>en</strong>ance push button will place the machine<br />

back into <strong>Manual</strong>.<br />

In the ELSE command eStep will be set to E_Undefined.<br />

158


Chapter: PLC Programming “The Inspection Conveyor”<br />

The <strong>en</strong>tire body of MAIN, now looks like the following<br />

Now would be a good time to check for errors using ‘Rebuild All’ from the ‘Project’ m<strong>en</strong>u,<br />

and save your project.<br />

At this point the control for the state machine is finished. Later in the section on ‘Fault<br />

Handling’ we will add to the state machine for what needs to be done wh<strong>en</strong> a fault occurs.<br />

The plan is to have a function block for each conveyor module. Each function block will be<br />

capable of controlling the conveyor module in each possible machine state. Therefore the<br />

machine state will be passed into the function block. Before creating the function blocks, we<br />

will create the code that is going to call the function blocks.<br />

159


Chapter: PLC Programming “The Inspection Conveyor”<br />

In the ‘POU’ column right click and select ‘Add Object’.<br />

Name the POU ‘P_MachineControl’. Leave the Type as a Program and set the Language to<br />

‘ST’ for Structured Text. Th<strong>en</strong> click on ‘OK’<br />

160


Chapter: PLC Programming “The Inspection Conveyor”<br />

Before writing any code in the new program we should call the program from ‘MAIN’.<br />

Double-click on ‘MAIN’ to op<strong>en</strong> it. Below the code for the CASE statem<strong>en</strong>t, place the cursor<br />

and press ‘F2’.<br />

In the ‘Input Assistant’ select ‘User defined Programs’ from the column on the left, select<br />

‘P_MachineControl’ from the window on the right, th<strong>en</strong> press ‘OK’.<br />

This will call the new program every PLC scan. The op<strong>en</strong> and close par<strong>en</strong>thesis are not<br />

required but should be used to indicate that it is a POU call.<br />

161


Chapter: PLC Programming “The Inspection Conveyor”<br />

Now double-click on ‘P_MachineControl’ in the ‘POU’ column. Later we will add code to this<br />

program for calling the Function Blocks that will control the machine. For now add a<br />

semicolon to prev<strong>en</strong>t any build errors.<br />

Next, add another program by right-clicking in the POU column and selecting ‘Add Object’<br />

Name the new Program ‘P_MachineMonitoring’<br />

In the Machine Monitoring program we will add some function blocks from a couple of<br />

libraries, to monitor things going on in the background.<br />

162


Chapter: PLC Programming “The Inspection Conveyor”<br />

First we will add the new library. From the ‘Window’ m<strong>en</strong>u, select ‘Library Manager’.<br />

The STANDARD.Lib is always included in every project by default. The Standard library<br />

contains timers, counters, triggers, and other basic function blocks.<br />

163


Chapter: PLC Programming “The Inspection Conveyor”<br />

Under the ‘STANDARD.Lib’ right click and select ‘Additional Library’.<br />

The ‘Op<strong>en</strong>’ dialog box will op<strong>en</strong> to the default location of C:\<strong>TwinCAT</strong>\PLC\Lib<br />

In this folder are all of the libraries that are included with the level of <strong>TwinCAT</strong> that you<br />

installed.<br />

164


Chapter: PLC Programming “The Inspection Conveyor”<br />

Add the ‘TcUtilities.lib’ by either scrolling to the right or typing the name into the ‘File<br />

name:’ box, if you choose to type in the name, you will notice that windows filters the<br />

results of possible options as you type.<br />

After selecting ‘TcUtilities.lib’ press the ‘Op<strong>en</strong>’ button.<br />

TcUtilities requires the use of TcBase and TcSystem, therefore these libraries are included as<br />

well.<br />

165


Chapter: PLC Programming “The Inspection Conveyor”<br />

Select TcUtilities in the list of libraries.<br />

Notice that libraries can contain POUs, Data Types, Visualizations, and Global Variables. In<br />

the POU column of the TcUtilities library expand the ‘<strong>TwinCAT</strong> System’ folder and select<br />

TC_CpuUsage. This will display a picture of the Function Block as it would appear in the FBD<br />

language; it also displays part of the local variable declaration section for the Function Block.<br />

If the ‘Beckhoff Information System’ is installed on your computer th<strong>en</strong> it is possible to<br />

highlight the name of the Function Block and press ‘F1’ to view the docum<strong>en</strong>tation for the<br />

Function Block.<br />

166


Chapter: PLC Programming “The Inspection Conveyor”<br />

The Tc_CpuUsage Function Block will monitor the perc<strong>en</strong>tage of the CPU that <strong>TwinCAT</strong> is<br />

using.<br />

In the POU column double click on ‘P_MachineMonitoring’.<br />

Now place the cursor on line 0001 in the code window and press ‘F2’ to op<strong>en</strong> the ‘Input<br />

Assistant’<br />

167


Chapter: PLC Programming “The Inspection Conveyor”<br />

From the ‘Input Assistant’ select ‘Standard Function Blocks’ from the left column and th<strong>en</strong><br />

expand TcUtilities in the window on the right.<br />

Scroll down to ‘<strong>TwinCAT</strong> System’ and expand that folder<br />

168


Chapter: PLC Programming “The Inspection Conveyor”<br />

Select ‘Tc_CpuUsage’ and click ‘OK’.<br />

This will add a g<strong>en</strong>eric version of the Function Block to the code.<br />

169


Chapter: PLC Programming “The Inspection Conveyor”<br />

The name on line 1 is the ‘Implem<strong>en</strong>tation’ name of the Function Block’, everything<br />

betwe<strong>en</strong> the op<strong>en</strong> and close par<strong>en</strong>thesis are variables that are defined inside of the<br />

Function Block. Wh<strong>en</strong> using large function blocks in Structured Text the variables are each<br />

placed on their own line to make them easier to view. Each variable is followed by either an<br />

input or output symbol and th<strong>en</strong> a comma. The assignm<strong>en</strong>t statem<strong>en</strong>t := is used to indicate<br />

that the variable is of type VAR_INPUT, the output assignm<strong>en</strong>t => is used to indicate that the<br />

variable is of type VAR_OUTPUT.<br />

Each use of a Function Block will receive its own memory space; therefore, each Function<br />

Block must be giv<strong>en</strong> a unique instance name.<br />

Add ‘fb’ to the beginning of the implem<strong>en</strong>tation name TC_CpuUsage.<br />

Wh<strong>en</strong> you click on any line other than line 1 the ‘Declare Variable’ window will appear.<br />

The ‘Class’ drop down list will allow for the selection of where the variable is to be declared,<br />

leave this on VAR to declare it in the local variable declaration section.<br />

170


Chapter: PLC Programming “The Inspection Conveyor”<br />

Change the ‘Type’ from BOOL to TC_CpuUsage, this can be done by either typing in the type<br />

or pressing the ‘Ellipse’ button.<br />

Wh<strong>en</strong> you press the ‘Ellipse’ button the ‘Input Assistant’ will op<strong>en</strong> and allow you to select<br />

the type from the list.<br />

Select ‘Standard Function Blocks’ from the column on the left, th<strong>en</strong> expand ‘TcUtilites’, th<strong>en</strong><br />

‘<strong>TwinCAT</strong> System’, finally select TC_CpuUsage and click ‘OK’.<br />

171


Chapter: PLC Programming “The Inspection Conveyor”<br />

The ‘Declare Variable” window should look like the following.<br />

Press ‘OK’, and notice that the instance of the Function Block has be<strong>en</strong> declared in the local<br />

variable section.<br />

Next the variables to be passed into the Function Block need to be added.<br />

The ‘NETID’ is the AMSNETID of the <strong>TwinCAT</strong> Run-Time that is to be read. According to the<br />

Docum<strong>en</strong>tation the variable type is ‘T_AmsNetID’, which is of type string with a l<strong>en</strong>gth of 23<br />

bytes.<br />

172


Chapter: PLC Programming “The Inspection Conveyor”<br />

In this example we are going to read the local CPU Usage, therefore the local AmsNetID can<br />

be provided. Click on your <strong>TwinCAT</strong> Icon in the windows system tray, the select ‘Properties’.<br />

Select the ‘AMS Router’ tab<br />

The AMS Net ID can be copied from here.<br />

173


Chapter: PLC Programming “The Inspection Conveyor”<br />

In the code place an empty string after the assignm<strong>en</strong>t statem<strong>en</strong>t of NETID, th<strong>en</strong> paste the<br />

AMS Net ID in betwe<strong>en</strong> the quotes.<br />

Wh<strong>en</strong> using the local AMS Net ID it is also possible to just use an empty string ‘’, internally<br />

the Function Block will read the local AMS Net ID in this case.<br />

Wh<strong>en</strong> the ‘START’ input variable rises from False to True, internally the Function Block will<br />

execute an ADSREAD one time. Each rising edge that is se<strong>en</strong> on the ‘START’ input will cause<br />

another read of the CPU usage. For now add the variable ‘xReadCpuUsage’ to the ‘START’<br />

input.<br />

174


Chapter: PLC Programming “The Inspection Conveyor”<br />

Wh<strong>en</strong> you click away from line 3 the ‘Declare Variable’ window will appear. Leave it defined<br />

as a Local variable and a BOOL.<br />

The ‘TMOUT’ variable is the amount of time to wait for a response, before throwing a<br />

TimeOut error. If the input is left empty the default time of 5 seconds will be used. Time<br />

values always start with T# and must <strong>en</strong>d with time unit being used. Place a time value of<br />

500 milliseconds in the ‘TMOUT’ variable.<br />

We will now create local variables that the Function Block will write to.<br />

175


Chapter: PLC Programming “The Inspection Conveyor”<br />

Use the following variable names for the outputs and declare them as shown below.<br />

Now would be a good time to compile the code and check for errors, by selecting ‘Rebuild<br />

all’ from the ‘Project’ m<strong>en</strong>u. Wh<strong>en</strong> there are no errors, save your project.<br />

A commonly used Function Block is NT_GetTime. This Function Block will read the Windows<br />

Clock each time the ‘START’ input is triggered. The time value can th<strong>en</strong> be added to log<br />

information.<br />

176


Chapter: PLC Programming “The Inspection Conveyor”<br />

Place the cursor on line 11 and press ‘F2’.<br />

Select ‘Standard Function Blocks’ from the left column, expand the ‘NT, W2K, XP, XPe, CE<br />

Operating System’ folder.<br />

177


Chapter: PLC Programming “The Inspection Conveyor”<br />

Select the NT_GetTime Function Block and press ‘OK’<br />

The g<strong>en</strong>eric Function Block has now be<strong>en</strong> added to the code.<br />

178


Chapter: PLC Programming “The Inspection Conveyor”<br />

Change the name to fbNT_GetTime.<br />

Click away from line 11 and declare the Function Block as a type NT_GetTime.<br />

Set the NETID to local by using an empty string. (Two single quotes, with no space betwe<strong>en</strong><br />

them.<br />

179


Chapter: PLC Programming “The Inspection Conveyor”<br />

Set the ‘START’ variable to xGetTimeStart and declare it as ‘Type’ BOOL.<br />

Set the ‘TMOUT’ to 500ms.<br />

Set the output variables and declare them as they are below.<br />

The local declaration section should have the following<br />

Notice that ‘stGetTimeValue’ is of Type ‘TIMESTRUCT’. This structure is defined inside of the<br />

TcUtilities library, and contains the following information.<br />

180


Chapter: PLC Programming “The Inspection Conveyor”<br />

wYear : Specifies the year: 1970 ~ 2106;<br />

wMonth : Specifies the month: 1 ~ 12 (January = 1, February = 2 and so on);<br />

wDayOfWeek : Specifies the day of the week: 0 ~ 6 (Sunday = 0, Monday = 1 and so on );<br />

wDay : Specifies the day of the month: 1 ~ 31;<br />

wHour : Specifies the hour: 0 ~ 23;<br />

wMinute : Specifies the minute: 0 ~ 59;<br />

wSecond : Specifies the second: 0 ~ 59;<br />

wMilliseconds : Specifies the millisecond: 0 ~ 999;<br />

The out ‘stGetTimeValue’ will hold values similar to the following.<br />

The previous two Function Blocks were provided by Beckhoff. It is also possible to create<br />

your own. In order to get regular updates of the CPU Usage the ‘START’ input of the<br />

TC_CpuUsage Function Block needs to toggle betwe<strong>en</strong> TRUE and FALSE repeatedly. To do<br />

this we will create a Function Block that pulses its output at a regular interval.<br />

From the POU column right-click and select ‘Add Object’<br />

181


Chapter: PLC Programming “The Inspection Conveyor”<br />

In the ‘New POU’ window, name the POU ‘FB_Pulse’. The Type of POU should be ‘Function<br />

Block’. The language will be ‘ST’ for structured text. Click ‘OK’ to create the Function Block.<br />

At the top of the declaration section you will see on line 1 that this is a Function Block not a<br />

Program or Function, the name of the Function Block is also included on this line. Following<br />

line 1 is the VAR_INPUT, VAR_OUTPUT, and VAR sections. In the VAR_INPUT section<br />

variables will be declared that have values passed into them from the calling code, the<br />

VAR_OUPUT section will declare variables that have their values passed out to the calling<br />

code. The VAR section will declare values that are only used internally within the Function<br />

Block.<br />

182


Chapter: PLC Programming “The Inspection Conveyor”<br />

In the VAR_INPUT section declare the following variables<br />

i_xEnable :BOOL;<br />

i_tTimeOn : TIME;<br />

i_tTimeOff : TIME;<br />

(*Wh<strong>en</strong> TRUE the Function Block is Running, Wh<strong>en</strong> FALSE the<br />

Function Block is stopped all values a reset and the outputs are<br />

FALSE*)<br />

(*L<strong>en</strong>gth of TIME for the Output to be TRUE*)<br />

(*L<strong>en</strong>gth of TIME for the Output to be FALSE*)<br />

In the VAR_OUTPUT section declare the following variable<br />

q_xPulse : BOOL;<br />

In the VAR section declare the following variables<br />

These are the two timers that will be used to control the output. They are in the STANDARD<br />

library.<br />

183


Chapter: PLC Programming “The Inspection Conveyor”<br />

In the code, window use ‘F2’ to place the two timers in the Function Block.<br />

184


Chapter: PLC Programming “The Inspection Conveyor”<br />

Now change the name of the TON and TOF to match the declaration section.<br />

The TON will start wh<strong>en</strong> the i_xEnable input is TRUE and the TOF output is FALSE.<br />

The i_xEnable variable can be added by placing the cursor betwe<strong>en</strong> the := and the ,<br />

185


Chapter: PLC Programming “The Inspection Conveyor”<br />

Th<strong>en</strong> press ‘F2’, in the left column of the Input Assistant select ‘Local Variables’, th<strong>en</strong> select<br />

i_xEnable from the right window.<br />

Next, add the code to monitor the output of fbTOF<br />

If you type in the code, notice that once you have added the dot ( . ) after fbTOF a drop list<br />

will appear that contains all of the variables declared inside of the TOF.<br />

Red icons indicate VAR_OUTPUT, Yellow icons are for VAR_INPUT, and Purple icons are for<br />

VAR.<br />

186


Chapter: PLC Programming “The Inspection Conveyor”<br />

Wh<strong>en</strong> the drop down list appears you can either continue typing to filter the list or use the<br />

arrow keys to move the cursor up and down. If you use the arrow keys, both the ENTER key<br />

and the space bar will select the variable and add it to the code.<br />

You code should now look like the following<br />

Next, add the TIME variable to PT:=<br />

Note: this is the tTimeOff variable<br />

Again, use ‘F2’ and select the variable from the ‘Local Variable’ list.<br />

The input for fbTOF will be the output of fbTON<br />

This time to add the i_tTimeOn variable do not use the ‘F2’ key, instead place the cursor<br />

after the := and before thecomma ( , )<br />

Now press the dot ( . ) key<br />

This list includes every variable in the project, including libraries. If you know the beginning<br />

of the variable name this can be an easy way to access it and still guarantee that typos are<br />

not made. After pressing the . press the ‘i’ key.<br />

187


Chapter: PLC Programming “The Inspection Conveyor”<br />

Pressing the down arrow will show the next variable in the list, which is the one we want to<br />

use.<br />

Also notice that if you hover the mouse over the variable name in the list, that the comm<strong>en</strong>t<br />

from the declaration section appears as a tool tip.<br />

With i_tTimeOn highlighted, press the ‘Enter’ key.<br />

Next add the output q_xPulse to the Q output of the fbTOF<br />

If you use the . and select the variable from the list, wh<strong>en</strong> selecting an output the . is not<br />

removed as it was on the input variable, the . must be removed or the compiler will throw<br />

an error.<br />

188


Chapter: PLC Programming “The Inspection Conveyor”<br />

Note: The following code would provide the exact same result<br />

Now would be a good time to compile the code by selecting ‘Rebuild all’ from the ‘Project’<br />

M<strong>en</strong>u and th<strong>en</strong> save the file.<br />

Wh<strong>en</strong> viewing code online that was writt<strong>en</strong> in Structured Text the code window is split, the<br />

left side shows the code as it appears offline, the right side show each variable and its value.<br />

Using the above as an example i_xEnable, fbTOF.Q, and i_tTimeOff will all be listed on the<br />

same line<br />

In order to make the code easier to read it is possible to place each variable on its own line.<br />

The common practice is to place the instance name of the Function Block and the op<strong>en</strong><br />

par<strong>en</strong>theses on the first line, th<strong>en</strong> on each following line place one variable leaving the<br />

comma at the <strong>en</strong>d of the line. The easiest way to do this, is place the cursor after each<br />

comma and press the ‘Enter’ key, resulting in the following<br />

Using the ‘TAB’ key to ind<strong>en</strong>t the lines of code that are part of the Function Block helps in<br />

reading the code, this allows the person viewing the code to easily see the beginning of each<br />

Function Block.<br />

The width of the displayed variables in the right window can be adjusted by single clicking<br />

on the variable and th<strong>en</strong> grabbing the right edge of the box click and drag to adjust the size.<br />

189


Chapter: PLC Programming “The Inspection Conveyor”<br />

It is also possible to select ‘Monitoring Options’ from the ‘Extras’ m<strong>en</strong>u, th<strong>en</strong> set the<br />

‘Distance of two variables value.<br />

190


Chapter: PLC Programming “The Inspection Conveyor”<br />

A pulsing output can be used for many differ<strong>en</strong>t things, flashing stack lights or other<br />

indicator lights, or triggering a function block to start repeatedly.<br />

We will now add the new Function Block to the Machine Monitoring code and use the<br />

pulsing output to trigger the TC_CpuUsage Function Block.<br />

In the POU column double-click on P_MachineMonitoring.<br />

Place the cursor on line 20 and press ‘F2’. From the ‘Input Assistant’ select ‘User defined<br />

Function Blocks’ from the left column and the ‘FB_Pulse’ from the window on the right.<br />

Th<strong>en</strong> press ‘OK’<br />

This will add the g<strong>en</strong>eric code for the Function Block to the program.<br />

191


Chapter: PLC Programming “The Inspection Conveyor”<br />

Replace the name FB_Pulse with a specific instance name of fbPulseCpuUsage.<br />

After clicking away from line 20 the ‘Declare Variable’ Window will appear. Change the<br />

‘Type’ to FB_Pulse by either typing it in or using the ‘Ellipse’ button and selecting it from the<br />

list of ‘User defined Function Blocks’. Click ‘OK’<br />

The declaration section should now contain the following<br />

Before assigning variable name to the inputs and outputs format the code for easier<br />

reading.<br />

Add the following values to the inputs of the Function Block.<br />

192


Chapter: PLC Programming “The Inspection Conveyor”<br />

For the output use the variable that was used on the TC_CpuUsage ‘START’ input.<br />

Now wh<strong>en</strong> the code is running the output will toggle on and off at a rate of 1 second. By<br />

writing to xReadCpuUsage the fbTC_CpuUsage ‘START’ input will toggle and read the CPU<br />

Usage every other second.<br />

Creating logging information can be done in several ways. There is a File Read and Write<br />

Function Block in the TcSystem library for interacting with a text file, there is also Database<br />

and XML supplem<strong>en</strong>ts for working with those file types. Beckhoff also provides the<br />

possibility to write logging information to the Windows Application Log. Using the<br />

ADSLOGSTR Function it is possible to write custom string values from the PLC into the<br />

Windows Application Log.<br />

For this example we will create a log message every time the Machine State changes based<br />

on the value of E_MachineState.<br />

We will be creating a Function Block to monitor the variable eStep which holds the curr<strong>en</strong>t<br />

value of the State Machine. Wh<strong>en</strong> the value changes the code needs to create the message<br />

to be logged, and th<strong>en</strong> log that message.<br />

Start by adding a new Function and name it FB_LogStateMachine<br />

193


Chapter: PLC Programming “The Inspection Conveyor”<br />

Declare the following in the local variable declaration section<br />

i_eState will be the curr<strong>en</strong>t value of the State Machine control by the ‘MAIN’ POU<br />

q_udiErrID will be the output result of the ADSLOGSTR Function<br />

ePreviousState will be updated at the <strong>en</strong>d of the code and hold the value of i_eState from<br />

the previous PLC scan<br />

fbRT_StateChange is a Rising Trigger, the R_TRIG Function Block monitors its CLK input and<br />

wh<strong>en</strong> it changes from FALSE to TRUE the Q output will be on for one PLC scan<br />

sStateLog will be the STRING repres<strong>en</strong>tation of the State Machine<br />

194


Chapter: PLC Programming “The Inspection Conveyor”<br />

Add the below code to the Function Block.<br />

Note: The Function on Line 8 (F_StateMachineLookup) does not yet exist. Wh<strong>en</strong> the ‘Declare<br />

Variable’ window appears press the ‘Cancel’ button.<br />

The ‘IF’ statem<strong>en</strong>t on line 1 uses the not equal to operator to compare the previous state<br />

to the curr<strong>en</strong>t state<br />

If they are not equal th<strong>en</strong> the CLK input of the Rising Trigger is set to true (Line 2), else it is<br />

set to false (Line 4).<br />

Note: Any time a variable is set to TRUE inside an ‘IF’ statem<strong>en</strong>t, code must be added to set<br />

that variable to FALSE. Wh<strong>en</strong> using a Rising Trigger Function Block the input must see the<br />

transition from FALSE to TRUE, if lines 3 and 4 were not included the Function Block would<br />

only work once.<br />

This code could also be done by using the following instead of lines 1 through 5<br />

The ‘IF’ statem<strong>en</strong>t on line 7 monitors the Q output of the Rising Trigger. Wh<strong>en</strong> the output is<br />

TRUE lines 8 through 14 will be executed and wh<strong>en</strong> the Q output is false line 16 will be<br />

executed.<br />

Line 8 passes the value of i_eState into the F_StateMachineLookup Function.<br />

Lines 10 calls the ADSLOGSTR Function in the TcSystem library.<br />

195


Chapter: PLC Programming “The Inspection Conveyor”<br />

Calling a Function is differ<strong>en</strong>t from calling a Function Block. A Function Block requires an<br />

instance name and is assigned its own memory space. A Function does not have an instance<br />

name and does not have its own space in memory. Functions do not retain any values from<br />

one PLC scan to the next. For Example a Timer or Counter must be a Function Block and not<br />

a Function. Additionally Functions only return a single result. The most basic Functions are<br />

the Math Operators: ADD, SUBTRACT, MULTIPLY, DIVIDE, etc. each of these are a function<br />

and return a single result.<br />

Wh<strong>en</strong> calling a function the result of that function must be stored into another variable, for<br />

example adding two numbers together would be done in the following manner<br />

The + sign repres<strong>en</strong>ts the ADD Function<br />

Functions that are not common Math Functions are called in a differ<strong>en</strong>t manner.<br />

The following line of code does not compile however for the sake of explanation let us<br />

assume that it would.<br />

The variable ‘a’ is assigned a value of<br />

Call the ADD function and pass in the value of the variables b and c<br />

The single result of the ADD Function will be stored in the variable a<br />

The ADSLOGSTR Function returns a UDINT (Unsigned Double Integer)<br />

ADSLOGSTR has three inputs<br />

msgCtrlMask : DWORD;<br />

msgFmtStr : T_MaxString;<br />

strArg : T_MaxString;<br />

196


Chapter: PLC Programming “The Inspection Conveyor”<br />

msgCtrlMask is used to define the parameters of the logged ev<strong>en</strong>t<br />

HINT , WARN , and ERROR are the type of Message<br />

LOG will write the message to the Windows Application Log<br />

MSGBOX will display a pop up box that shows the message<br />

msgFmtStr is a string that contains the text of the message and <strong>en</strong>ds with %s<br />

Note: the text in the sample code and the %s are inside of single quotes<br />

strArg is also a string, the value that is passed into the Function will replace the %s in<br />

msgFmtStr<br />

The code sets the Control Mask to Hint and Log<br />

197


Chapter: PLC Programming “The Inspection Conveyor”<br />

The message in the log will be Machine State Changed to: Auto if sStateLog has<br />

a value of Auto<br />

Note: The ADSLOGSTR should always be called conditionally using a Rising Trigger Function<br />

Block; otherwise it will create a log message every PLC scan.<br />

q_udiErrID will hold the value of the result of the ADSLOGSTR Function, these values are<br />

ADS Return Codes, any value other than 0 is an error.<br />

Line 19 copies the value of i_eState into ePreviousState so that on the next PLC scan the two<br />

values can be compared and a change can be detected.<br />

198


Chapter: PLC Programming “The Inspection Conveyor”<br />

Now would be a good time to ‘Rebuild’ the code and save the file. However the call to<br />

F_StateMachineLookup is going to throw an error. To prev<strong>en</strong>t this and check the code place<br />

comm<strong>en</strong>t markers around the code on Line 8<br />

Now, ‘Rebuild all’ and save the project.<br />

Let’s now add the code for F_StateMachineLookup.<br />

The Purpose of this Function will be to pass in the curr<strong>en</strong>t value of the machine state and<br />

th<strong>en</strong> convert that to a string value.<br />

Right-Click in the POU column and select ‘Add Object’<br />

199


Chapter: PLC Programming “The Inspection Conveyor”<br />

Define the Function as below.<br />

In the declaration section add the Input Variable<br />

Note: Because Functions only have one output there is no VAR_OUTPUT section. The Name<br />

of the Function is the output variable, and its type is defined on line 1 of the declaration<br />

section. If you forget to change the type in the ‘New POU’ window, it can be changed on<br />

line 1.<br />

The Input Variable eState holds the STRING repres<strong>en</strong>tation of the Enumeration. This<br />

Function will convert this value to an actual STRING that can be passed into the ADSLOGSTR<br />

Function.<br />

There are several ways to do this, the most common way would be to create nested IF<br />

statem<strong>en</strong>ts as below.<br />

200


Chapter: PLC Programming “The Inspection Conveyor”<br />

Using nested IF statem<strong>en</strong>ts in this manner will allow for the code to jump to the END_IF<br />

after the correct value of eState has be<strong>en</strong> found and its code has be<strong>en</strong> run.<br />

Let us assume that eState has a value of 2, repres<strong>en</strong>ting ‘<strong>Manual</strong>’.<br />

On line 1 eState will be compared to 0, this will return FALSE and the code will th<strong>en</strong> go to<br />

line 4.<br />

On line 4 eState will be compared to 1, this will return FALSE and the code will th<strong>en</strong> go to<br />

line 7.<br />

On line 7 eState will be compared to 2, this will return TRUE and the code will continue to<br />

line 8.<br />

On line 8 the output variable F_StateMachineLookup will be set to a value of ‘<strong>Manual</strong>’.<br />

Line 9 is empty<br />

Line 10 is another ELSIF, because line 7 return a TRUE the code is now looking for the<br />

END_IF statem<strong>en</strong>t and will skip all lines until it is found.<br />

On line 13 the END_IF statem<strong>en</strong>t is found<br />

The code will continue to run until the <strong>en</strong>d of the Function and th<strong>en</strong> return to the calling<br />

code and write the value of F_StateMachineLookup in the variable sStateLog<br />

The above code will work as needed however there is a more effici<strong>en</strong>t way to do this.<br />

201


Chapter: PLC Programming “The Inspection Conveyor”<br />

The use of a CASE statem<strong>en</strong>t will allow for only the minimum amount of code to be run.<br />

The traditional use of a case statem<strong>en</strong>t would not work correctly inside of a function.<br />

Remember that a Function does not hold any data from one PLC scan to the next, and a<br />

CASE statem<strong>en</strong>t takes one PLC scan to change to the next step.<br />

Ev<strong>en</strong> in this very simple example it would be on the 4 th PLC scan that iStep would have a<br />

value of 3.<br />

This code would never work inside of a Function.<br />

However if the variable to be evaluated is the variable that is passed into the Function as a<br />

VAR_INPUT th<strong>en</strong> the one step that is equal to the value of the variable that was passed in,<br />

that one step will run.<br />

In the below code eState is passed into the Function<br />

eState is th<strong>en</strong> evaluated by the CASE statem<strong>en</strong>t to determine which part of the CASE<br />

statem<strong>en</strong>t to run<br />

202


Chapter: PLC Programming “The Inspection Conveyor”<br />

Wh<strong>en</strong> the Function is called and eState has a value of 2<br />

Line 1 will evaluate the value of eState and determine that it is 2<br />

The code will th<strong>en</strong> go to line 7 where it finds 2: and th<strong>en</strong> run the code until it finds the next<br />

number that is followed by a : and th<strong>en</strong> jump the END_CASE on line 12.<br />

By using a CASE statem<strong>en</strong>t in this way, the amount of code to be processed is less than the<br />

above example of IF and ELSIF statem<strong>en</strong>ts, therefore the amount of CPU usage is reduced.<br />

Place the code for the CASE statem<strong>en</strong>t into the body of the Function<br />

Now would be a good time to ‘Rebuild all’ and ‘Save’ your project.<br />

203


Chapter: PLC Programming “The Inspection Conveyor”<br />

You might notice that F_StateMachineLookup is grayed out in the POU column. This is<br />

because the Function is not being used.<br />

The comm<strong>en</strong>t markers need to be removed from the FB_LogStateMachine.<br />

Do another ‘Rebuild all’ and th<strong>en</strong> ‘Save’.<br />

After the ‘Rebuild all’ F_StateMachineLookup should now be in black<br />

204


Chapter: PLC Programming “The Inspection Conveyor”<br />

At this point we have covered the following:<br />

1. Starting a new project<br />

2. Creating Global Variables with addresses<br />

3. Adding Comm<strong>en</strong>ts to Variable names.<br />

4. Using a CASE statem<strong>en</strong>t to create a state machine<br />

5. How to call a Program from another Program<br />

6. Adding an existing library<br />

7. Using Functions and Function Blocks from a library<br />

8. Creating custom Functions and Function Blocks and the using them.<br />

205


Chapter: PLC Programming “The Inspection Conveyor”<br />

23.Digital I/O<br />

The purpose of this section is to introduce the first mechanical part of the Inspection Conveyor.<br />

We will be adding code to the program that allows the conveyor to be loaded and material to<br />

<strong>en</strong>ter the system. The first conveyor will be manually loaded by an operator and th<strong>en</strong> index the<br />

box along the conveyor. We will start by creating a PROGRAM to control a single conveyor, and<br />

th<strong>en</strong> we will convert this PROGRAM to a FUNCTION BLOCK so that we can create multiple<br />

instances of it.<br />

We will start by adding a call to the P_MachineControl program from MAIN.<br />

Left click at the <strong>en</strong>d of line 33 in MAIN. This will place the cursor on that line. Th<strong>en</strong> press the<br />

‘Enter’ key twice.<br />

The cursor is now on line 35<br />

Press the ‘F2’ key to op<strong>en</strong> the ‘Input Assistant’<br />

In the left column select ‘User Defined Programs’, in the window on the right, select<br />

‘P_MachineControl’. Th<strong>en</strong> press ‘OK’.<br />

206


Chapter: PLC Programming “The Inspection Conveyor”<br />

‘P_MachineControl’ will now be called and scanned after ‘P_MachineMonitoring’.<br />

Double-click on P_MachineControl in the POUs column.<br />

From ‘P_MachineControl’ we will be adding code to call the control program of the conveyor.<br />

Ev<strong>en</strong>tually there will be several specialized conveyors in our conveyor system. For now let us<br />

create the ‘Infeed Conveyor’.<br />

Right-Click in the POUs column and select ‘Add Object’.<br />

207


Chapter: PLC Programming “The Inspection Conveyor”<br />

Create a ‘Program’ and ‘Name’ the ‘POU’ ‘P_InFeedConveyor’.<br />

Double-Click on P_MachineControl and use the ‘F2’ key to call the ‘P_InFeedConveyor’ program<br />

from ‘P_MachineControl’.<br />

In keeping with ‘Top-Down’ programming principles we will add some ‘code’ that is more<br />

descriptive than functional.<br />

To prev<strong>en</strong>t the ‘Declare Variable’ window from popping up we will create all of this as<br />

comm<strong>en</strong>ts<br />

The first comm<strong>en</strong>t will be a g<strong>en</strong>eral overview of what the code in this POU does.<br />

By placing (* at the beginning and *) at the <strong>en</strong>d, all text in betwe<strong>en</strong> is ignored by the compiler.<br />

208


Chapter: PLC Programming “The Inspection Conveyor”<br />

The next thing to do is add comm<strong>en</strong>ts for what we expect to need the program to do. These are<br />

not in any specific order and more might be added later, but this gives us a place to start.<br />

This program will control this conveyor in all modes of operation; Auto, <strong>Manual</strong>, and<br />

Maint<strong>en</strong>ance.<br />

There are several ways to do this, we could set up a selection statem<strong>en</strong>t and write code for what<br />

to do wh<strong>en</strong> in each mode or each command (output) could monitor each mode and decide what<br />

to do.<br />

It is best to only write to an output in one location. If you attempt to control an output from<br />

more than one location th<strong>en</strong> the last one to write to the outputs will determine its final state.<br />

As a simple example let us consider the following:<br />

Wh<strong>en</strong> in Auto a light should flash at 1Hz, wh<strong>en</strong> in <strong>Manual</strong> the same light should flash at 2Hz.<br />

We could try the following:<br />

Note: (eMode = E_<strong>Manual</strong>) in the code will compare the two values and return either a TRUE or<br />

FALSE value.<br />

However, both of these Function Blocks are writing to the same output (bLight) every PLC Scan;<br />

therefore, the Function Block fbPulseAuto always has control of the output.<br />

209


Chapter: PLC Programming “The Inspection Conveyor”<br />

The following ‘IF’ statem<strong>en</strong>t could be used to properly select which Function Block to call<br />

Only one of the two Function Blocks will be called at a time; therefore, only one of them will be<br />

attempting to control the value of bLight.<br />

With only two possibilities (Auto or <strong>Manual</strong>) an ‘IF’ statem<strong>en</strong>t works well; however, a ‘CASE’<br />

statem<strong>en</strong>t is more effici<strong>en</strong>t. The following provides the same functionality as above:<br />

Both of these examples have an inher<strong>en</strong>t issue, however. Because we are writing to the same<br />

output from two differ<strong>en</strong>t Function Blocks wh<strong>en</strong> the transition happ<strong>en</strong>s the value of the output<br />

might not be what we expect.<br />

Let us assume the curr<strong>en</strong>t value of eMode is E_<strong>Manual</strong>, after a period of time eMode changes to<br />

E_Auto. The light has changed from a 1Hz pulse to a 2Hz pulse. However in the code shown<br />

there is nothing to reset the fbPulse<strong>Manual</strong> Function Block, the code just stops calling the<br />

Function Block. The value of all of the variables have be<strong>en</strong> ‘froz<strong>en</strong>’, either the TON or the TOF<br />

was in the process of timing. Internally the TON and TOF Function Blocks do not need to<br />

increm<strong>en</strong>t each PLC scan, they record the start time and compare that to the curr<strong>en</strong>t time to<br />

calculate the elapsed time. Therefore, it is not possible to ‘Pause’ a timer. Wh<strong>en</strong> eMode changes<br />

back to E_<strong>Manual</strong> the elapsed time (ET) will jump. For a light this probably will not cause a<br />

problem; however, if the output is something more critical it could be a serious issue.<br />

210


Chapter: PLC Programming “The Inspection Conveyor”<br />

In order to remove this problem we can use one Function Block to write to the output, but<br />

adjust the time value based on eMode:<br />

In the above example the value of tTime will change based on the value of eMode. The time<br />

value will be loaded into the TON and TOF inside of fbPulseLight on the same PLC scan. If eMode<br />

has a value of E_Auto and the active timer has an ET of greater than 500ms th<strong>en</strong> wh<strong>en</strong> eMode<br />

changes to E_<strong>Manual</strong> that timer will instantly be done and the Q output of the timer will be<br />

TRUE.<br />

In the below example the Pulse Function Block is called and the Enable input is set to FALSE<br />

wh<strong>en</strong> the value of eMode Changes<br />

In this sc<strong>en</strong>ario both the TON and TOF will be restarted wh<strong>en</strong> the value of eMode changes.<br />

With the exception of the first example, all of these samples do the same thing. The differ<strong>en</strong>ce<br />

betwe<strong>en</strong> them is how the output reacts on the PLC scan where the value of eMode changes, it is<br />

ultimately up to the programmer to choose the implem<strong>en</strong>tation that best fits the specific<br />

implem<strong>en</strong>tation.<br />

211


Chapter: PLC Programming “The Inspection Conveyor”<br />

Wh<strong>en</strong> writing a PLC program the above situation can cause many problems for new<br />

programmers. The small changes that can happ<strong>en</strong> in one PLC scan can create unexpected<br />

results that are difficult to detect and troubleshoot. If the output was not controlling a Light, but<br />

instead being used as an input to a Rising Edge or Falling Edge trigger, the R_Trig and F_Trig<br />

Function blocks will see this transition but you may never see it simply by visually looking at the<br />

code. This is where a program like Scope View can be used to detect these short pulses.<br />

If we look at a simple conveyor that has an Entry and Exit Photo Eye (PE), and one Motor Starter,<br />

wh<strong>en</strong> a box is placed on the conveyor, the Entry PE is blocked which causes the Motor Starter to<br />

<strong>en</strong>ergize and the conveyor moves forward. Once, the box has reached the Exit PE the Motor<br />

Starter is de-<strong>en</strong>ergized and the conveyor will stop. I would like to explore some options for how<br />

to write this control code before moving on to our slightly more complex example with a Middle<br />

PE.<br />

The below code uses the EntryPE to start the conveyor and the ExitPE to stop the conveyor, this<br />

would achieve the desired result; however, if both Photo Eyes are blocked, what happ<strong>en</strong>s? In<br />

this case the ExitPE is looked at last and therefore the MotorStarter would be set to FALSE. If the<br />

two ‘IF’ statem<strong>en</strong>ts were reversed and both PEs were blocked, the conveyor would continue to<br />

run.<br />

To fix this problem, and try to optimize the code we could also do the following.<br />

212


Chapter: PLC Programming “The Inspection Conveyor”<br />

This does a couple of things. The ExitPE will have a value of FALSE wh<strong>en</strong> there is not a box<br />

blocking the PE. Therefore anytime a box is pres<strong>en</strong>t at the ExitPE the nested ‘IF’ statem<strong>en</strong>t to<br />

look at the EntryPE will not be executed. This makes the code more CPU fri<strong>en</strong>dly and also<br />

<strong>en</strong>sures that any time the ExitPE is blocked (TRUE) the conveyor will stop.<br />

The last option I want to explain will be the most difficult to understand; however, it will provide<br />

the most flexibility, and as PEs or other conditions are added to the system it will be the easiest<br />

to manage and change. Although as a programmer it is good to optimize your code, remember<br />

that at some point in the future, you or someone else is going to have to read your code. Finding<br />

a balance betwe<strong>en</strong> effici<strong>en</strong>cy and readability is always a difficult task. Normally as effici<strong>en</strong>cy<br />

increases, readability decreases and vice versa.<br />

Truth Tables are used to describe a Boolean function that has multiple inputs and one output.<br />

Our conveyor has two PEs and one Motor Starter. The Truth Table for our conveyor would look<br />

like the following.<br />

Each of the two inputs can only be either TRUE or FALSE. The first line shows them both being<br />

FALSE, the second line shows that the EntryPE is FALSE and the ExitPE is TRUE, the third line<br />

shows the EntryPE is TRUE and the ExitPE is FALSE, the fourth line shows that both inputs are<br />

TRUE. This covers all possible input situations. In the Motor Starter column is the state of the<br />

output that we would like, based on the input conditions. Notice that the only situation where<br />

the Motor Starter will be TURE is wh<strong>en</strong> the Entry PE is true and the ExitPE is FALSE. The numbers<br />

on the far left are decimal numbers starting at 0; notice that the numbers under the Input<br />

conditions are the binary equival<strong>en</strong>t to these decimal numbers.<br />

213


Chapter: PLC Programming “The Inspection Conveyor”<br />

To translate this into code we will start by converting the Boolean inputs and combining them<br />

into an integer number.<br />

Let us assume that iStep is declared in the PLC as an integer. If we th<strong>en</strong> assign the ExitPE to the<br />

first bit of iStep and the EntryPE to the second bit of iStep, iStep will repres<strong>en</strong>t the decimal<br />

equival<strong>en</strong>t of the status, of the two PEs.<br />

We can th<strong>en</strong> control the output based on the value of iStep. iStep has four possible values 0,1,2,<br />

and 3<br />

Wh<strong>en</strong> iStep is 0, 1, or 3 the Motor Starter is False. Wh<strong>en</strong> iStep is 2 the Motor Starter is True.<br />

We can now use a ‘CASE’ statem<strong>en</strong>t to control this:<br />

214


Chapter: PLC Programming “The Inspection Conveyor”<br />

It is also possible to combine the CASES where the code is the same, simply separate the values<br />

with a comma.<br />

Although we are writing to the variable in multiple places, because they are inside of a ‘CASE’<br />

statem<strong>en</strong>t only one of them will be writt<strong>en</strong> to in a giv<strong>en</strong> PLC scan. If the value of iStep was to<br />

change, it will be the next PLC scan before the ‘CASE’ would change.<br />

This also gives us the flexibility to easily add more functionality based on the status of the<br />

inputs. If you wanted to start a timer wh<strong>en</strong> the ExitPE was blocked and the EntryPE was not,<br />

you could simple add that code to ‘CASE’ 1, which would be much easier than trying to add it to<br />

the ‘IF’ statem<strong>en</strong>ts in the first examples.<br />

Adding the MiddlePE to the system will be simple in the ‘CASE’ statem<strong>en</strong>t; however, I would first<br />

like to repeat the first two ‘IF’ statem<strong>en</strong>ts to show why and how this method becomes more<br />

complicated.<br />

The below could be used, but if all three PEs are on th<strong>en</strong> the PLC is writing to the output in two<br />

places, within the same PLC scan.<br />

215


Chapter: PLC Programming “The Inspection Conveyor”<br />

In the next example the code has be<strong>en</strong> made more effici<strong>en</strong>t and the PLC is only writing to the<br />

output once during the PLC scan, but it is more complicated to follow, and therefore more<br />

difficult to debug.<br />

If the ‘CASE’ statem<strong>en</strong>t is used th<strong>en</strong> we will see how flexible it really is.<br />

Previously there were two PEs, to add a third PE, simply add a third bit, copy and adjust which<br />

inputs are copied to which bits.<br />

216


Chapter: PLC Programming “The Inspection Conveyor”<br />

Expand the ‘Truth Table’ to include the new possible combinations<br />

From the ‘Truth Table’ we now see that the Motor Starter will be <strong>en</strong>ergized wh<strong>en</strong> iStep is equal<br />

to 2, 4, or 6<br />

217


Chapter: PLC Programming “The Inspection Conveyor”<br />

This can be reduced to:<br />

For an example of how to use a Truth Table and Boolean Algebra for the most effici<strong>en</strong>t coding of<br />

this example please refer to App<strong>en</strong>dix II – Truth Tables and Boolean Algebra.<br />

For this program we will use the ‘CASE’ statem<strong>en</strong>t as it is easier to make changes to.<br />

I have changed the variables names to match the naming conv<strong>en</strong>tion.<br />

xConvRunEnable is defined as a local BOOLEAN. This variable will be used to know wh<strong>en</strong> the<br />

Photo Eyes are in the correct states to start the conveyor. It will not be used to directly start and<br />

stop the conveyor.<br />

The xConvRunEnable will provide one of the start commands, each Photo Eye will provide a stop<br />

command. If we start with the following code we will see that the code gets locked up, because<br />

any time the middle PE is blocked the Conveyor cannot move. Therefore we need to monitor<br />

the PE and select wh<strong>en</strong> it will have an effect on the conveyor.<br />

218


Chapter: PLC Programming “The Inspection Conveyor”<br />

There are several ways to do this; the simplest is to use a Rising Edge Trigger ‘R_Trig’ from the<br />

‘Standard’ libray. The PE will provide the input and the output will be TRUE for one PLC scan.<br />

This will allow the program to know that a new boxed has arrived, and the Q output of the<br />

‘R_Trig’ can be monitored for stopping the conveyor while the PE itself is ignored.<br />

Add the three R_Trig functions blocks to the code below the CASE statem<strong>en</strong>t. The Q outputs of<br />

the function blocks were removed, because they will not be used on this line of code. It will be<br />

used later to stop the conveyor.<br />

In order to start the conveyor the <strong>en</strong>able needs to be TRUE and we are also going to pause the<br />

conveyor for 5 seconds each time a PE is blocked, this will allow the operator to place a new box<br />

at the Entry PE.<br />

The timer needs a condition that will stay TRUE for the duration of the PT (Preset Time). If the IN<br />

goes FALSE th<strong>en</strong> the timer will reset and start again with an ET (Elapsed Time) of zero. Wh<strong>en</strong> a<br />

box reaches a PE the conveyor should stop, 5 seconds later the conveyor should start again.<br />

Using each PE to stop the conveyor, th<strong>en</strong> a 5 second timer to pause the conveyor, th<strong>en</strong><br />

monitoring the xConvRunEnable will give us everything we need. This sequ<strong>en</strong>ce of steps is easily<br />

handled in a ‘CASE’ statem<strong>en</strong>t.<br />

219


Chapter: PLC Programming “The Inspection Conveyor”<br />

The basic framework of the ‘CASE’ statem<strong>en</strong>t will look like the following.<br />

Each step has a comm<strong>en</strong>t that describes what will happ<strong>en</strong> in that step. Each step number also<br />

increases by a value of 10, this allows for steps to be added without having to change all of the<br />

step numbers.<br />

The ‘Init’ step is there because it is a good habit to start, most ‘CASE’ statem<strong>en</strong>ts are going to<br />

need to use it; therefore, I always include it. As an example we will be adding a TON (Timer On)<br />

in step 20, this timer will be reset in the ‘Init’ step.<br />

220


Chapter: PLC Programming “The Inspection Conveyor”<br />

Below is the <strong>en</strong>tire ‘CASE’ statem<strong>en</strong>t.<br />

221


Chapter: PLC Programming “The Inspection Conveyor”<br />

Step 0 is the ‘Init’ step; here we set all Function Blocks that are going to be used within the<br />

‘CASE’ statem<strong>en</strong>t to FALSE. The last command of the step is to increase the value of<br />

iStepSequ<strong>en</strong>ce by 10. On the next PLC scan step 10 will be executed.<br />

Step 10 monitors the xConvRunEnable from the previous ‘CASE’ statem<strong>en</strong>t. IF the PEs are in<br />

their correct state, th<strong>en</strong> iStepSequ<strong>en</strong>ce will be increased by 10. On the next PLC scan step 20 will<br />

be executed.<br />

Step 20 calls the timer with a FALSE command; this will reset the ET of the timer to 0. Next the<br />

same timer is called with a TRUE command and giv<strong>en</strong> a time value of 5 seconds. Th<strong>en</strong><br />

iStepSequ<strong>en</strong>ce is increased by 1. On the next PLC scan step 21 will be executed.<br />

Step 21 calls the timer and monitors the Q output of the timer. After 5 seconds has elapsed the<br />

Q output will be TRUE, the timer will be reset with a FALSE command and the value of<br />

iStepSequ<strong>en</strong>ce will be set to 30.<br />

The reason for the extra step is to <strong>en</strong>sure that the timer is reset before being used, because the<br />

timer is reset in step 20 we must go to another step to wait for it to finish. If the code stayed in<br />

step 20 the timer would be reset every PLC scan and therefore it would never complete.<br />

Step 30 sets the Motor output to TRUE and increases iStepSequ<strong>en</strong>ce by 10.<br />

Step 40 monitors the outputs of the three R_Trig Function Blocks, wh<strong>en</strong> any one of them is TRUE<br />

the motor output is set to FALSE and iStepSequ<strong>en</strong>ce is set to 0.<br />

The process will th<strong>en</strong> repeat.<br />

The ELSE step is a good practice, if for some reason a change is made to the code and<br />

iStepSequ<strong>en</strong>ce is giv<strong>en</strong> a value that is not defined th<strong>en</strong> the commands in the ELSE step will be<br />

executed. Without the ELSE step the code would get stuck. Additionally iErrStepNumber is<br />

giv<strong>en</strong> a value of iStepSequ<strong>en</strong>ce to help find what the value of iStepSequ<strong>en</strong>ce was that s<strong>en</strong>t us to<br />

the else statem<strong>en</strong>t, this is purely used for debugging purposes.<br />

222


Chapter: PLC Programming “The Inspection Conveyor”<br />

Also notice how the code is ind<strong>en</strong>ted using the ‘TAB’ key. This is done to help make the code<br />

more readable. If we look at step numbers, it is easy to move downward and find the next step<br />

number. Also the IF and END_IF have nothing in betwe<strong>en</strong> them, which makes the END_IF easy to<br />

locate. Compare the two pictures below to see the differ<strong>en</strong>ce this makes.<br />

If nothing ever w<strong>en</strong>t wrong our conveyor would be mostly complete at this point; however, if it<br />

can go wrong it will. It is unlikely that you as a programmer will think of every possible situation<br />

that could cause a problem. Over time you will start to learn the most common problems. One<br />

of them is the possibility of a glitch in the Photo Eye. Wh<strong>en</strong> using a very s<strong>en</strong>sitive PE it is possible<br />

that the PE will transition from FALSE to TRUE at times other than wh<strong>en</strong> a box appears in front<br />

of it on the conveyor. Let us assume that a fly is in the building and it crosses in front of the<br />

path of the PE, dep<strong>en</strong>ding on the hardware of the PE it may or may not be detected. If it is<br />

detected th<strong>en</strong> the conveyor is going to stop as if a box was pres<strong>en</strong>t. To prev<strong>en</strong>t this type of<br />

problem we can add a ‘De-bounce circuit’ to the code. The idea of a ‘De-bounce circuit’ is to<br />

detect that a BOOLEAN condition has changed and stayed at its new state, and not bouncing<br />

betwe<strong>en</strong> TURE and FALSE. There are a couple of ways to do this; all of them deal with timing.<br />

223


Chapter: PLC Programming “The Inspection Conveyor”<br />

We will start with an obscure example because it makes for good sample code.<br />

In the above example wh<strong>en</strong> the PE is TRUE iCount will increase by a value of 1 each PLC scan. If<br />

the PLC scan is 10ms th<strong>en</strong> after 100ms (iCount >= 10) xInputDebounced will be set to TRUE. We<br />

would th<strong>en</strong> have to monitor xInputDebounced in our code and possibly look at other conditions<br />

for setting it to FALSE and set iCount back to 0.<br />

The above example inher<strong>en</strong>tly uses the PLC cycle time as the timer. If this was done on the<br />

machine and th<strong>en</strong> for some other reason the PLC task time needed to change, th<strong>en</strong> all of the<br />

places in the code where we de-bounced an input would need to change. In my opinion using<br />

the PLC scan to control your code is never a good idea.<br />

For another version of the above, please refer to App<strong>en</strong>dix III – De-bouncing and Input.<br />

Wh<strong>en</strong> de-bouncing an input that involves motion the speed at which the product is moving<br />

needs to be considered. Imagine we have a simple conveyor with a PE on the <strong>en</strong>d of the<br />

conveyor. The box should stop at the <strong>en</strong>d of the conveyor without stopping erroneously, but<br />

also should not allow boxes to fall into the floor. If the conveyor is moving extremely slow th<strong>en</strong><br />

the code could wait for the PE to be True for 1 second before stopping the conveyor. However<br />

as the conveyor increases in speed the 1 second wait might cause the box to move to far before<br />

stopping the conveyor. This would be another reason not to use the above counter and rely on<br />

it to work in all situations. If there is a way to know the velocity of the conveyor th<strong>en</strong> we can<br />

calculate the precise time we need to <strong>en</strong>sure a box is pres<strong>en</strong>t and still stop the conveyor before<br />

it falls off.<br />

D = R * T<br />

Distance = Rate of travel * Time<br />

If the box is 10 inches long and we want to limit it so that no more than 25% of the box moves<br />

past the PE th<strong>en</strong> our Distance will be 2.5 inches<br />

224


Chapter: PLC Programming “The Inspection Conveyor”<br />

The Rate of travel will be the speed of the conveyor. We will assume that out conveyor is<br />

moving at 1 foot per second (fps).<br />

Our reaction is now<br />

Time = Distance / Rate of travel<br />

Time = 2.5 inches / 1fps<br />

Time = 2.5 seconds<br />

Therefore we could implem<strong>en</strong>t the following code with a simple timer<br />

Note: The above sample will not compile, Distance / Rate will return a LREAL value which cannot<br />

be stored in a variable of type TIME<br />

Wh<strong>en</strong> the input is True for tTime (2.5 seconds) the output will th<strong>en</strong> be True. The output will turn<br />

False immediately wh<strong>en</strong> input turns False.<br />

To make this more flexible and reusable we will place this into a Function Block and allow the<br />

values of Distance and Rate to adjusted by a variable.<br />

Add a Function Block with a name of FB_DebounceInputFalseToTrue<br />

225


Chapter: PLC Programming “The Inspection Conveyor”<br />

Declare the follow in the Function Block<br />

Add the following code to the body of the Function Block<br />

The LREAL_TO_TIME conversion will convert the 2.5 into T#2.5ms, multiplying by 1000.0 before<br />

converting will result in tTime having a value of T#2.5s<br />

Op<strong>en</strong> P_InFeedConveyor and use the Function Block to de-bounce the 3 PEs on the Conveyor.<br />

226


Chapter: PLC Programming “The Inspection Conveyor”<br />

xExitPE, xMiddlePE, and xEntryPE are declared as local variables of type BOOL.<br />

In the Check if clear to advance and the Conveyor Advance sections we are using the real inputs<br />

in the code, these must be replaced by our new de-bounced inputs.<br />

227


Chapter: PLC Programming “The Inspection Conveyor”<br />

In review of where we started<br />

We see that the following sections of code have be<strong>en</strong> completed.<br />

De-bounce, Check if clear to Advance, and Conveyor Advance<br />

The On/Off delay was built into the CASE Statem<strong>en</strong>t for Conveyor Advance, so it can be<br />

removed.<br />

The next thing to implem<strong>en</strong>t is Jam Detection.<br />

The jam detector on this conveyor will detect wh<strong>en</strong> a box leaves either the Entry or Middle PE<br />

and does not reach the next PE.<br />

Because there will be two Jam Detectors we will implem<strong>en</strong>t this as a Function Block.<br />

This basic idea for the code is as follows<br />

If both PEs are False th<strong>en</strong> start a Timer. If the timer completes within the giv<strong>en</strong> amount of time<br />

th<strong>en</strong> this will indicate that the Box is stuck on the conveyor.<br />

A few things to consider:<br />

We don’t want the Jam Detector to cause an error if there are no boxes on the conveyor.<br />

228


Chapter: PLC Programming “The Inspection Conveyor”<br />

We need to know how long it is supposed to take for the box to get from one PE to the Next. We<br />

can do a calculation similar to the one we used for the de-bounce D=R*T.<br />

The last thing to keep in mind is what happ<strong>en</strong>s if the conveyor starts and the box gets jammed<br />

before clearing the first PE. Therefore, instead of using the NOT PE we will use the command for<br />

the Conveyor to start moving.<br />

Create a Function Block with the following name FB_JamDetection<br />

Declare the following in the Function Block.<br />

229


Chapter: PLC Programming “The Inspection Conveyor”<br />

Add the following code to the body of the Function Block.<br />

Lines 1-5<br />

A rising edge of i_xStart will be used to start Jam detection (xJamDectectEnable).<br />

Line 7<br />

Calculate the amount of time that can pass before turning on the error (q_xJamDetected).<br />

Line 9<br />

Call the timer.<br />

Lines 11-16<br />

If the destination is reached, disable the Jam Detection, disable the timer, and set the Jam<br />

Detected output to False.<br />

230


Chapter: PLC Programming “The Inspection Conveyor”<br />

Place the following in P_InfeedConveyor<br />

fbJamDetection_MiddlePE and fbJamDetection_ExitPE are defined locally as type<br />

FB_JamDetection<br />

xJamDetectedMiddlePE and xJamDetectedExitPE are defined locally as type BOOL<br />

We are using the destination as the Jam Detection PE. Therefore the Function Blocks are for the<br />

Middle and Exit PEs.<br />

The variable gatq_xMotorOn will be used to start the monitoring for a Jam.<br />

The destination PE will stop the monitoring.<br />

A distance of 50 with a Rate of 1 will make the timer run for 50 seconds before turning on the<br />

Jam Detected output.<br />

231


Chapter: PLC Programming “The Inspection Conveyor”<br />

Mode Handling<br />

In the Program ‘MAIN’ we created a CASE statem<strong>en</strong>t that would select the Mode based on the<br />

input selector switches, which were defined in ‘Global_Variables_IO’.<br />

eStep was defined locally in MAIN. We will need to change this to a global variable.<br />

Cut eStep :E_MachineState :=0; from the local declaration in MAIN, and Paste it into<br />

‘Global_Variables’. Use the Resources tab to see the Global Variable lists.<br />

MAIN should now have no local variables.<br />

‘Global_Variables’ should now have eStep.<br />

232


Chapter: PLC Programming “The Inspection Conveyor”<br />

The curr<strong>en</strong>t code inside of P_InfeedConveyor is for how we want it to operate wh<strong>en</strong> machine is<br />

in Auto. We still need code for <strong>Manual</strong>, and Maint<strong>en</strong>ance.<br />

In order to organize the code we will use ‘Actions’. One Action will be created for each possible<br />

state of E_MachineState. To review E_MachineState has four possible values: E_Undefined,<br />

E_Maint<strong>en</strong>ance, E_<strong>Manual</strong>, and E_Auto.<br />

To add an ‘Action’, Right-Click on P_InfeedConveyor and select ‘Add Action’ from the context<br />

m<strong>en</strong>u.<br />

233


Chapter: PLC Programming “The Inspection Conveyor”<br />

Name the ‘Action’ A_Auto, and set the language to ‘ST’. Th<strong>en</strong> click ‘OK’.<br />

Notice tha P_InfeedConveyor is now expandable, and the Action is shown wh<strong>en</strong> it is expanded.<br />

If you Double-Click on the Action, you will notice that it does not have a local variable<br />

declaration section. It only has a code window. Actions will use the same local variable list from<br />

the POU in which it is contained.<br />

Create actions for the other possible Modes of E_StateMachine, E_Maint<strong>en</strong>ance, E_<strong>Manual</strong>,<br />

and E_Undefined.<br />

Place a semicolon ; in each of the Actions. Preform a Project-> Rebuild All to compile the code.<br />

You should get 1 error.<br />

Double-click on the error and look at the code<br />

234


Chapter: PLC Programming “The Inspection Conveyor”<br />

In P_MachineMonitoring we were looking at the status of eStep, which was previously declared<br />

in MAIN. Since we have now moved eStep to a Global Variable we need to correct this line of<br />

code. Simply remove ‘MAIN.’ In front of eStep.<br />

Preform another Project -> Rebuild All, and th<strong>en</strong> Save your program.<br />

We now need to move parts of the code from P_InfeedConveyor into the A_Auto Action<br />

De-bouncing the Input PEs, Jam Detection, and Faults are not mode dep<strong>en</strong>d<strong>en</strong>t and will stay in<br />

P_InfeedConveyor.<br />

‘Check if clear to advance’ and ‘Conveyor advance’ could happ<strong>en</strong> in both <strong>Manual</strong> and Auto, but<br />

the code was writt<strong>en</strong> for Auto, and the code for <strong>Manual</strong> will be differ<strong>en</strong>t.<br />

Copy and Paste the ‘Check if clear to advance’ and ‘Conveyor advance’ code from<br />

P_InfeedConveyor to A_Auto.<br />

Starting at line 40<br />

Ending at Line 97<br />

235


Chapter: PLC Programming “The Inspection Conveyor”<br />

We must now call the Action A_Auto (and the other Actions) from P_InfeedConveyor.<br />

We will create a new CASE statem<strong>en</strong>t that selectively calls the Actions based on the value of<br />

eStep.<br />

The code in A_Auto is complete for now.<br />

236


Chapter: PLC Programming “The Inspection Conveyor”<br />

In A_<strong>Manual</strong> we will add code for Jogging the Conveyor.<br />

Declare gatq_xJogConveyor as a Global Input<br />

For now A_Maint<strong>en</strong>ance and A_Undefined have no use. Leave them with only a semicolon ; in<br />

them.<br />

237


Chapter: PLC Programming “The Inspection Conveyor”<br />

Fault Handling<br />

Creating faults for every possible situation is a never <strong>en</strong>ding task. We will create some faults for<br />

the most obvious conditions that could happ<strong>en</strong> in our program.<br />

Starting with Jam Detection, create a fault for each of the two Function Blocks<br />

Create a new Global Variable list called Global_Variables_Faults<br />

Declare the two new Fault Variables<br />

In the Fault section of P_InFeedConveyor place the following code.<br />

This code will turn on the two fault variables wh<strong>en</strong> a Jam is detected.<br />

238


Chapter: PLC Programming “The Inspection Conveyor”<br />

Add the following code to reset the faults.<br />

Note: This reset code will only reset the fault variable, if the fault condition still exists, th<strong>en</strong> the<br />

fault variable will set back to True.<br />

In the CASE statem<strong>en</strong>t that handles the conveyor in Auto we created an Error Step Number<br />

variable called iErrStepNumber.<br />

Add the following code to create a fault wh<strong>en</strong> this error happ<strong>en</strong>s.<br />

gxConveyorAutoSequ<strong>en</strong>ceErr, giConveyorAutoSequ<strong>en</strong>ceErrID, and<br />

gsConveyorAutoSequ<strong>en</strong>ceErrMsg are defined in the Global_Variables_Faults list<br />

Wh<strong>en</strong> the variable iErrStepNumber has a value other than zero three types of faults will happ<strong>en</strong>.<br />

gxConveyorAutoSequ<strong>en</strong>ceErr is a BOOL that will be set to TRUE.<br />

giConveyorAutoSequ<strong>en</strong>ceErrID is an INT that will hold the value of the Error Step.<br />

gsConveyorAutoSequ<strong>en</strong>ceErrMsg will hold a STRING that gives a description of the error and the<br />

Error Step number.<br />

239


Chapter: PLC Programming “The Inspection Conveyor”<br />

These Errors should be Reset by use of the variable gati_xReset. However, there is curr<strong>en</strong>tly no<br />

code to change iErrSStepNumber back to 0. We could do this somewhere in the CASE statem<strong>en</strong>t,<br />

but there could pot<strong>en</strong>tially be a problem caused by the PLC scan. Instead we will set it back to<br />

zero wh<strong>en</strong> the Reset button is pressed.<br />

Add the following code<br />

As we expand upon our Faults in further chapters we will explore more effici<strong>en</strong>t was to handle<br />

Faults, and resetting them.<br />

At this point our conveyor is complete. I would like to remind you of a point I made earlier. The<br />

more effici<strong>en</strong>t the code is, the more difficult it is to read. However the easier it is to read the<br />

harder it is to program wh<strong>en</strong> changes have to be made.<br />

The core of the program we just created could be summed up in 1 line of code<br />

However, this program is not flexible. Not IF, but WHEN someone decides that the machine<br />

needs to be modified it will be more difficult to do. Comparing the above line of code with the<br />

program that we created gives the impression that we wrote a bunch of code for no reason.<br />

However as we expand the machine, the power of this modular approach using Functions and<br />

Function Blocks will become very obvious.<br />

240


Chapter: Trouble shooting<br />

VI.<br />

Trouble shooting<br />

24.Lamp Test<br />

One of the key points of trouble shooting any system is knowing where to dissect the<br />

system. If you know where to break the system apart and what to look for th<strong>en</strong> the problem<br />

can be more easily isolated.<br />

In the below picture is a simple circuit consisting of a power supply, a push button, and a<br />

LED. If the LED is not illuminated th<strong>en</strong> the first step is to decide where to start searching for<br />

the problem. Test the power supply, if it is good th<strong>en</strong> test the continuity of the wire, if that<br />

is good, th<strong>en</strong> test the push button, and so on.<br />

With a PLC the method of trouble shooting does not change. Over the next few pages we<br />

will look at how the hardware is wired and how the communication happ<strong>en</strong>s wh<strong>en</strong> using a<br />

PLC to control our simple system.<br />

241


Chapter: Trouble shooting<br />

• The Power Rail is powered by an external source. The I/O cards receive their power from<br />

the cards to their left, and th<strong>en</strong> pass power to the cards on their right.<br />

• Be aware that not all cards use and/or pass the power rail.<br />

242


Chapter: Trouble shooting<br />

• The push button will be wired from Connection Point 2 on the EL1002 through the push button,<br />

and th<strong>en</strong> back to Connection Point 1 on the EL1002.<br />

• Wh<strong>en</strong> the contacts are closed power is s<strong>en</strong>t from the positive connection to the input.<br />

• The LED will be wired from Connection Point 3 on the EL2002 through the LED, and th<strong>en</strong> back to<br />

Connection Point 1 on the EL2002.<br />

• Wh<strong>en</strong> the output is turned on, the LED will illuminate.<br />

243


Chapter: Trouble shooting<br />

• The EtherCAT Coupler must be powered for communication to occur.<br />

• Note: This power should be supplied separately from the power rail.<br />

244


Chapter: Trouble shooting<br />

• The EtherCAT Coupler is connected to a network port on the Controller by an EtherCAT Cable.<br />

245


Chapter: Trouble shooting<br />

• The Controller will communicate with the I/O through the coupler. Wh<strong>en</strong> the Input is true this<br />

will be s<strong>en</strong>t to the controller to be processed by the PLC. The PLC will th<strong>en</strong> s<strong>en</strong>d a command to<br />

the output to turn on the LED.<br />

• Note: The Coupler power and power rail power are supplied separately.<br />

246


Chapter: Trouble shooting<br />

• In the <strong>TwinCAT</strong> System Manager the EtherCAT Coupler can be found under the I/O<br />

Configuration<br />

• I/O Devices – Device 1 EtherCAT – Term 1 EK1100<br />

(These are the default labels, they will probably be differ<strong>en</strong>t on your machine.)<br />

• The I/O Terminals can be found under the Coupler<br />

247


Chapter: Trouble shooting<br />

• In the <strong>TwinCAT</strong> System Manager the Hardware is linked to the PLC variables.<br />

248


Chapter: Trouble shooting<br />

• In the PLC the variables are declared with addresses so that they may be linked to the hardware<br />

• Wh<strong>en</strong> the code is run, Light1 will have the same value as Switch1<br />

• Power passes from the supply through the power rail and to the Push Button, wh<strong>en</strong> the button<br />

is pressed power is supplied to the input<br />

249


Chapter: Trouble shooting<br />

• Wh<strong>en</strong> the EtherCAT update happ<strong>en</strong>s the status of the input will be giv<strong>en</strong> to the EtherCAT packet<br />

• The EtherCAT card in the PC will pass the data directly to the PCs memory where it can be read<br />

by the System Manager<br />

250


Chapter: Trouble shooting<br />

• The system manager will th<strong>en</strong> pass the data from the I/O Configuration to the PLC Configuration<br />

• The PLC will th<strong>en</strong> process the code<br />

251


Chapter: Trouble shooting<br />

• The system manager will th<strong>en</strong> pass the data from the PLC Configuration back to the I/O<br />

Configuration<br />

252


Chapter: Trouble shooting<br />

• The EtherCAT card in the PC will read the data directly from the PCs memory and s<strong>en</strong>d out the<br />

EtherCAT packet over the network.<br />

• Wh<strong>en</strong> the data reaches the Output card the output will be <strong>en</strong>ergized and the LED will illuminate.<br />

253


Chapter: Trouble shooting<br />

• Electricity and Data flow “downstream”<br />

• From the Push Button to the LED<br />

• Along the path there are several places where the signal can be tested and/or monitored<br />

• At the wiring connection of the card, in the I/O or PLC configuration of the System Manager and<br />

in the PLC Code itself.<br />

254


Chapter: Trouble shooting<br />

• Wh<strong>en</strong> testing hardware it is possible to “Write” and to “Force” data into the system<br />

• A “Write” is applied one time and th<strong>en</strong> control is giv<strong>en</strong> back to the system<br />

• A “Force” in the System Manager is applied before each update of the I/O or PLC task<br />

• If a Write is applied to a variable that is not linked th<strong>en</strong> nothing in the system will tell that<br />

variable to have any other state<br />

• Wh<strong>en</strong> Writing or Forcing in the system manager the Flow of data must be tak<strong>en</strong> into<br />

consideration<br />

• If the Force is applied to an Input in the I/O Configuration th<strong>en</strong> everything downstream will react<br />

accordingly, just as if the Push Button had be<strong>en</strong> pressed<br />

• However, if the Output in the PLC Configuration is Forced th<strong>en</strong> only the hardware will be<br />

effected. The PLC Code will have no idea that the output has be<strong>en</strong> <strong>en</strong>ergized.<br />

• Wh<strong>en</strong> a variable is Forced inside the PLC, the Force is applied and th<strong>en</strong> the PLC Code is allowed<br />

to run as it normally would. The Force is th<strong>en</strong> applied again at the <strong>en</strong>d of the PLC Scan.<br />

• Here b has be<strong>en</strong> Forced to a value of 1 and a is assigned a value of b + 1 or 2<br />

• Here b has also be<strong>en</strong> forced to a value of 1<br />

• However, the first line of code assigns a value of 2 to b<br />

• This will result in a being assigned the value of 3<br />

255


Chapter: Trouble shooting<br />

25.Code Sequ<strong>en</strong>cing<br />

• <strong>TwinCAT</strong> can control up to 4 PLC Run-Times<br />

• Each Run-Time can have up to 4 Tasks<br />

• This allows for up to 16 tasks each with their own update rate.<br />

• In the Task configuration of the Resources Tab you will find the Default ‘Standard’ task with its<br />

call to the program ‘MAIN’<br />

• Task ‘Standard’ is configured here with a Priority of 0 and an interval of 10ms<br />

256


Chapter: Trouble shooting<br />

• The below tasks are configured with a ‘SlowTask’ at 50ms and a Priority of 2, task ‘Standard’<br />

runs at 10ms with a Priority of 1, and the task ‘FastTask’ has an interval of 1ms and a Priority of<br />

0<br />

• The highest Priority ‘0’ should always have the fastest interval time<br />

• In this configuration the ‘Standard’ task calls the program ‘MAIN’<br />

• ‘MAIN’ will th<strong>en</strong> call its subsequ<strong>en</strong>t POUs<br />

257


Chapter: Trouble shooting<br />

• In the below example ‘MAIN’ is calling the other programs<br />

• The first line of code in ‘MAIN’ calls the program ‘<strong>Manual</strong>’<br />

• ‘<strong>Manual</strong>’ will run its code from top to bottom and th<strong>en</strong> return to ‘MAIN’<br />

• ‘MAIN’ will th<strong>en</strong> call ‘Semi_Auto’<br />

• ‘Semi_Auto’ will run its code from top to bottom and th<strong>en</strong> return to ‘MAIN’<br />

• Note: To view the Call Tree, right click on a POU and select ‘Show Call Tree’<br />

258


Chapter: Trouble shooting<br />

• If a Function Block is called from a program the same process applies<br />

• Wh<strong>en</strong> the last line of code in ‘MAIN’ is reached the PLC will return to the first line and repeat the<br />

process<br />

• Below is an online view of ‘MAIN’<br />

• The dark gray lines are code that is running, line 6 is the last line of code<br />

259


Chapter: Trouble shooting<br />

26.Break Points<br />

• WARNING!<br />

• A Breakpoint will stop the PLC<br />

• Note: If a breakpoint is set by accid<strong>en</strong>t the fastest way to remove it is to ‘Logout’ of the PLC<br />

(F12), but with the PLC running every 10ms you probably won’t make it in time.<br />

• Breakpoints are <strong>en</strong>abled and disabled in the Project -> Options m<strong>en</strong>u<br />

260


Chapter: Trouble shooting<br />

• In the left column select ‘<strong>TwinCAT</strong>’<br />

• Select ‘Enable breakpoints’ th<strong>en</strong> click ‘OK’<br />

• Breakpoints can be used to aid in debugging the PLC code<br />

• Wh<strong>en</strong> the line is selected where the Breakpoint is to happ<strong>en</strong> the PLC code will run until that line<br />

of code is reached<br />

• Wh<strong>en</strong> the breakpoint is reached the PLC will stop running and the status of variables can be<br />

se<strong>en</strong> in their curr<strong>en</strong>t state<br />

• This will allow the checking of the code to determine if the code is executing properly<br />

• Note: Breakpoints can NOT be set in an instance of a function block they must be set in the<br />

implem<strong>en</strong>tation of the function block and therefore each instance of that function block will<br />

stop wh<strong>en</strong> the breakpoint is reached.<br />

• To set a breakpoint, click on the rung or line number where you wish the PLC to stop<br />

261


Chapter: Trouble shooting<br />

• Here the breakpoint has be<strong>en</strong> set on line 4. bSwitch is curr<strong>en</strong>tly TRUE and therefore the PLC is<br />

still running<br />

• Also note that the breakpoint indicator is set in the bottom right corner of the PLC Control<br />

• Wh<strong>en</strong> bSwitch turns FALSE the breakpoint on line 4 will stop the PLC<br />

• The code on line 4 is not executed<br />

• We can also see in the status bar that the PLC is no longer running<br />

262


Chapter: Trouble shooting<br />

• The Online m<strong>en</strong>u provides the programmer with a list of options<br />

• The Run (F5) command will start the PLC again and it will run until it hits a breakpoint<br />

• The Toggle Breakpoint(F9) command will remove or add a Breakpoint at the line where the<br />

cursor is curr<strong>en</strong>tly located<br />

• Step over (F10) will execute the line of code and go to the next line of code. If a call to another<br />

POU is on the line of code being executed, the POU will run in its <strong>en</strong>tirety<br />

• Step in (F8) will perform the same action as Step over with the added functionality of op<strong>en</strong>ing<br />

the called POU and stepping through its code line by line<br />

Note: The Step in command will not op<strong>en</strong> a POU inside of a library<br />

• Single Cycle (Ctrl+F5) will run the PLC to the next breakpoint.<br />

If only one breakpoint is set th<strong>en</strong> the PLC will run from the breakpoint thru the last line of code, upon<br />

the next Single Cycle command the PLC will run from the first line of code up to the breakpoint.<br />

Note: Once a breakpoint has be<strong>en</strong> reached the Single Cycle command will still stop at the breakpoint<br />

ev<strong>en</strong> if the code would not normally execute the line of code where the breakpoint exists.<br />

263


Chapter: Trouble shooting<br />

• The Breakpoint Dialog command op<strong>en</strong>s the below window<br />

• From here you can see a list of all breakpoints that exists in the PLC<br />

• Breakpoints can also be added and removed from here<br />

264


Chapter: Trouble shooting<br />

27.Flow Control<br />

• Flow control allows you to see which lines of code are being executed<br />

• In the sample lines 1 and 4 are running because 1 is greater than 0<br />

265


Chapter: Trouble shooting<br />

• Flow Control can be turned on thru the ‘Online’ m<strong>en</strong>u or with the keyboard shortcut Ctrl+F11<br />

• Flow Control may appear at times to not be working, there are 3 possible reasons for this.<br />

1. You must be ‘Logged In’ to the PLC<br />

2. The program you are monitoring is not being called<br />

3. The task that is responsible for calling the program you are monitoring must be set to the<br />

‘Debug Task’<br />

266


Chapter: Trouble shooting<br />

• In this example wh<strong>en</strong> ‘a’ is greater than ‘b’ the program Light_On is called<br />

• First take note that the code for Light_Off will only show the flow control if the program<br />

Light_Off is being called and you can see from ‘MAIN’ that it is not being called unless a is not<br />

greater than b<br />

• Secondly note that only the selected window will display the flow control<br />

267


Chapter: Trouble shooting<br />

• The debug task can be set in the Task configuration wh<strong>en</strong> you are logged in to the PLC<br />

• Right click on the Task name and set it as the ‘Debug’ task<br />

• Flow Control is only displayed for the ‘Debug’ task<br />

• Warning!!!<br />

• Flow control should never be used inside of a function block<br />

• Only use Flow control in a Program<br />

• If Flow Control is on inside of a Function Block it will display the values and status of the first<br />

instance of that Function Block<br />

268


Chapter: Trouble shooting<br />

• In the below picture you see that the second instance of the Function Block indicates that it is<br />

running ev<strong>en</strong> though it is not being called from ‘MAIN’<br />

269


Chapter: Trouble shooting<br />

• Notice in this picture that bPulse is blue indicating that it has a value of TRUE<br />

• However fbPulse2 is not being called from ‘MAIN’ and bPulse in the local delaration has a value<br />

of FALSE<br />

• NEVER use Flow Control inside of a Function Block<br />

270


Chapter: Trouble shooting<br />

28.Global Search<br />

• The Global Search tool allows for the search of anything inside of any part of the project or the<br />

<strong>en</strong>tire project<br />

• A Global Search can be started in 3 differ<strong>en</strong>t ways<br />

• Project -> Global Search<br />

• Ctrl+ Alt + S<br />

• Tool Bar Icon<br />

271


Chapter: Trouble shooting<br />

• Selecting Global Search from the Project M<strong>en</strong>u will op<strong>en</strong> the following window<br />

• Ctrl+Alt+S will op<strong>en</strong> the same window<br />

• From here the sections of the program to be searched can be selected<br />

• Holding the Ctrl key will allow for selecting multiple sections<br />

Note: Using the Tool Bar icon skips this selection window and will search the <strong>en</strong>tire project.<br />

272


Chapter: Trouble shooting<br />

• Once the sections have be<strong>en</strong> selected press the ‘OK’ button<br />

273


Chapter: Trouble shooting<br />

• From this dialog box type in the search phrase<br />

• If text was selected (highlighted) before starting the Global Search it will appear in the box<br />

• Set the filter options for ‘Match whole word only’ and ‘Match Case’<br />

• The ‘Find Next’ button will search for the first occurr<strong>en</strong>ce of the search phrase, and each time<br />

the button is pressed it will go to the next occurr<strong>en</strong>ce<br />

• ‘Cancel’ will close the search box<br />

• ‘Message Window’ will search for all occurr<strong>en</strong>ces and list them in the message window.<br />

• Note: If you are Logged In to the PLC, the message window is hidd<strong>en</strong> by default. Selecting<br />

‘Message Window’ from the ‘Window’ m<strong>en</strong>u or pressing Shift+Esc on the keyboard will op<strong>en</strong> the<br />

Message Window<br />

274


Chapter: Trouble shooting<br />

• Searching for the letter ‘a’ will return everywhere the letter ‘a’ is used in the sections selected<br />

• The first line shows the search phrase<br />

• The last line shows how many times the search phrase was found<br />

275


Chapter: Trouble shooting<br />

• The second line below is stating the following<br />

• Double Clicking a line in the Message Window will take you to that line of code in the program<br />

• Wh<strong>en</strong> using the search tools on a structure remember that the Global Search will search for<br />

anything and the Cross Refer<strong>en</strong>ce needs an exact variable name<br />

• The Global Search tool can be used to search for an elem<strong>en</strong>t within a structure, the instance of<br />

the structure or both<br />

276


Chapter: Trouble shooting<br />

29.Cross Refer<strong>en</strong>ce<br />

• The Cross Refer<strong>en</strong>ce tool allows for searching specific items in the PLC<br />

• Variable<br />

• Address<br />

• POU<br />

• The tool can be started 2 ways<br />

• Project -> Show Cross Refer<strong>en</strong>ce<br />

• Ctrl+Alt+C<br />

• Note: The code must compile with no errors before a cross refer<strong>en</strong>ce can be done. Additionally<br />

if a Build has not be<strong>en</strong> done since the last change was made the cross refer<strong>en</strong>ce could return<br />

incorrect results<br />

277


Chapter: Trouble shooting<br />

• The variable name must me <strong>en</strong>tered exactly as it is used in the PLC code<br />

• Selecting the text before op<strong>en</strong>ing the tool will place the selected text in the ‘Name’ box.<br />

• Get Refer<strong>en</strong>ces’ will start the search<br />

• After selecting an item in the POU column ‘Go To’ will op<strong>en</strong> the POU to the line of code where<br />

the variable is used. Double clicking the POU name will also go to where the variable is used<br />

• ‘Cancel’ will close the search window<br />

• ‘To message window’ will s<strong>en</strong>d all of the search results to the message window. The format will<br />

be done the same as a ‘Global Search’<br />

278


Chapter: Trouble shooting<br />

• The ‘List of Refer<strong>en</strong>ces’ shows the following<br />

• The POU and line where the variable was found<br />

• The name of the variable<br />

• The address of the variable (if it has one)<br />

• The scope of the variable Global or Local<br />

• The Variable access (Read or Write)<br />

279


Chapter: Trouble shooting<br />

• Wh<strong>en</strong> searching by address the full address must be <strong>en</strong>tered<br />

• Only the address <strong>en</strong>tered will be searched, overlapping memory addresses will not be found<br />

280


Chapter: Trouble shooting<br />

• The POU search is limited, but wh<strong>en</strong> multiple tasks are used this will tell you which task to set as<br />

the ‘Debug Task’ for displaying the ‘Flow Control’<br />

281


Chapter: Trouble shooting<br />

• Wh<strong>en</strong> looking for where a POU is in the POU list, click somewhere in the POU list and start<br />

typing the name of the POU<br />

• This will bring up a dialog box that will narrow down the results as you type<br />

• Select the POU name from the list and th<strong>en</strong> select op<strong>en</strong><br />

• This will op<strong>en</strong> the POU and also highlight it in the POU list<br />

282


Chapter: Trouble shooting<br />

30.Scope View<br />

• Scope View is a software oscilloscope for monitoring variables in the PLC<br />

• Scope View is an optional compon<strong>en</strong>t that can be installed wh<strong>en</strong> <strong>TwinCAT</strong> is installed<br />

• From the Windows Start m<strong>en</strong>u select Programs, <strong>TwinCAT</strong> System, <strong>TwinCAT</strong> Scope View<br />

• Right click on Scope and select Add Scope View<br />

283


Chapter: Trouble shooting<br />

• Leave the defaults and select OK<br />

• Right click on Scope View 1 and select Add Channel<br />

284


Chapter: Trouble shooting<br />

• Give the Channel a descriptive name and press OK<br />

• On the Acquisition Tab of the Channel press the Change button<br />

285


Chapter: Trouble shooting<br />

• In the Edit Acquisition window select the correct Server Port and press the Reload Symbols<br />

button<br />

286


Chapter: Trouble shooting<br />

• Select MAIN.BSWITCH and press OK<br />

287


Chapter: Trouble shooting<br />

• Press the Start button<br />

288


Chapter: Trouble shooting<br />

• Wh<strong>en</strong> the PLC variable changes state the change can be se<strong>en</strong> in the Scope<br />

289


Chapter: Labs<br />

VII.<br />

Labs<br />

31.Languages<br />

Assignm<strong>en</strong>t:<br />

Write a program that will monitor an Analog Value and <strong>en</strong>ergize an output if the value is<br />

within a specific range.<br />

Thoughts:<br />

We have 1 output to control.<br />

The output will be <strong>en</strong>ergized if the value is within range. A range is defined as having an<br />

upper value and a lower value.<br />

Therefore we have 2 conditions that determine if the output is <strong>en</strong>ergized. The first condition<br />

is that the value is greater than the low <strong>en</strong>d of the range, and the second condition is that<br />

the value is less than the upper <strong>en</strong>d of the range.<br />

If both conditions are TRUE th<strong>en</strong> the output will be <strong>en</strong>ergized.<br />

Condition1 is that the value of the analog input is greater than the lower <strong>en</strong>d of the Range.<br />

We will assume the lower <strong>en</strong>d of the range is defined as 0.<br />

Therefore Condition will be TRUE is the value is greater than 0.<br />

Condition2 is that the value of the analog input is less than the upper <strong>en</strong>d of the Range. We<br />

will assume the upper <strong>en</strong>d of the range is defined as 10,000.<br />

Therefore Condition will be TRUE is the value is less than 10,000.<br />

290


Chapter: Labs<br />

Here is the Ladder Diagram (LD) Code to solve the problem<br />

291


Chapter: Labs<br />

Here is the Function Block Diagram (FBD) Code<br />

It could also be writt<strong>en</strong> this way<br />

292


Chapter: Labs<br />

In Continuous Function Chart (CFC) it will look very similar to the second FBD example.<br />

Notice that iPot is only used once, and th<strong>en</strong> connected to both inputs. Also notice the order<br />

of operation in the gray box. If this order of operations is incorrect, it will require multiple<br />

PLC scans to fully execute the code.<br />

293


Chapter: Labs<br />

For Instruction List (IL) the same ideas still apply, but we now work with 1 simple instruction<br />

at a time, and we work with a ‘Holding Register’<br />

The below code works like this:<br />

The LD command will load the value of the following variable into the holding register.<br />

The AND command will perform the AND function on the value of the following variable and<br />

the value stored in the holding register. It will th<strong>en</strong> store that result in the holding register.<br />

The ST command will read the value from the holding register and store it in the following<br />

variable.<br />

Load the value of Condition1<br />

AND it with Condition2<br />

Store the result in xLight1<br />

For the comparison we do the following<br />

Load the value of iPot<br />

If it is Greater Than 0 th<strong>en</strong> store a TRUE, else store a False<br />

Store the result in Condition1<br />

Load the value of iPot<br />

If it is Less Than 10,000 the store a TRUE, else store a FALSE<br />

Store the result in Condition2<br />

294


Chapter: Labs<br />

In some of the previous example I started with the output first. This was only done for<br />

planning and explanation. It should be noted that you should always set your Conditions<br />

before you evaluate them. However, wh<strong>en</strong> writing code it is a common practice to work<br />

backwards to find a solution. Starting with the Output and th<strong>en</strong> working back towards the<br />

input conditions that control the state of that output.<br />

We started with the xLight1, and the 2 conditions required to <strong>en</strong>ergize it. We th<strong>en</strong> looked at<br />

the values of iPot that were needed to set the conditions.<br />

Although we wrote that conditions last, they should be analyzed first.<br />

Below are the full solutions:<br />

Ladder Diagram (LD)<br />

295


Chapter: Labs<br />

Function Block Diagram (FBD)<br />

Or<br />

Continuous Function Chart (CFC)<br />

296


Chapter: Labs<br />

Instruction List (IL)<br />

The last language option is Structured Text (ST)<br />

In the previous examples I started with the output first, and wrote the code that would<br />

control that output. In ST we will do the same; however, we will apply this literally. In ST the<br />

line of code will always start with the variable that we would like to assign a value to.<br />

The above line of code reads as<br />

xLight1 is assigned a value of Condition1 and Condition2<br />

The := is an assignm<strong>en</strong>t statem<strong>en</strong>t. Anytime you would like to assign a value to a variable<br />

this symbol will be used.<br />

In Structured Text the semi-colon is a separator. It indicates that a giv<strong>en</strong> statem<strong>en</strong>t is<br />

separate from the one that follows. It actually has little to do with being at the <strong>en</strong>d of each<br />

line of code other than we humans like to put it there. As long as it appears somewhere<br />

before the next statem<strong>en</strong>t, it will be fine. The semi-colon is for the compiler, not the human.<br />

297


Chapter: Labs<br />

These two lines of code:<br />

xMyOutput:=true<br />

;xMyOtherOutput:=false;<br />

Are equally valid as these two lines of code:<br />

xMyOutput:=true;<br />

xMyOtherOutput:=false;<br />

In the case of a block statem<strong>en</strong>t like IF-THEN, CASE-OF or WHILE-DO, the compiler already<br />

knows how to parse it via predefined delimiters such as END_CASE, ELSE, ELSIF, END_WHILE,<br />

et cetera. Therefore a semicolon becomes unnecessary in a block statem<strong>en</strong>t except to parse<br />

the separation of the individual lines inside the block statem<strong>en</strong>t.<br />

IF myValue > 9 THEN<br />

xMyOutput:=true;<br />

xMyOtherOutput:=false;<br />

END_IF<br />

298


Chapter: Labs<br />

Now we add the code to control the Conditions.<br />

Par<strong>en</strong>theses aid in understanding and controlling the order of operation.<br />

Condition1 is assigned a value of: (iPot > 0) <strong>en</strong>d of line<br />

Greater Than > is a function. Pass in 2 values and it will return either TRUE or FALSE.<br />

If iPot is greater than 0 th<strong>en</strong> the function will return a TRUE, and Condition1 will be set to<br />

TRUE.<br />

If iPot is not greater than 0 th<strong>en</strong> the function will return a FALSE, and Condition1 will be set<br />

to FALSE.<br />

If the value of iPot is less than 10,000 th<strong>en</strong> the function will return TRUE, and Condition2 will<br />

be set to TRUE, else the function will return FALSE, and Condition2 will be set to FALSE.<br />

Wh<strong>en</strong> looking at these three lines of code together, notice that each of them <strong>en</strong>ds with a ;<br />

this tells us that each of them are their own lines of code.<br />

Each line of code has an assignm<strong>en</strong>t instruction, and there is either an evaluation or<br />

instruction that must happ<strong>en</strong> to determine the value that will be assigned to the output.<br />

Similar to the other languages, there are many ways to write the code and obtain the same<br />

result.<br />

This line of code simply compresses the above into one line.<br />

IF iPot is greater than 0 and iPot is less than 10,000 th<strong>en</strong> xLight1 will be TRUE, else xLight1<br />

will be FALSE.<br />

299


Chapter: Labs<br />

The IF instruction will selectively call parts of the code. It is similar to a jump instruction.<br />

Betwe<strong>en</strong> IF and THEN the code must simplify down to either TRUE or FALSE<br />

IF iPot is greater than 0 and iPot is less than 10,000 th<strong>en</strong> xLight1 will be TRUE, ELSE xLight1<br />

will be FALSE.<br />

The code of the ELSE condition will only be executed if the IF statem<strong>en</strong>t returns a FALSE.<br />

IF TRUE THEN<br />

ELSE<br />

END_IF<br />

Run This Code<br />

Run This Code<br />

Every IF instruction requires an END_IF<br />

300


Chapter: Labs<br />

32.Linear scaling using a Ratio<br />

Assignm<strong>en</strong>t:<br />

Create a function the will scale a value betwe<strong>en</strong> 0 and 32767 to a value betwe<strong>en</strong> 0 and 100.<br />

Thoughts:<br />

Because both scales start at 0 we can simply divide the maximum scale-to value by the<br />

maximum scaled-from value.<br />

This will give us a ratio that we can multiply by the input and it will give us the scaled value.<br />

The formula will be<br />

Ratio := MaxOutput / MaxInput;<br />

ScaledValue := InputValue * Ratio;<br />

301


Chapter: Labs<br />

33.Linear scaling using an equation<br />

Assignm<strong>en</strong>t:<br />

Create a function that will scale a value betwe<strong>en</strong> any two numbers to a value betwe<strong>en</strong> any two<br />

other numbers.<br />

Thoughts:<br />

This is similar to converting temperature from one scale to another. The numbers can go both<br />

positive and negative. For any giv<strong>en</strong> value on 1 scale there is exactly 1 possible value on the<br />

other scale. 32 degrees F = 0 degrees C and 212 degrees F = 100 C<br />

Think of the Celsius scale as the X-axis and the Fahr<strong>en</strong>heit scale as the Y-axis.<br />

The Formula to convert from Celsius to Fahr<strong>en</strong>heit is:<br />

TempF = 9/5 * TempC + 32<br />

The +32 is the offset of the line, because it does not cross the Y-axis at 0.<br />

The 9/5 comes from the step required to get from one position on the line to the next.<br />

For each increase of 9 degrees in Fahr<strong>en</strong>heit, you must increase 5 degrees in Celsius.<br />

An increase on the Y-axis is referred to as Rise, an increase on the X-axis is called a Run.<br />

So we have a Rise of 9 and a Run of 5. This can be calculated using the two known positions<br />

100,212 and 0,32. The differ<strong>en</strong>ce in the values will give us the change in Step.<br />

212-32 / 100-0 = 180 / 100 = dividing both numerator and d<strong>en</strong>ominator by 20 will reduce the<br />

fraction to 9/5<br />

Step = Y2 – Y1 / X2 – X1 = 212-32/100-0 = 9/5<br />

302


Chapter: Labs<br />

Because the step is actually a ratio it is referred to as the slope of the Line, in the formula we will<br />

use the letter m.<br />

The formula needed to do our conversion is<br />

y=mx+b<br />

m = Y2 – Y1 / X2 – X1 = 212-32/100-0 = 9/5<br />

x = Temp in Celsius<br />

b = 32 the Y-Intercept, the location where the line crosses the Y-axis<br />

y = 9/5 * TempC + 32<br />

TempF = 9/5 * TempC +32<br />

Using this formula we can now convert from any scale to any other scale<br />

y = mx + b<br />

m = Y2 - Y1 / X2 - X1<br />

b = How do you calculate b if you don’t have a graph?<br />

b = y1 – ( x1 * m )<br />

If we know two points on the graph 0,32 and 100,212 we can calculate everything else in the<br />

PLC<br />

303


Chapter: Labs<br />

304


Chapter: Camming<br />

VIII.<br />

Camming<br />

Creation of Cam Tables with or without TC Cam Design Tool, with the new MC2 PLC Op<strong>en</strong> Standard<br />

34.Preface<br />

This docum<strong>en</strong>t is mostly compiled with information and scre<strong>en</strong> shots directly from the Beckhoff<br />

Information System version 01/2010. The curr<strong>en</strong>t version can be downloaded from here. If you prefer<br />

not to download and install the Beckhoff Information System you can also access it on the web.<br />

However please keep in mind that the links in the docum<strong>en</strong>t only work if you have the Information<br />

System installed locally in the default location. The links in the docum<strong>en</strong>t will op<strong>en</strong> a web page showing<br />

the Information System article on the specific topic and not the <strong>en</strong>tire Information System. Additionally<br />

the docum<strong>en</strong>tation for the specific topics covered and refer<strong>en</strong>ced in the article can be downloaded<br />

using the following: <strong>TwinCAT</strong> Cam Design Tool TcMC2 Camming.lib Note: these are .chm files and you<br />

must ‘UnBlock’ them before they can be op<strong>en</strong>ed.<br />

This docum<strong>en</strong>t covers a brief introduction to the new TcMC2 library; as defined by PLCop<strong>en</strong>, and<br />

its differ<strong>en</strong>ces from the previous TcMC library. TcMC2.lib has be<strong>en</strong> included with <strong>TwinCAT</strong> NC PTP and<br />

higher since version 2.10 build 1340. To download the <strong>TwinCAT</strong> developm<strong>en</strong>t software please go here.<br />

The registration form must have a valid email address and the requested version can be selected at the<br />

bottom of the form. After ‘submitting’ the information a link to download the requested version will be<br />

emailed to the email address provided.<br />

The docum<strong>en</strong>t th<strong>en</strong> covers the creation of cam tables from either the PLC or the <strong>TwinCAT</strong> Cam<br />

Design Tool. Wh<strong>en</strong> using the PLC to create a cam table the TcMC2_Camming.lib is required. This library<br />

is provided as a supplem<strong>en</strong>t to <strong>TwinCAT</strong> and must be purchased. This library is required for all camming<br />

functionality, ev<strong>en</strong> if the <strong>TwinCAT</strong> Cam Design Tool is used. The <strong>TwinCAT</strong> Cam Design Tool is provided as<br />

a supplem<strong>en</strong>t to <strong>TwinCAT</strong> to assist in the developm<strong>en</strong>t of cam tables by giving a graphical<br />

repres<strong>en</strong>tation to the cam table and its elem<strong>en</strong>ts. The <strong>TwinCAT</strong> Cam Design Tool must be purchased,<br />

but can also be evaluated for 30 days by <strong>en</strong>tering ‘DEMO’ wh<strong>en</strong> asked for a product key.<br />

The use of Motion Functions as defined by the VDI 2143 Guidelines is covered in the docum<strong>en</strong>t;<br />

however the functions themselves are not covered. The curr<strong>en</strong>t publication from the VDI is geared<br />

toward mechanical cams and is only published in Deustch. The VDI does have plans to publish a new<br />

docum<strong>en</strong>t in English that will focus more on software camming; however no indication of wh<strong>en</strong> this<br />

might occur has be<strong>en</strong> giv<strong>en</strong>.<br />

305


Chapter: Camming<br />

35.Intro to TcMC2.Lib<br />

a. Overview<br />

The TcMC2 <strong>TwinCAT</strong> motion control PLC library includes function blocks for programming machine<br />

applications and repres<strong>en</strong>ts a further developm<strong>en</strong>t of the TcMC library. TcMC2 is based on the revised<br />

PLCop<strong>en</strong> specification for motion control function blocks V2.0 (www.PLCop<strong>en</strong>.org).<br />

Compatibility<br />

The TcMC2 motion control library contains <strong>en</strong>hanced and new functions. The function blocks are better<br />

adapted to the requirem<strong>en</strong>ts of the PLCop<strong>en</strong> specification and are not compatible with the first version<br />

(TCMC). Users maintaining existing projects are advised to continue using the original TcMC library for<br />

these projects, although TcMC2 should be used for new projects or revision of existing projects.<br />

Main new features<br />

A key feature of TcMC2 compared with TcMC is the so-called buffer mode. Buffer mode <strong>en</strong>ables Move<br />

commands to be queued in order to achieve a continuous positioning without intermediate stops. It<br />

<strong>en</strong>ables transition of two travel commands with a defined velocity at a certain position.<br />

Move commands can be followed by further Move commands during execution. This makes adaptation<br />

of target position or travel speed during the movem<strong>en</strong>t much easier.<br />

<strong>TwinCAT</strong> Version<br />

The TcMC2 library is available from <strong>TwinCAT</strong> version 2.10 build 1340. On remote programmable<br />

controls, both systems, the programming PC and the control PC, must have installed an appropriate<br />

version. Windows CE systems must have installed an image from version Windows CE 3.08.<br />

306


Chapter: Camming<br />

G<strong>en</strong>eral rules for MC function blocks<br />

For all MC function blocks the following rules apply, which <strong>en</strong>sure defined processing through the PLC<br />

program.<br />

Exclusivity of the outputs<br />

The outputs Busy, Done, Error and CommandAborted are mutually exclusive, i.e. only one of these<br />

outputs can be TRUE at a function block at any one time. Wh<strong>en</strong> the Execute input becomes TRUE, one of<br />

the outputs must become TRUE. Similarly, only one of the outputs Active, Error, Done and<br />

CommandAborted can be TRUE at any one time.<br />

An exception of this rule is, MC_Stop. MC_Stop sets Done to TRUE as soon as the axis is in standstill.<br />

Busy and Active stay TRUE, since the axis is locked. After Execute is reset to FALSE, the axis is released<br />

and Busy as well as Active are reset to FALSE.<br />

Initial state<br />

The outputs Done, InGear, InSync, InVelocity, Error, ErrorID and CommandAborted are reset with a<br />

falling edge at input Execute, if the function block is not active (Busy=FALSE). However, a falling edge at<br />

Execute has no influ<strong>en</strong>ce on the command execution. Resetting Execute during command execution<br />

<strong>en</strong>sures that one of the outputs is set at the <strong>en</strong>d of the command for a single PLC cycle. Only th<strong>en</strong> are<br />

the outputs reset.<br />

If Execute is triggered more than once while a command is executing, the function block will not execute<br />

further commands and will not provide any feedback.<br />

Input parameters<br />

The input parameters are read with rising edge at Execute. To change the parameters the command has<br />

to be triggered again once it is completed or a second instance of the function block must be triggered<br />

with new parameters during command execution.<br />

If an input parameter is not transferred to the function block, the last value transferred to this block<br />

remains valid. A meaningful default value is used for the first call.<br />

Position and Distance<br />

The Position input d<strong>en</strong>otes a defined value within a coordinate system, while Distance is a relative<br />

measure for the distance betwe<strong>en</strong> two positions. Position and Distance are specified in technical units,<br />

e.g. [mm] or [°], according to the axis scaling.<br />

Dynamic parameters<br />

The dynamic parameters for Move functions are specified in technical units with second as time base. If<br />

an axis is scaled in millimeters, for example, the following units are used: Velocity [mm/s], Acceleration<br />

[mm/s2], deceleration [mm/s2], jerk [mm/s3].<br />

307


Chapter: Camming<br />

Error handling<br />

All function blocks have two error outputs for indicating errors during command execution. Error<br />

indicates the error; ErrorID contains a supplem<strong>en</strong>tary error number. The outputs Done, InVelocity,<br />

InGear and InSync indicate successful command execution and are not set if Error becomes TRUE.<br />

Errors of differ<strong>en</strong>t type are signaled at the function block output. The error type is not specified<br />

explicitly. It dep<strong>en</strong>ds on the unique, system-wide error number.<br />

Error types<br />

Function block errors only related to the function block, not the axis (e.g. incorrect parameterization).<br />

Function block errors do not have to be reset explicitly. They are reset automatically wh<strong>en</strong> the Execute<br />

input is reset.<br />

Communication errors (the function block cannot address the axis, for example). Communication errors<br />

usually indicate incorrect configuration or parameterization. A reset is not possible. The function block<br />

can only be triggered again after the configuration was corrected.<br />

Axis errors (logical NC axis) usually occur during the motion (e.g. following error). They cause the axis to<br />

switch to error status. An axis error must be reset through MC_Reset.<br />

Drive errors (control device) may result in an axis error, i.e. an error in the logical NC axis. In many cases<br />

axis errors and drive errors can be reset together through MC_Reset. Dep<strong>en</strong>ding on the drive controller,<br />

a separate reset mechanism may be required (e.g. connection of a reset line to the control device).<br />

Behavior of the Done output<br />

The Done output (or alternatively InVelocity, InGear, InSync, etc.) is set wh<strong>en</strong> a command was executed<br />

successfully. If several function blocks are used for an axis and the running command is interrupted<br />

through a further block, the Done output for the first block is not set.<br />

Behavior of the CommandAborted output<br />

CommandAborted is set if a command is interrupted through another block.<br />

Behavior of the Busy output<br />

The Busy output indicates that the function block is active. The block can only be triggered with a rising<br />

edge at Execute, if Busy is FALSE. Busy is immediately set with a rising edge at Execute and is only reset<br />

wh<strong>en</strong> the command was completed successful or unsuccessfully. As long as Busy is TRUE, the function<br />

block must be called cyclically for the command to be executed.<br />

Behavior of the Active output<br />

If the axis movem<strong>en</strong>t is controlled by several functions, the Active output of each block indicates that<br />

the axis executes the command. The status Busy=TRUE and Active=FALSE means that the command is<br />

not or no longer executed.<br />

Enable input and Valid output<br />

In contrast to Execute, the Enable input results in an action being executed perman<strong>en</strong>tly and repeatedly,<br />

as long as Enable is TRUE. MC_ReadStatus cyclically updates the status of an axis, for example, as long as<br />

Enable is TRUE. A function block with an Enable input indicates through the Valid output that the output<br />

data is good. The data is updated continuously while Valid is TRUE.<br />

308


Chapter: Camming<br />

BufferMode<br />

Some function blocks have a BufferMode input for controlling the command flow with several function<br />

blocks. For example, BufferMode can specify that a command interrupts another command (nonqueued<br />

mode) or that the following command is only executed after the previous command (queued<br />

mode). In queued mode BufferMode can be used to specify the movem<strong>en</strong>t transition from one<br />

command to the next. This is referred to as Bl<strong>en</strong>ding, which specifies the velocity at the transition point.<br />

In non-queued mode a subsequ<strong>en</strong>t command leads to termination of a running command. In this case<br />

the previous command sets the CommandAborted output. In queued mode a subsequ<strong>en</strong>t command<br />

waits until a running command is completed.<br />

Only one command is queued while another command is executed. If more than one command is<br />

triggered while a command is running, the command started last for queuing is rejected with an error. If<br />

the last command is started in non-queued mode (Aborting), it becomes active and interrupts the<br />

running and an already queued command.<br />

BufferModes<br />

Aborting : Default mode without buffering. The command is executed immediately and<br />

interrupts any other command that may be running.<br />

Buffered : The command is executed after no other command is running on the axis. The<br />

previous movem<strong>en</strong>t continues until it has stopped. The following command is started<br />

from standstill.<br />

Bl<strong>en</strong>dingLow : The command is executed after no other command is running on the axis. In<br />

contrast to Buffered the axis does not stop at the previous target, but passes through<br />

this position with the lower velocity of two commands.<br />

Bl<strong>en</strong>dingHigh : The command is executed after no other command is running on the axis. In<br />

contrast to Buffered the axis does not stop at the previous target, but passes through<br />

this position with the higher velocity of two commands.<br />

Bl<strong>en</strong>dingNext : The command is executed after no other command is running on the axis. In<br />

contrast to Buffered the axis does not stop at the previous target, but passes through<br />

this position with the velocity of the last command.<br />

Bl<strong>en</strong>dingPrevious: The command is executed after no other command is running on the axis. In<br />

contrast to Buffered the axis does not stop at the previous target, but passes through<br />

this position with the velocity of the first command.<br />

Options input<br />

Many function blocks have an Options input with a data structure containing additional, infrequ<strong>en</strong>tly<br />

required options. For the basic block function these options are oft<strong>en</strong> not required, so that the input can<br />

remain op<strong>en</strong>. The user only has to populate the Options data structure in cases where the<br />

docum<strong>en</strong>tation explicitly refers to certain options.<br />

Slave Axes<br />

Motion commands like MC_MoveAbsolute can be passed to slave axes if they are explicitly <strong>en</strong>abled in<br />

the axis parameters. A motion command will th<strong>en</strong> decouple the axis and move it afterwards. In this case<br />

just Buffer-Mode Aborting can be used.<br />

309


Chapter: Camming<br />

b. Migration from TcMC to TcMC2<br />

The main differ<strong>en</strong>ces and modifications betwe<strong>en</strong> the TcMC motion control library and the ext<strong>en</strong>ded<br />

TcMC2 library are listed here, so that the effort for converting an existing project can be estimated.<br />

Axis data structure<br />

In the past an axis required two data structures for cyclic data exchange with the NC.<br />

NcToPlc_Axis1 AT %I* : NCTOPLC_AXLESTRUCT;<br />

PlcToNc_Axis1 AT %Q* : PLCTONC_AXLESTRUCT;<br />

In most function blocks, including MC_MoveAbsolute, the NCTOPLC_AXLESTRUCT data structure was<br />

transferred at the Axis input. Certain function blocks, including MC_Power, expected an additional<br />

PLCTONC_AXLESTRUCT structure.<br />

In the TcMC2 <strong>en</strong>vironm<strong>en</strong>t the axis structure was ext<strong>en</strong>ded so that all required data are included in a<br />

single structure, which is transferred to each MC function block.<br />

Axis1: AXIS_REF;<br />

The structure contains the cyclic input and output data for the NC plus additional status information. An<br />

existing project g<strong>en</strong>erally accesses the cont<strong>en</strong>t of the NcToPlc structure. The data are also available in<br />

the Axis1 structure and can be used to adapt the application program.<br />

Example:<br />

TcMC :<br />

NcToPlc_Axis1.fPosSoll<br />

TcMC2 : Axis1.NcToPlc.SetPos<br />

Please note that the sub elem<strong>en</strong>ts for the NcToPlc and PlcToNc structures now have English names in<br />

view of the international market. For example, the curr<strong>en</strong>t set position for an axis is no longer referred<br />

to as fPosSoll, but as SetPos.<br />

310


Chapter: Camming<br />

Function blocks<br />

The input and output configuration of the function blocks has changed slightly compared with TcMC.<br />

The main new feature is support for MC_BufferMode in Move blocks. In addition, the blocks now also<br />

support a Busy and Active output. These modifications g<strong>en</strong>erally only require little migration effort. The<br />

following table contains a list of blocks with more ext<strong>en</strong>sive modifications.<br />

TcMC TcMC2 Remark<br />

MC_GearInFloat<br />

MC_NewPos<br />

MC_NewPosAndVelo<br />

MC_GearIn<br />

MC_Move...<br />

MC_GearIn now accepts the gear ratio as a floating point<br />

value<br />

The new BufferMode <strong>en</strong>ables each Move block to be used<br />

to assign a new target for the axis or change the velocity.<br />

The NewPos function blocks are therefore no longer<br />

required.<br />

MC_MoveAbsoluteOrRestart MC_Move...<br />

MoveAbsoluteOrRestart can be replaced with two<br />

instances of a Move block (see BufferMode).<br />

MC_CamIn<br />

MC_CamInExt<br />

MC_SetRefer<strong>en</strong>ceFlag<br />

MC_SetPositionOnTheFly<br />

MC_SetActualPosition<br />

MC_CamIn<br />

MC_Home<br />

MC_SetPosition<br />

MC_SetPosition<br />

The new MC_CamIn function block deals with the<br />

function of the ext<strong>en</strong>ded MC_CamInExt block. The input<br />

configuration was adapted accordingly.<br />

Setting and resetting of the refer<strong>en</strong>ce flag (axis is<br />

refer<strong>en</strong>ced) can be achieved with the MC_Home block.<br />

To set an axis position on the fly, MC_SetPosition can be<br />

used in relative mode (Mode=TRUE).<br />

MC_SetActualPosition can be replaced with<br />

MC_SetPosition. The new function block sets both, actual<br />

and set position.<br />

MC_GearOutExt<br />

MC_Move...<br />

Motion commands like MC_MoveAbsolute can be passed<br />

to slave axes if they are explicitly <strong>en</strong>abled in the axis<br />

parameters (from <strong>TwinCAT</strong> 2.11). A motion command<br />

will th<strong>en</strong> decouple the axis and move it afterwards. In this<br />

case just Buffer-Mode Aborting can be used.<br />

MC_Ori<strong>en</strong>tedStop MC_MoveModulo MC_MoveModulo can be executed from standstill or in<br />

motion. If started in motion, the block will behave like<br />

311


Chapter: Camming<br />

MC_Ori<strong>en</strong>tedStop<br />

MC_Stop<br />

MC_Halt,<br />

MC_Stop<br />

MC_Halt stops the axis in a normal operation cycle.<br />

MC_Stop is only used in a particular condition wh<strong>en</strong> the<br />

axis must be locked against further motion.<br />

TcNC library<br />

The previous TcMC library required declarations and functions from the TcNC library, so that this was<br />

always integrated in a project. The new TcMC2 library no longer has this dep<strong>en</strong>d<strong>en</strong>cy. All required<br />

declarations and functions are now included in TcMC2 library itself, so that the TcNC library is no longer<br />

required. Nevertheless, the TcNC library can still be used for compatibility reasons.<br />

312


Chapter: Camming<br />

c. Status information<br />

In existing motion applications axis status information was oft<strong>en</strong> determined via a function call<br />

(AxisHasJob(), AxisIsMoving() etc.). While these functions can still be used if the TcNC library is<br />

integrated, we now recomm<strong>en</strong>ded a differ<strong>en</strong>t approach:<br />

The complete status information for an axis is included in the above-m<strong>en</strong>tioned axis data structure<br />

Axis1:AXIS_REF. However, this data must be updated cyclically by calling the function block<br />

MC_ReadStatus or an Axis1.ReadStatus action at the start of the PLC cycle. Curr<strong>en</strong>t status information is<br />

th<strong>en</strong> available at any point in the program during the PLC cycle.<br />

313


Chapter: Camming<br />

36.Wh<strong>en</strong> to use a Cam Table<br />

a. Overview<br />

In many applications it is necessary to synchronize two or more axes. Axes can be coupled together in<br />

the <strong>TwinCAT</strong> NC PTP. A master axis is th<strong>en</strong> actively controlled, and the position of one or more coupled<br />

slave axes is synchronously controlled by the NC.<br />

The simplest type of coupling is linear coupling with a fixed ratio of transmission (an electronic gearbox).<br />

Some applications require a more complex coupling of master and slave, one which cannot be described<br />

by a simple mathematical formula. Such a dep<strong>en</strong>d<strong>en</strong>cy can be described by means of a table that<br />

specifies an associated slave position for every master position.<br />

The <strong>TwinCAT</strong> NC PTP offers the possibility of coupling a slave axis to a master axis by means of a table<br />

(electronic cam plate). Here the table contains a certain number of prescribed refer<strong>en</strong>ce points, and the<br />

NC interpolates position and speed betwe<strong>en</strong> them.<br />

The TcMC2_Camming library contains function blocks for handling cam plates. Two types of cam plates<br />

are supported.<br />

One option is a cam plate in the form of a 2-column table containing master and slave positions<br />

(standard table). The master column defines interpolation points via the travel path of the master,<br />

asc<strong>en</strong>ding from a minimum position value to a maximum value. The associated slave position is<br />

determined from the second column using the interpolation points of the table. Values betwe<strong>en</strong> these<br />

points are interpolated.<br />

Another option is to define a cam plate as a so-called motion function. A motion function is a singlecolumn<br />

table of interpolation points. Each interpolation point not only contains a position, but a<br />

complete description of the shape of the curve within a section (segm<strong>en</strong>t) of the cam plate. In addition<br />

to the master and slave position at the start of the segm<strong>en</strong>t, the shape of the function; for example, is<br />

specified up to the next interpolation point in the form of a mathematical function. Using this<br />

procedure, a motion function requires only very few interpolation points. Despite this, each point<br />

betwe<strong>en</strong> the interpolation points are precisely defined through the mathematical function, and there<br />

are no uncertainties due to interpolation.<br />

Unlike a standard table, the points of a motion function can be manipulated at run time. The system<br />

<strong>en</strong>sures that a manipulation only becomes effective once an alteration has no direct influ<strong>en</strong>ce on the<br />

slave. Position jumps are thus avoided.<br />

314


Chapter: Camming<br />

b. Gearing<br />

With a 1:1 gear Ratio the two axes will move the tooling at a 45 degree angle.<br />

With a 3.6:1 gear ratio the axes will move the tooling in a diagonal line as se<strong>en</strong> below.<br />

315


Chapter: Camming<br />

c. Linearly Increasing Gear Ratio (Dynamic)<br />

Dynamically changing the gear ratio by a fixed increm<strong>en</strong>t each PLC cycle will create a curve. The math<br />

for any other curve is long and complicated.<br />

The key behind the cam table is that it is used wh<strong>en</strong> the slave position relative to the master position is<br />

critical. For example if at 360 degrees both slave and master must be at 360 degrees, but wh<strong>en</strong> the<br />

master reaches 720 the slave must be at 1080. This can be accomplished by having the gear ratio<br />

doubled, but it is Time dep<strong>en</strong>dant and if the gear ratio is not changed at exactly the right time for<br />

correct l<strong>en</strong>gth of time the proper position cannot be reached. So gearing works well for linear changes<br />

but not arbitrary changes. The cam table allows you to specify any point for the slave to be at any<br />

position of the master, the mathematics of the cam table allow you to make the transition from one<br />

point to the next as smooth as possible while guaranteeing that the slave will be at the specified point<br />

wh<strong>en</strong> the master reaches its predefined position.<br />

Linear and fixed gear ratios are no problem but determining a position based on adjusting the gear ratio<br />

is time dep<strong>en</strong>dant and time is not necessarily under the control of the programmer, if the ratio is<br />

changed too early or too late the target position will not be reached.<br />

316


Chapter: Camming<br />

d. Cam Table<br />

With a Cam Table, Slave positions can be defined in the forward direction of the Master and <strong>TwinCAT</strong><br />

will do the math for you.<br />

Cam tables can be made cyclical so that they repeat, typically a rotary axis will be the master and after<br />

every 360 degrees of the Master the Cam Table will repeat.<br />

In the below graph the Master is moving along the X-Axis from left to right. The Slave is moving along<br />

the Y-Axis from bottom to top. As the Master position increases from 0 to 100 the Slave axis moves<br />

from 0 to 100, and th<strong>en</strong> as the Master continues towards 360 the slave will return to 0 and hold that<br />

position until the next revolution of the Master. If only the points are defined on the table th<strong>en</strong><br />

<strong>TwinCAT</strong> will calculate a straight line from one point to the next. If Motion Functions are used th<strong>en</strong><br />

<strong>TwinCAT</strong> will use the VDI 2143 Motion Function standard to calculate a curve betwe<strong>en</strong> the points.<br />

Typically Polynomial 5 will be used. If a differ<strong>en</strong>t curve is desired th<strong>en</strong> the Cam Table can be setup to<br />

use a differ<strong>en</strong>t motion function to calculate the path from one point to another. Additionally the type of<br />

points can be selected; these include Rest, Velocity, Return, and Movem<strong>en</strong>t.<br />

317


Chapter: Camming<br />

37.Creating a Cam Table with Function Blocks<br />

Prerequisites:<br />

<strong>TwinCAT</strong> NC PTP 2.10 Build 1340 or Higher<br />

TcMC2_Camming.lib (From the <strong>TwinCAT</strong> NC Camming Supplem<strong>en</strong>t)<br />

a. Overview<br />

By the use of the TcMC2_Camming library a cam table can be created, implem<strong>en</strong>ted, adjusted, and used<br />

directly from the PLC. Motion Function Points define the points on the table and the associated Motion<br />

Function to be used with that point. The refer<strong>en</strong>ce to the Cam Table by use of a pointer is created to<br />

define the starting memory location and size of the Cam Table. Additionally the table type must be<br />

defined. Each Cam Table will have a unique TableID from 1 to 255. This table ID will be used by the<br />

programmer to refer<strong>en</strong>ce the Cam Table wh<strong>en</strong> creating and/or selecting it for use. The use of the CamIn<br />

procedure will couple the slave axis to the master axis with the giv<strong>en</strong> TableID as a refer<strong>en</strong>ce. In order to<br />

provide more flexibility, the individual points; and the properties of those points, on the Cam Table can<br />

be adjusted after the coupling has be<strong>en</strong> performed. The mode in which the Cam Table is to be activated<br />

is also selectable.<br />

b. Defining the Points on the Cam Table<br />

i. Motion Function Point<br />

A motion function point describes a start point of a motion function. The description includes<br />

the point itself, a definition of the function type and a relative pointer to the <strong>en</strong>d point of the motion<br />

function segm<strong>en</strong>t.<br />

The data structure MC_MotionFunctionPoint describes an interpolation point of a motion function. A<br />

motion function is a one-dim<strong>en</strong>sional list (array) of type MC_MotionFunctionPoint.<br />

TYPE MC_MotionFunctionPoint :<br />

STRUCT<br />

PointIndex<br />

: MC_MotionFunctionPoint_ID;<br />

FunctionType : MC_MotionFunctionType;<br />

PointType<br />

: MC_MotionPointType;<br />

RelIndexNextPoint : MC_MotionFunctionPoint_ID;<br />

MasterPos : LREAL; (* X *)<br />

SlavePos : LREAL; (* Y *)<br />

SlaveVelo : LREAL; (* Y' *)<br />

SlaveAcc : LREAL; (* Y'' *)<br />

SlaveJerk : LREAL; (* Y''' *)<br />

END_STRUCT<br />

END_TYPE<br />

318


Chapter: Camming<br />

PointIndex: Absolute index of this interpolation point within the motion function. The point index of all<br />

interpolation points must increase strictly monotonously and must have no gaps and be greater than 0.<br />

Notes: The first point in a list must start AT any index > 0. All following points in the list add 1 to the<br />

PointIndex. MC_MotionFunctionPoint_ID is of type UDINT.<br />

FunctionType: Type definition for motion functions. Type MC_MotionFunctionType of the mathematical<br />

function betwe<strong>en</strong> this and the subsequ<strong>en</strong>t interpolation point.<br />

Notes: The type Automatic motion function type used in the <strong>TwinCAT</strong> Cam Design Editor corresponds to<br />

MOTIONFUNCTYPE_POLYNOM5_MM.<br />

TYPE MC_MotionFunctionType :<br />

( MOTIONFUNCTYPE_NOTDEF,<br />

MOTIONFUNCTYPE_POLYNOM1 := 1, (* 1: polynom with order 1 *)<br />

MOTIONFUNCTYPE_POLYNOM3 := 3, (* 3: polynom with order 3 (rest rest) *)<br />

MOTIONFUNCTYPE_POLYNOM5 := 5, (* 5: polynom with order 5 (rest rest) *)<br />

MOTIONFUNCTYPE_POLYNOM5_MM := 15, (* 15: polynom with order 5 (motion motion) *)<br />

MOTIONFUNCTYPE_BESCHLTRAPEZ_RT := 22, (* 22: acceleration trapezoid (rest turn) *));<br />

END_TYPE<br />

PointType: Type MC_MotionPointType of this interpolation point.<br />

TYPE MC_MotionFunctionPoint:<br />

( MOTIONPOINTTYPE_IGNORE, (* Ignore point *)<br />

MOTIONPOINTTYPE_REST := 16#0001, (* Rest point *)<br />

MOTIONPOINTTYPE_VELOCITY := 16#0002, (* Velocity point *)<br />

MOTIONPOINTTYPE_TURN := 16#0004, (* Turn point *)<br />

MOTIONPOINTTYPE_MOTION := 16#0008, (* Motion point *)<br />

MOTIONPOINTTYPE_ADD := 16#0F00, (* Adding of segm<strong>en</strong>ts *)<br />

MOTIONPOINTTYPE_ACTIVATION := 16#2000 (* 1: activation point *));<br />

END_TYPE<br />

RelIndexNextPoint: Relative refer<strong>en</strong>ce to the subsequ<strong>en</strong>t interpolation point (usually 1).<br />

319


Chapter: Camming<br />

ii. Sample Code:<br />

Below is a really bad graphical repres<strong>en</strong>tation of the Points on the Cam Table below.<br />

Point3 Point4<br />

X--------X<br />

/ \<br />

/ \<br />

/ \<br />

/ \<br />

------X--------X<br />

X-------------X<br />

Point1 Point2 Point5 Point6<br />

(*Point 1*)<br />

VM_MotionFunctionPoints[1].PointIndex := 1;<br />

VM_MotionFunctionPoints[1].FunctionType := 15;<br />

(*MOTIONFUNCTYPE_POLYNOM5_MM*)<br />

VM_MotionFunctionPoints[1].PointType := 1;<br />

(*MOTIONPOINTTYPE_REST*)<br />

VM_MotionFunctionPoints[1].RelIndexNextPoint := 1;<br />

(*1 = Increm<strong>en</strong>t PointIndex by 1 to get to Next Point, must be 0 for the last point on the table*)<br />

VM_MotionFunctionPoints[1].MasterPos := 0;<br />

VM_MotionFunctionPoints[1].SlavePos := 0;<br />

(*Point 2*)<br />

VM_MotionFunctionPoints[2].PointIndex := 2;<br />

VM_MotionFunctionPoints[2].FunctionType := 15;<br />

VM_MotionFunctionPoints[2].PointType := 1;<br />

VM_MotionFunctionPoints[2].RelIndexNextPoint := 1;<br />

VM_MotionFunctionPoints[2].MasterPos := 30;<br />

VM_MotionFunctionPoints[2].SlavePos := 0;<br />

(*Point 3*)<br />

VM_MotionFunctionPoints[3].PointIndex := 3;<br />

VM_MotionFunctionPoints[3].FunctionType := 15;<br />

VM_MotionFunctionPoints[3].PointType := 1;<br />

VM_MotionFunctionPoints[3].RelIndexNextPoint := 1;<br />

VM_MotionFunctionPoints[3].MasterPos := 45;<br />

VM_MotionFunctionPoints[3].SlavePos := 150;<br />

(*Point 4*)<br />

VM_MotionFunctionPoints[4].PointIndex := 4;<br />

VM_MotionFunctionPoints[4].FunctionType := 15;<br />

VM_MotionFunctionPoints[4].PointType := 1;<br />

VM_MotionFunctionPoints[4].RelIndexNextPoint := 1;<br />

VM_MotionFunctionPoints[4].MasterPos := 60;<br />

VM_MotionFunctionPoints[4].SlavePos := 150;<br />

320


Chapter: Camming<br />

(*Point 5*)<br />

VM_MotionFunctionPoints[5].PointIndex := 5;<br />

VM_MotionFunctionPoints[5].FunctionType := 15;<br />

VM_MotionFunctionPoints[5].PointType := 1;<br />

VM_MotionFunctionPoints[5].RelIndexNextPoint := 1;<br />

VM_MotionFunctionPoints[5].MasterPos := 75;<br />

VM_MotionFunctionPoints[5].SlavePos := 0;<br />

(*Point 6*)<br />

VM_MotionFunctionPoints[6].PointIndex := 6;<br />

VM_MotionFunctionPoints[6].FunctionType := 15;<br />

VM_MotionFunctionPoints[6].PointType := 1;<br />

VM_MotionFunctionPoints[6].RelIndexNextPoint := 0;<br />

VM_MotionFunctionPoints[6].MasterPos := 360;<br />

VM_MotionFunctionPoints[6].SlavePos := 0;<br />

321


Chapter: Camming<br />

38.Defining the Cam Table in the PLC<br />

a. Overview<br />

Within the PLC a Cam Table can be defined by providing a starting memory location, size, and table type.<br />

TYPE MC_CAM_REF :<br />

STRUCT<br />

pArray<br />

ArraySize<br />

TableType<br />

b. MC_CAM_REF<br />

: UDINT;<br />

: UDINT;<br />

: MC_TableType;<br />

: UDINT;<br />

NoOfRows<br />

NoOfColumns : UDINT;<br />

END_STRUCT<br />

END_TYPE<br />

The data structure MC_CAM_REF describes the data memory of a cam plate in a further PLC variable<br />

(array).<br />

The first parameter pArray is a pointer to a data structure containing the cam plate data. The data<br />

structure dep<strong>en</strong>ds on the table type TableType. The number of rows is <strong>en</strong>tered in the compon<strong>en</strong>t<br />

NoOfRows, the number of columns in NoOfCols (usually 1 or 2).<br />

i. Example 1: Position table structure description<br />

pArray: Address of a two-dim<strong>en</strong>sional array. The first column contains an asc<strong>en</strong>ding list of master<br />

positions. The second column contains the associated slave positions. The address can be assigned with<br />

the ADR function.<br />

Example:<br />

Table1 : ARRAY[0..360, 0..1] OF LREAL;<br />

pArray := ADR( Table1 );<br />

ArraySize : Storage capacity of the two-dim<strong>en</strong>sional array, which can be determined with the SIZEOF<br />

function.<br />

Example:<br />

ArraySize := SIZEOF( Table1 );<br />

TableType: The table type is MC_TABLETYPE_EQUIDISTANT, if the master positions have the same<br />

distance, or MC_TABLETYPE_NONEQUIDISTANT it the distance is variable.<br />

NoOfRows: The number or rows corresponds to the number of table points.<br />

NoOfColumns: The number of columns is 2.<br />

322


Chapter: Camming<br />

ii. Example 2: Structure description of a motion function<br />

pArray: Address of a two-dim<strong>en</strong>sional array. The first column contains an asc<strong>en</strong>ding list of master<br />

positions. The second column contains the associated slave positions. The address can be assigned with<br />

the ADR function.<br />

Example:<br />

Table1 : ARRAY[0..360, 0..1] OF LREAL;<br />

pArray := ADR( Table1 );<br />

ArraySize : Storage capacity of the one-dim<strong>en</strong>sional array, which can be determined with the SIZEOF<br />

function.<br />

Example:<br />

ArraySize := SIZEOF( MotionFunction );<br />

TableType: The table type is MC_TABLETYPE_MOTIONFUNCTION.<br />

NoOfRows: The number or rows corresponds to the number of table points.<br />

NoOfColumns: The number of columns is 1.<br />

323


Chapter: Camming<br />

c. MC_TableType<br />

TYPE MC_TableType :<br />

((* n*m tabular with equidistant asc<strong>en</strong>ding master values *)<br />

MC_TABLETYPE_EQUIDISTANT := 10,<br />

(* n*m tabular with strictly monotone asc<strong>en</strong>ding master values (not imperative equidistant) *)<br />

MC_TABLETYPE_NONEQUIDISTANT := 11,<br />

(* motion function calculated in runtime *)<br />

MC_TABLETYPE_MOTIONFUNCTION := 22 );<br />

END_TYPE<br />

(*Cam Table Data*)<br />

i. Sample Code:<br />

VM_MotionFunctionPoints : ARRAY [1..6] OF MC_MotionFunctionPoint;<br />

(*The size of the Array determines the number of points in the Cam Table*)<br />

CamTable_Slave : MC_Cam_Ref;<br />

(*MC_Cam_Ref contains the location, size, and type of the Cam Table*)<br />

(*Provide MC_Cam_Ref with the data of the CAM Table*)<br />

CamTable_Slave.pArray := ADR(VM_MotionFunctionPoints);<br />

CamTable_Slave.ArraySize := SIZEOF(VM_MotionFunctionPoints);<br />

CamTable_Slave.TableType := MC_TABLETYPE_MOTIONFUNCTION;<br />

CamTable_Slave.NoOfRows := 6;<br />

CamTable_Slave.NoOfColumns := 1;<br />

324


Chapter: Camming<br />

39.Creating the Cam Table<br />

a. Overview<br />

The Cam Table Select block <strong>en</strong>ables the programmer to create a Cam Table by providing the Master and<br />

Slave axes along with the ID of the Cam Table to be used, and the refer<strong>en</strong>ce to the Cam Table.<br />

b. MC_CamTableSelect<br />

With the function block MC_CamTableSelect, a table can be specified and loaded into the NC. The block<br />

creates a new table and simultaneously fills it with data provided by the PLC.<br />

MC_CamTableSelect does not have to be used, if a table created with the <strong>TwinCAT</strong> cam plate editor is to<br />

be used. In this case, simple coupling with MC_CamIn is suffici<strong>en</strong>t.<br />

Inputs<br />

Execute: The command is executed with a rising edge at input Execute.<br />

Periodic: Periodic is TRUE if the cam plate is repeatedly cyclically.<br />

MasterAbsolute: Absolute interpretation of master positions.<br />

SlaveAbsolute: Absolute interpretation of slave positions.<br />

CamTableID: ID of the cam plate used for coupling.<br />

Outputs<br />

Done: becomes TRUE, if the cam plate was created successfully.<br />

Busy: The Busy output becomes TRUE wh<strong>en</strong> the command is started with Execute and remains TRUE as<br />

long as the command is processed. Wh<strong>en</strong> Busy becomes FALSE again, the function block is ready for a<br />

new command. At the same time one of the outputs, Done or Error, is set.<br />

Error: Becomes TRUE, as soon as an error occurs.<br />

ErrorID: If the error output is set, this parameter supplies the error number.<br />

Input/Outputs<br />

Master: Axis data structure of the master<br />

Slave: Axis data structure of the slave<br />

CamTable: The data structure of type MC_CAM_REF describes the data storage for the cam plate in the<br />

PLC.<br />

325


Chapter: Camming<br />

i. Sample Code:<br />

(*Axes*)<br />

VM : Axis_Ref;<br />

Slave : Axis_Ref;<br />

(*Triggers*)<br />

bCamTableSel1 : BOOL; (*MC_CamTableSelect*)<br />

(*FB Error Info*)<br />

bErrorCamCreate : BOOL;<br />

iErrorIDCamCreate : UDINT;<br />

fbMC_CamTableSelect1 : MC_CamTableSelect;<br />

(*Create the Cam Table*)<br />

fbMC_CamTableSelect1(<br />

Execute:= bCamTableSel1,<br />

Periodic:= TRUE,<br />

MasterAbsolute:=TRUE ,<br />

SlaveAbsolute:=TRUE ,<br />

CamTableID:=1 ,<br />

Master:=VM ,<br />

Slave:=Slave ,<br />

CamTable:=CamTable_Slave ,<br />

Done=> ,<br />

Busy=> ,<br />

Error=>bErrorCamCreate ,<br />

ErrorID=>iErrorIDCamCreate );<br />

326


Chapter: Camming<br />

40.Importing a Cam Table for Verification<br />

a. Overview<br />

Without a lic<strong>en</strong>se for the <strong>TwinCAT</strong> Cam Design Tool, the Cam Table created by the PLC can be viewed<br />

but changes will not be saved. Once the Cam Table has be<strong>en</strong> uploaded changes can be made to tweak<br />

the table, and th<strong>en</strong> corresponding changes can be made to the PLC code.<br />

b. Creating a Blank Table<br />

Under the NC-Configuration, right click on Tables and select App<strong>en</strong>d Table…<br />

Leave the defaults and select OK.<br />

327


Chapter: Camming<br />

If you do not have a lic<strong>en</strong>se for the Cam Design Tool you will receive the following message. Select OK.<br />

Right click on Master 1 and select App<strong>en</strong>d Slave…<br />

Leave the defaults and select OK.<br />

328


Chapter: Camming<br />

You should now see an empty Cam Table.<br />

329


Chapter: Camming<br />

c. Importing the Cam Table<br />

On the Slave Tab verify that the Table ID matches the Table ID used in the PLC program.<br />

If it does not match th<strong>en</strong> right click on the Slave and select Change ID.<br />

330


Chapter: Camming<br />

Change the ID: and select OK.<br />

After verifying the Table ID, select Upload.<br />

Leave the defaults and select OK.<br />

331


Chapter: Camming<br />

Your Cam Table should now look like the following.<br />

332


Chapter: Camming<br />

41.Camming the two Axes together<br />

a. Overview<br />

Once the Cam Table has be<strong>en</strong> defined, verified, and created; the two axes are now ready to be cammed<br />

together.<br />

b. MC_CamIn<br />

The function block MC_CamIn activates master-slave coupling with a certain cam plate. In addition it is<br />

possible to switch to a new cam plate in coupled state. The switching rules, in particular the time or<br />

position, can be specified.<br />

The status flag Axis.Status.CamTableQueued can be used to check whether a cam plate is queued for<br />

switchover.<br />

Inputs<br />

VAR_INPUT<br />

Execute :<br />

BOOL;<br />

MasterOffset : LREAL;<br />

SlaveOffset : LREAL;<br />

MasterScaling : LREAL := 1.0;<br />

SlaveScaling : LREAL := 1.0;<br />

StartMode : MC_StartMode;<br />

CamTableID : MC_CAM_ID;<br />

BufferMode : MC_BufferMode;<br />

Options : ST_CamInOptions;<br />

END_VAR<br />

Execute: The command is executed with a rising edge at input Execute<br />

MasterOffset: Offset to the master position of the cam plate<br />

SlaveOffset: Offset to the slave position of the cam plate<br />

MasterScaling: Scaling of the master position of the cam plate<br />

StartMode: StartMode determines whether the cam plate position is interpreted absolute or relative to<br />

the coupling position.<br />

StartMode can be relative or absolute for master (X coordinate) and slave (Y coordinate).<br />

333


Chapter: Camming<br />

CamTableID: ID of the cam plate used for coupling<br />

BufferMode: curr<strong>en</strong>tly not implem<strong>en</strong>ted<br />

Options: Data structure with further coupling and switching options:<br />

ActivationMode: ActivationMode specifies the switching time or position at which cam plate<br />

coupling or switchover takes place.<br />

ActivationMode can also be specified wh<strong>en</strong> a slave is coupled for the first time.<br />

ActivationPosition: Optional master position at which a cam plate is switched, dep<strong>en</strong>ding on the<br />

ActivationMode.<br />

(not required for first coupling.)<br />

If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used, the position refers to the<br />

non-scaled cam plate. If the position in the application refers to the scaled cam plate, it can be<br />

divided by the MasterScaling before the function block is called.<br />

MasterScalingMode: Optional Scaling mode for the master position of the cam plate<br />

SlaveScalingMode: Optional Scaling mode for the Slave position of the cam plate<br />

InterpolationType: Interpolation type for position tables. Not required for motion functions<br />

Outputs<br />

VAR_OUTPUT<br />

InSync :<br />

BOOL;<br />

Busy :<br />

BOOL;<br />

Active :<br />

BOOL;<br />

CommandAborted : BOOL;<br />

Error :<br />

BOOL;<br />

ErrorID : UDINT;<br />

END_VAR<br />

InSync: Becomes TRUE, if the coupling was successful and the cam plate is active.<br />

Busy: The Busy output becomes TRUE wh<strong>en</strong> the command is started with Execute and remains TRUE as<br />

long as the command is processed. Wh<strong>en</strong> Busy becomes FALSE again, the function block is ready for a<br />

new command. At the same time one of the outputs, InSync, CommandAborted or Error, is set.<br />

Active: Active indicates that the command is executed. For cam plate switching Active becomes TRUE, if<br />

the coupling command was executed successfully but the cam plate is still queued. If the cam plate is<br />

activated dep<strong>en</strong>ding on the ActivationMode, Active becomes FALSE and InSync is set.<br />

CommandAborted: Becomes TRUE, if the command could not be fully executed. The axis may have<br />

become decoupled during the coupling process (simultaneous command execution).<br />

Error: Becomes TRUE, as soon as an error occurs.<br />

ErrorID: If the error output is set, this parameter supplies the error number.<br />

Inputs/outputs<br />

VAR_IN_OUT<br />

Master : AXIS_REF;<br />

Slave : AXIS_REF;<br />

END_VAR<br />

334


Chapter: Camming<br />

i. Sample Code:<br />

(*Couple the Axes using the Cam Table*)<br />

fbMC_CamInSlave(<br />

Execute:=bExectueCamInSlave ,<br />

MasterOffset:= ,<br />

SlaveOffset:= ,<br />

MasterScaling:= ,<br />

SlaveScaling:= ,<br />

StartMode:=MC_STARTMODE_ABSOLUTE ,<br />

CamTableID:=1 ,<br />

BufferMode:= ,<br />

Options:= ,<br />

Master:=VM ,<br />

Slave:= Slave,<br />

InSync=> ,<br />

Busy=> ,<br />

Active=> ,<br />

CommandAborted=> ,<br />

Error=>bErrorCamIn ,<br />

ErrorID=>iErrorIDCamIn );<br />

335


Chapter: Camming<br />

42.Changing a table point via the PLC<br />

a. Overview<br />

While the Cam Table is in operation it may be necessary to adjust the location and/or properties of the<br />

points. Although the point before and after the curr<strong>en</strong>t Slave position cannot be adjusted every other<br />

point can be. The way the change is to be implem<strong>en</strong>ted can also be defined.<br />

b. MC_WriteMotionFunctionPoint<br />

The function block MC_WriteMotionFunctionPoint can be used to write the data of a motion function<br />

interpolation point.<br />

Inputs<br />

VAR_INPUT<br />

Execute<br />

CamTableID<br />

PointID<br />

END_VAR<br />

: BOOL;<br />

: MC_CAM_ID;<br />

: MC_MotionFunctionPoint_ID;<br />

Execute: The command is executed with rising edge.<br />

CamTableID: ID of the loaded table.<br />

PointID: Point ID of the first point of the motion function to be read.<br />

Outputs<br />

VAR_OUTPUT<br />

Done<br />

Busy<br />

Error<br />

ErrorID<br />

END_VAR<br />

: BOOL;<br />

: BOOL;<br />

: BOOL;<br />

: UDINT;<br />

Done: Becomes TRUE, if the data were writt<strong>en</strong> successfully.<br />

Busy: The Busy output becomes TRUE wh<strong>en</strong> the command is started with Execute and remains TRUE as<br />

long as the command is processed. Wh<strong>en</strong> Busy becomes FALSE again, the function block is ready for a<br />

new command. At the same time one of the outputs, Done or Error, is set.<br />

Error: Becomes TRUE, as soon as an error occurs.<br />

ErrorID: If the error output is set, this parameter supplies the error number<br />

Inputs/Outputs<br />

VAR_IN_OUT<br />

Point : MC_MotionFunctionPoint;<br />

END_VAR<br />

336


Chapter: Camming<br />

Point: Data structure containing the data of a motion function interpolation point<br />

Motion Function Point: Refer to Creating a Cam Table with Function Blocks<br />

c. MC_SetCamOnlineChangeMode<br />

The function block MC_SetCamOnlineChangeMode specifies the mode for write access to cam plate<br />

data. The function block can also be used to specify wh<strong>en</strong> the data is read into the cam plate. If<br />

activation of the data is to be delayed until the master reaches a certain position, the system will initially<br />

queue the writt<strong>en</strong> data and activate them at the master position.<br />

The status flag Axis.Status.CamDataQueued can be used to check whether data has be<strong>en</strong> queued (i.e.<br />

writt<strong>en</strong> but not yet activated).<br />

Cam plate can be modified at run time via the PLC (see MC_WriteMotionFunction,<br />

MC_WriteMotionFunctionPoint). The function block MC_SetCamOnlineChangeMode is used to specify<br />

wh<strong>en</strong> and how these changes take effect. The set mode affects all subsequ<strong>en</strong>t write operations. It is<br />

therefore not necessary to call the block before each write access.<br />

This function specifies the activation mode for modifications but does not affect a change or changeover<br />

of cam plates.<br />

Inputs<br />

VAR_INPUT<br />

Execute<br />

ActivationMode<br />

ActivationPosition<br />

MasterScalingMode<br />

SlaveScalingMode<br />

CamTableID<br />

END_VAR<br />

: BOOL;<br />

: MC_CamActivationMode;<br />

: LREAL;<br />

: MC_CamScalingMode;<br />

: MC_CamScalingMode;<br />

: MC_CAM_ID;<br />

Execute: The command is executed with rising edge.<br />

ActivationMode: Defines wh<strong>en</strong> and how scaling takes place. (MC_CamActivationMode)<br />

ActivationPosition: Optional master position at which scaling is carried out (dep<strong>en</strong>ding on<br />

ActivationMode). If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used, the position<br />

refers to the non-scaled cam plate. If the position in the application refers to the scaled cam plate, it can<br />

be divided by the MasterScaling before the function block is called.<br />

337


Chapter: Camming<br />

MasterScalingMode: Type of master scaling. (MC_CamScalingMode)<br />

SlaveScalingMode: Type of slave scaling. (MC_CamScalingMode)<br />

CamTableID: Table ID.<br />

Outputs<br />

VAR_OUTPUT<br />

Done<br />

Busy<br />

Error<br />

ErrorID<br />

END_VAR<br />

: BOOL;<br />

: BOOL;<br />

: BOOL;<br />

: UDINT;<br />

Done: Becomes TRUE, if the data were writt<strong>en</strong> successfully.<br />

Busy: The Busy output becomes TRUE wh<strong>en</strong> the command is started with Execute and remains TRUE as<br />

long as the command is processed. Wh<strong>en</strong> Busy becomes FALSE again, the function block is ready for a<br />

new command. At the same time one of the outputs, Done or Error, is set.<br />

Error: Becomes TRUE, as soon as an error occurs.<br />

ErrorID: If the error output is set, this parameter supplies the error number<br />

338


Chapter: Camming<br />

d. MC_CamActivationMode<br />

TYPE MC_CamActivationMode :<br />

(<br />

MC_CAMACTIVATION_INSTANTANEOUS, (* instantaneous change *)<br />

MC_CAMACTIVATION_ATMASTERCAMPOS, (* modify the data at a defined master position referring<br />

to the cam tables master position *)<br />

MC_CAMACTIVATION_ATMASTERAXISPOS, (* modify the data at a defined master position referring<br />

to the absolute master axis position *)<br />

MC_CAMACTIVATION_NEXTCYCLE, (* modify the data at the beginning of the next cam table<br />

cycle *)<br />

MC_CAMACTIVATION_NEXTCYCLEONCE, (* Not Yet Implem<strong>en</strong>ted! Modify the data at the beginning<br />

of the next cam table cycle, activation is valid for one cycle only *)<br />

MC_CAMACTIVATION_ASSOONASPOSSIBLE, (* modify the data as soon as the cam table is in a safe<br />

state to change its data *)<br />

MC_CAMACTIVATION_OFF, (* don't accept any modification *)<br />

MC_CAMACTIVATION_DELETEQUEUEDDATA (* delete all data which was writt<strong>en</strong> to modify the cam<br />

table but is still not activated *)<br />

);<br />

END_TYPE<br />

MC_CamActivationMode specifies the timing and type of change for a cam plate. Changes can be<br />

affected through scaling, modification of the cam plate data, or switching of cam plates.<br />

The following modes are possible:<br />

MC_SetCamOnlineChangeMode is used to specify wh<strong>en</strong> modified cam plate data become active (see<br />

also MC_WriteMotionFunction and MC_WriteMotionFunctionPoint).<br />

In both cases the following modes are possible:<br />

MC_CAMACTIVATION_INSTANTANEOUS: The change takes effect immediately.<br />

MC_CAMACTIVATION_ATMASTERCAMPOS: The change takes effect at a certain cam plate position<br />

(master position within the cam plate). The command must be issued ahead of this position.<br />

The position refers to the non-scaled cam plate. If the position in the application refers to the scaled<br />

cam plate, it can be divided by the MasterScaling before the function block is called.<br />

MC_CAMACTIVATION_ATMASTERAXISPOS: The change takes effect at a certain absolute position of<br />

the master axis. The command must be issued ahead of this position.<br />

MC_CAMACTIVATION_NEXTCYCLE: For a cyclic cam plate, the change takes effect at the transition to<br />

the next period.<br />

MC_CAMACTIVATION_ASSOONASPOSSIBLE: Modified cam plate data take effect as soon as system<br />

dynamics allow.<br />

MC_CAMACTIVATION_OFF: Changes in cam plate data are ignored.<br />

MC_CAMACTIVATION_DELETEQUEUEDDATA : Queued cam plate data are deleted. Data are queued if<br />

the change was requested at a certain master position or at the <strong>en</strong>d of the cycle, for example.<br />

339


Chapter: Camming<br />

i. Sample Code:<br />

(*New data for point 5 of the Cam Table*)<br />

VM_MotionFunctionPoints[5].PointIndex := 5;<br />

VM_MotionFunctionPoints[5].FunctionType := 15;<br />

VM_MotionFunctionPoints[5].PointType := 1;<br />

VM_MotionFunctionPoints[5].RelIndexNextPoint := 1;<br />

VM_MotionFunctionPoints[5].MasterPos := 75;<br />

VM_MotionFunctionPoints[5].SlavePos := 75;<br />

(*Buffer the Data for Point 5*)<br />

fbMC_WriteMotionFunctionPoint5_1st(<br />

Execute:=TRUE ,<br />

CamTableID:=1 ,<br />

PointID:=5 ,<br />

Point:=VM_MotionFunctionPoints[5] ,<br />

Done=> ,<br />

Busy=> ,<br />

Error=>bErrorWritePoint_1st ,<br />

ErrorID=>iErrorIDWritePoint_1st );<br />

(*Use new Data for Point 5*)<br />

fbMC_SetCamOnlineChangeModeTable1_1st(<br />

Execute:= TRUE ,<br />

ActivationMode:=MC_CAMACTIVATION_ATMASTERAXISPOS ,<br />

ActivationPosition:=370 ,<br />

MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET ,<br />

SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET ,<br />

CamTableID:=1 ,<br />

Done=> ,<br />

Busy=> ,<br />

Error=> bErrorChangeMode_1st,<br />

ErrorID=>iErrorIDChangeMode_1st );<br />

340


Chapter: Camming<br />

(*New data for point 5 of the Cam Table*)<br />

VM_MotionFunctionPoints[5].PointIndex := 5;<br />

VM_MotionFunctionPoints[5].FunctionType := 15;<br />

VM_MotionFunctionPoints[5].PointType := 1;<br />

VM_MotionFunctionPoints[5].RelIndexNextPoint := 1;<br />

VM_MotionFunctionPoints[5].MasterPos := 75;<br />

VM_MotionFunctionPoints[5].SlavePos := 0;<br />

(*Buffer the Data for Point 5*)<br />

fbMC_WriteMotionFunctionPoint5_2nd(<br />

Execute:=TRUE ,<br />

CamTableID:=1 ,<br />

PointID:=5 ,<br />

Point:=VM_MotionFunctionPoints[5] ,<br />

Done=> ,<br />

Busy=> ,<br />

Error=>bErrorWritePoint_2nd ,<br />

ErrorID=>iErrorIDWritePoint_2nd );<br />

(*Use new Data for Point 5*)<br />

fbMC_SetCamOnlineChangeModeTable1_2nd(<br />

Execute:= TRUE ,<br />

ActivationMode:=MC_CAMACTIVATION_ATMASTERAXISPOS ,<br />

ActivationPosition:=730 ,<br />

MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET ,<br />

SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET ,<br />

CamTableID:=1 ,<br />

Done=> ,<br />

Busy=> ,<br />

Error=> bErrorChangeMode_2nd,<br />

ErrorID=>iErrorIDChangeMode_2nd );<br />

341


Chapter: Camming<br />

43.Motion Functions vs. Position Tables<br />

a. Position Tables<br />

G<strong>en</strong>eral Table Conv<strong>en</strong>tions<br />

Tables only contain binary data. Table can be read from an ASCII file but you have to parse the file.<br />

A table consists of a header (the first line) and the table data (the remaining lines).<br />

The header contains two numbers of type unsigned short. The first column contains the number of lines<br />

(without header), while the second column contains the number of columns (for table-slave tables this is<br />

always 2). There are no separating characters betwe<strong>en</strong> the data.<br />

Apart from the header, the table only contains data of type double.<br />

The first column (with the exception of the header line) contains the master positions, while the second<br />

column contains the associated slave positions (both in mm). There are no separating characters<br />

betwe<strong>en</strong> the data.<br />

The quantity of data is restricted to 64 KB (<strong>TwinCAT</strong> Version 2.6). (This might be greater in newer<br />

versions)<br />

A position table is a 2D array that provides a slave position relative to the master position. The<br />

downside of a position table is that the segm<strong>en</strong>ts betwe<strong>en</strong> defined points are calculated in a straight line<br />

betwe<strong>en</strong> the points. Therefore the more points on the table the shorter the segm<strong>en</strong>ts and the better<br />

the motion. Most 2D tables contain at least 1000 points and are commonly g<strong>en</strong>erated by 3 rd party<br />

software using a mathematical formula (similar to a motion function) to create a table of 1000+ points.<br />

342


Chapter: Camming<br />

Below are the points g<strong>en</strong>erated by using Motion Functions from our above sample code. The values<br />

highlighted in yellow are the master. The values highlighted in red are the defined points. If this was a<br />

table of points the Slave axis values would increase linearly.<br />

343


Chapter: Camming<br />

b. Motion Functions<br />

A motion function (MF) describes a cam disc via mathematical functions. It sub-divides the curve into<br />

appropriate segm<strong>en</strong>ts (sections), for which differ<strong>en</strong>t motion laws, i.e. special mathematical functions,<br />

can be used (for cam examples see: Cam design tool examples). The motion laws for mechanical cams<br />

are defined in VDI guideline 2143 and other docum<strong>en</strong>ts. The electronic cams in <strong>TwinCAT</strong> use these<br />

functions, among others. The motion functions realize these motion functions directly in the real-time<br />

driver of the NC. Unlike classic table couplings that only transfer discrete steps (scatter plots) in the form<br />

of larger data quantities to the NC, the complete information is stored in the NC in very compact form.<br />

Problems originating from data granularity (position refer<strong>en</strong>ce points) in the table are thus eliminated.<br />

The realization of motion laws in the NC has a further crucial advantage: A motion diagram, i.e. the<br />

complete description of the motion of a slave axis, can now simply and clearly be defined and modified<br />

from the PLC. Associated PLC function blocks make the application of this functionality very conv<strong>en</strong>i<strong>en</strong>t.<br />

Users can influ<strong>en</strong>ce not only the complete motion description, but also individual segm<strong>en</strong>ts or subsections.<br />

In order to <strong>en</strong>sure that the drive system can actually implem<strong>en</strong>t a cam in practice, the system calculates<br />

characteristic values (such as maximum and minimum position values, velocity and acceleration etc.),<br />

which the user has to analyze. The resulting dynamic limit values ultimately dep<strong>en</strong>d on the motion of<br />

the master and relate to constant master velocity. The characteristic values are thus calculated with the<br />

idealized assumption of constant master velocity. In addition, the mean velocity and the effective<br />

acceleration are calculated. These values may be used, for example, for calculating the effective torque<br />

or the operating point P A (n m ; M eff ) in the torque/speed diagram of the motor. The PLC can access the<br />

curr<strong>en</strong>t characteristic values of the NC via function blocks.<br />

In the cam design tool (<strong>TwinCAT</strong> Cam Design Editor) the decision whether to use classic table couplings<br />

(scatter plot) or motion functions can be configured via an associated selection. Subsequ<strong>en</strong>tly, either the<br />

position tables or the motion function points are g<strong>en</strong>erated wh<strong>en</strong> the configuration is activated. If<br />

motion functions are used, these points can subsequ<strong>en</strong>tly be modified individually by the PLC.<br />

It is possible to modify individual values or complete sections of the motion functions online according<br />

to associated rules, i.e. while the cam is active. Very flexible cams can thus be realized.<br />

344


Chapter: Camming<br />

c. Definition of a Point<br />

The information contained in the cam design tool table is suffici<strong>en</strong>t for defining the motion in the NC.<br />

However, closer inspection of this MF table reveals the pres<strong>en</strong>ce of redundant data. Because the motion<br />

is described in segm<strong>en</strong>ts (sections), for motion diagrams with simple interrelationships the <strong>en</strong>d point of<br />

a section is id<strong>en</strong>tical to the starting point of the next segm<strong>en</strong>t. The more complex point types offered by<br />

the cam design tool, such as slide point, are not yet implem<strong>en</strong>ted. In addition, users want to be able to<br />

deactivate individual points in a particular motion diagram (MOTIONPOINTTYPE_IGNORE, referred to as<br />

IGNORE below) at a later stage. These requirem<strong>en</strong>ts lead a description that in addition to the starting<br />

point of a segm<strong>en</strong>t, including the point information (velocity, acceleration, point type), also contains the<br />

segm<strong>en</strong>t information (function type, symmetry value).<br />

d. Point structure<br />

PointIndex<br />

FunctionType<br />

PointType<br />

RelIndexNextPoint<br />

MasterPos<br />

SlavePos<br />

SlaveVelo<br />

SlaveAcc<br />

SlaveJerk/Symmetry<br />

UINT32 Point index<br />

UINT16 Function type<br />

UINT16 Point type<br />

Relative index of the <strong>en</strong>d point (default: 0, subsequ<strong>en</strong>tly corresponds<br />

INT32<br />

to 1)<br />

REAL64 Master position<br />

REAL64 Slave position at this refer<strong>en</strong>ce point<br />

REAL64 Slave velocity at this refer<strong>en</strong>ce point<br />

REAL64 Slave acceleration at this refer<strong>en</strong>ce point<br />

Slave jerk at this refer<strong>en</strong>ce point or symmetry value of the segm<strong>en</strong>ts<br />

REAL64<br />

for rest in rest motion laws<br />

In this structure, a relative index is used to refer to the point index of the <strong>en</strong>d point of this segm<strong>en</strong>t.<br />

In order to keep the definition simple for motion diagrams with simple interrelationships, the IGNORE<br />

points are indeed ignored completely. The relative point index is therefore automatically adjusted<br />

internally.<br />

The default value of the relative point index may therefore be zero, although for a standard list with<br />

simple link the value should be ‘1’. The user therefore does not have to update this information. The<br />

possible point types of the cam design tool therefore includes the IGNORE point.<br />

345


Chapter: Camming<br />

e. Point types<br />

MOTIONPOINTTYPE_IGNORE 0x0000 Ignore point Ignored point<br />

MOTIONPOINTTYPE_REST 0x0001 Restpoint Rest point<br />

MOTIONPOINTTYPE_VELOCITY 0x0002 Velocitypoint Velocity point<br />

MOTIONPOINTTYPE_TURN 0x0004 Turnpoint Reversal point<br />

MOTIONPOINTTYPE_MOTION 0x0008 Motionpoint Movem<strong>en</strong>t point<br />

MOTIONPOINTTYPE_REST v=0, a=0<br />

MOTIONPOINTTYPE_VELOCITY v=?, a=0<br />

MOTIONPOINTTYPE_TURN<br />

v=0, a=?<br />

MOTIONPOINTTYPE_MOTION v=?, a=?<br />

At Rest the velocity and acceleration will be 0.<br />

A Velocity point will have 0 acceleration and the velocity will be defined by the Cam Table or the user.<br />

A Turn point will have a velocity of 0, and the acceleration will be calculated by the Cam Table or the<br />

user.<br />

A Motion point is the default type in which the velocity and acceleration will be calculated by the Cam<br />

Table.<br />

Since no points can be added while the MF is active, the IGNORE point type <strong>en</strong>ables associated points to<br />

be included. These can be activated online at a later stage by specifying the associated values (point<br />

type not equal IGNORE).<br />

Warning:<br />

The master position has to be either strictly monotonic rising or falling. Otherwise it is rejected with an<br />

associated error message.<br />

346


Chapter: Camming<br />

44.Cam Design Tool<br />

a. Overview<br />

A cam design editor is used to design the movem<strong>en</strong>ts for a cam plate. A cam design editor is integrated<br />

into <strong>TwinCAT</strong>, and it can be found in the System Manager under the NC Configuration, under the Tables<br />

item. The cam design editor is a flexible tool that provides the user with optimum support and only the<br />

minimum of restrictions. Therefore, responsibility for the choice of parameters lies with the user. The<br />

user, for instance, should carefully check whether the starting and <strong>en</strong>d points correspond exactly to<br />

requirem<strong>en</strong>ts. On the other hand, the user is offered the best possible assistance for checking velocity,<br />

acceleration and jerk through the graphic display facilities.<br />

With all these options, however, the user must remember that it is physics that sets the limits to the<br />

possible movem<strong>en</strong>t.<br />

347


Chapter: Camming<br />

b. Creating a Cam Table<br />

Right click on Tables and select App<strong>en</strong>d Table…<br />

Leave the defaults and select OK.<br />

348


Chapter: Camming<br />

Right click on the Master and select App<strong>en</strong>d Slave…<br />

Leave the defaults and select OK.<br />

It is possible here to insert additional masters, and to <strong>en</strong>ter corresponding slaves under. If you th<strong>en</strong> click<br />

the master in the structure tree, the property pages can be used to set the properties not only of the<br />

master, but also of the associated slaves.<br />

349


Chapter: Camming<br />

350


Chapter: Camming<br />

The g<strong>en</strong>eral procedure for developing a design of a cam is based on VDI (Verein Deutscher Ing<strong>en</strong>ieure)<br />

Guideline 2143. The rough design of the movem<strong>en</strong>t - the movem<strong>en</strong>t plan - defines the starting and <strong>en</strong>d<br />

points of the movem<strong>en</strong>t section. The editor, however, does not make a distinction betwe<strong>en</strong> the<br />

movem<strong>en</strong>t sketch and the movem<strong>en</strong>t diagram containing the detailed description of the movem<strong>en</strong>t,<br />

they will show the same data.<br />

The user's interface to the cam design editor is graphic. Following interactive graphic <strong>en</strong>try of the points<br />

in the graphic window, the co-ordinates of the points are displayed in the table window above it. New<br />

points can only be inserted in the graph, and it is only possible to delete existing points via the graph.<br />

The properties of the points - the co-ordinate values or their derivatives - can also be interactively<br />

manipulated in the table window.<br />

351


Chapter: Camming<br />

Not just the position, but also the velocity, acceleration and jerk can be displayed in the graphic area.<br />

The mode of the display can be changed by a right mouse click in the graphic window, which op<strong>en</strong>s the<br />

following m<strong>en</strong>u:<br />

Thus a separate Graphic Window is op<strong>en</strong>ed for each derivative.<br />

352


Chapter: Camming<br />

i. Master Tab<br />

The minimum and maximum master positions can be specified.<br />

The Normed switch allows you to choose betwe<strong>en</strong> a normalized display and a physically ori<strong>en</strong>ted display<br />

in which the velocity, acceleration and jerk of the slave are shown against time. The normalized display<br />

refers these displays to the master position.<br />

The velocity of the master is needed for the physically ori<strong>en</strong>ted display; it is necessary, first of all, to<br />

distinguish here betwe<strong>en</strong> a linear and a rotary axis (angular values quoted in degrees). Wh<strong>en</strong> the data is<br />

transferred to the NC, the choice betwe<strong>en</strong> a linear and a rotary axis specifies whether the table type is<br />

linear or cyclic.<br />

For a rotary Master, the first and second derivatives at the <strong>en</strong>d are set equal to the corresponding<br />

values at the start of the movem<strong>en</strong>t cycle, if the starting and <strong>en</strong>d positions of the slave correspond to<br />

the minimum and maximum positions of the master.<br />

The increm<strong>en</strong>t specifies the increm<strong>en</strong>t of the master position used for output of the table into a file. If<br />

an equidistant table is to be g<strong>en</strong>erated, the total l<strong>en</strong>gth (the actual maximum minus the minimum)<br />

should be divisible by the increm<strong>en</strong>t. Wh<strong>en</strong> the project is saved in the registry, the information required<br />

to g<strong>en</strong>erate and transfer the tables with this increm<strong>en</strong>t is created in the NC.<br />

The Rounding Value rounds the master position in the graphic input with the giv<strong>en</strong> value.<br />

Fixed Table / Motion Function: Wh<strong>en</strong> exporting the cam table to a .csv file this option will either<br />

g<strong>en</strong>erate a straight line (Fixed Table) or calculate the points using the Motion Function.<br />

353


Chapter: Camming<br />

ii. Slave Tab<br />

Maximum and minimum values can be specified for position, velocity, acceleration and jerk. These<br />

values can be used as initial specifications wh<strong>en</strong> the graphic window is first displayed. Adjustm<strong>en</strong>t to the<br />

curr<strong>en</strong>t values in the diagram can be performed in the relevant graphic window with the Adjust to<br />

Extreme Values command.<br />

The Rounding Value rounds the slave position in the graphic input with the giv<strong>en</strong> value.<br />

Export allows the slave's values to be stored in an ASCII file in the form of master position, slave<br />

position, on one line each. The master position increm<strong>en</strong>t is specified in the master's property page.<br />

Import allows files in the format just described to be read in. The values can th<strong>en</strong> be displayed as cubic<br />

splines. The type of the spline still needs to be adjusted in the table, according to the values.<br />

The Table Id provides a unique id<strong>en</strong>tifying number (1..255) for the table, with the aid of which the table<br />

data is stored in the NC. It can be changed to using a right mouse click in the m<strong>en</strong>u with the Change Id...<br />

command.<br />

354


Chapter: Camming<br />

c. Graphic Window<br />

The slave's position and derivatives are each shown in separate graphic windows.<br />

The associated toolbar includes both buttons that are only related to the graph as well as the special<br />

commands for the cam plate editor.<br />

Wh<strong>en</strong> the Overview Window is switched on, it is not only possible to see which section the graph<br />

window is looking at, but this section can be moved, or it is possible to zoom to a new section.<br />

The horizontal and vertical Scrollbars can be used to shift the Graphic Section; the horizontal scrollbar<br />

acts on all the graphic windows at the same time.<br />

If you're using an IntelliMouse with a ScrollWheel you can zoom with the ScrollWheel.<br />

355


Chapter: Camming<br />

The toolbar and its commands can be displayed or hidd<strong>en</strong> via the m<strong>en</strong>u that is op<strong>en</strong>ed by a right mouse<br />

click (in the graphic window).<br />

This window also has a Horizontal Scrollbar if the Horizontal Scrollbar option is activated. All the<br />

horizontal scrollbars are synchronized.<br />

The Cross on Point option causes the starting and <strong>en</strong>d points of a movem<strong>en</strong>t section to be indicated by a<br />

cross.<br />

The Show Online Data displays the table data that is curr<strong>en</strong>tly in the NC, with the associated table ID as<br />

a cubic spline. Curr<strong>en</strong>tly this can result in a distorted display; because the linear tables are displayed as<br />

natural splines (second derivative at the edges equals 0). The data is displayed in the same color, but<br />

somewhat darker.<br />

The data is automatically transferred by ADS, as soon as Online Mode is switched on. The curr<strong>en</strong>t data<br />

can be read by switching the mode on and off.<br />

Wh<strong>en</strong> the project is saved in the registry (Activate Configuration), the information required to g<strong>en</strong>erate<br />

and transfer the tables is created in the NC.<br />

356


Chapter: Camming<br />

d. Tables Window<br />

The values for the movem<strong>en</strong>t section are displayed in the table window:<br />

The values can be altered via the keyboard, remember that restrictions are applied arising from the<br />

choice of function type or other boundary conditions for the points.<br />

Since movem<strong>en</strong>t sections are normally continuous; except for Slide Points, the <strong>en</strong>d point and its<br />

derivatives at the <strong>en</strong>d of the section are equal to the corresponding values at the start of the following<br />

movem<strong>en</strong>t section. For this reason it is normally always the initial values that should be manipulated. In<br />

addition to this, if any inconsist<strong>en</strong>cies are se<strong>en</strong> in the graph of a completed movem<strong>en</strong>t diagram, the<br />

agreem<strong>en</strong>t of the initial and <strong>en</strong>d points should be checked. If certain values in the table cannot be<br />

changed, consideration should be giv<strong>en</strong> to the boundary conditions applying to the points. It may be<br />

appropriate to change them. The boundary conditions limit the scope of the functions in sections in<br />

accordance with their type.<br />

The symmetry of the functions can only be changed for the following types: Polynom3, Polynom5,<br />

Polynom8, Sinusline, ModSinusline, Bestehorn, and AccTrapezoid. Normally the inflection on the curve<br />

(acceleration = 0) at 50 % = 0.5. This value can be changed in the table or in the diagram of the<br />

acceleration (Example 6).<br />

357


Chapter: Camming<br />

i. Function Types<br />

In addition to the standard types (synchronous/automatic), which can be changed by command on the<br />

graph, the function type can also be modified in the combo box. Wh<strong>en</strong> the combo box; or a field in the<br />

first column, is first clicked, a rectangle is temporarily shown in the position window, with the initial and<br />

<strong>en</strong>d points of the section at its corners. As soon as another field in the table window is activated, either<br />

the rectangle for this one is shown, or no rectangle is displayed at all.<br />

The types correspond to those of VDI Guideline 2143; additionally, there are the cubic splines, with the<br />

boundary conditions of natural, tang<strong>en</strong>tial and periodical.<br />

Changing the type of spline at the first point implies that the spline type as a whole is changed, including<br />

that of the <strong>en</strong>d point.<br />

If Spline Tang<strong>en</strong>tial is chos<strong>en</strong> as the spline type, the boundary conditions (first derivative at the starting<br />

and <strong>en</strong>d point) should be modified.<br />

At the Motion functions with fit to boundary values the R is for Rest, V for Velocity, T for Turn, and M for<br />

Motion.<br />

358


Chapter: Camming<br />

ii. Commands<br />

The cam design editor offers the following commands, and these may be called up through the toolbars<br />

on the relevant graphic window:<br />

All these commands are only applicable to the associated window.<br />

Adjustm<strong>en</strong>t to the Extreme Values<br />

The window's coordinates are adjusted to the extreme values of the movem<strong>en</strong>t.<br />

Measurem<strong>en</strong>t of Distance<br />

The horizontal and vertical distance to the curr<strong>en</strong>t point from the point first clicked with the left mouse<br />

button is displayed at the top right hand corner of the window (please hold the mouse button down for<br />

this).<br />

Curr<strong>en</strong>t Position<br />

The absolute horizontal and vertical position of the point curr<strong>en</strong>tly clicked with the left mouse button is<br />

displayed at the top right hand corner of the window (please hold the mouse button down for this).<br />

Horizontal Shift<br />

Moves the selected point horizontally<br />

In the velocity window for synchronous functions: shift along a straight line in the position window.<br />

The left-hand edge of the graphic area can be temporarily moved in this way, so that the scale can be<br />

more easily read.<br />

Vertical Shift<br />

Moves the selected point vertically<br />

In the velocity window for synchronous functions: adjustm<strong>en</strong>t of the position in the position window to<br />

the velocity.<br />

In the acceleration window for automatic function: adjustm<strong>en</strong>t of the acceleration.<br />

Shift<br />

Moves the selected point.<br />

359


Chapter: Camming<br />

The following commands only apply in the graphic window for position:<br />

Insert Point<br />

Inserts a point at the cursor position.<br />

Synchronous Function<br />

The chos<strong>en</strong> section is passed through with a synchronous function.<br />

Automatic Function<br />

An optimum function is selected automatically for the chos<strong>en</strong> section including adjustm<strong>en</strong>t to the<br />

boundary values.<br />

Delete Point<br />

The selected point is deleted, as is the corresponding section.<br />

The following four items define specific boundary conditions for the points:<br />

The point type is correspondingly displayed in front of the point in the table window. This restriction can<br />

mean that the <strong>en</strong>d value of a section does not agree with the initial value for the following section.<br />

Rest Point<br />

The selected point is defined as a rest point (boundary condition: v=0, a=0).<br />

Velocity Point<br />

The selected point is defined as a velocity point (boundary condition: a=0).<br />

Reversal Point<br />

The selected point is defined as a reversal point (boundary condition: v=0).<br />

Movem<strong>en</strong>t Point<br />

The selected point is defined as a movem<strong>en</strong>t point (no boundary conditions).<br />

Slide Point<br />

The starting position of the following section or the <strong>en</strong>d position of the previous section is set at the<br />

cursor position, without changing the selected section.<br />

The point can th<strong>en</strong> be moved on to the section using horizontal shift.<br />

Delete Slide Point<br />

The slide point is deleted and the sections are joined together as they were previously.<br />

360


Chapter: Camming<br />

45.Cam Table Scaling<br />

a. Overview<br />

As required by the application the scale of the Cam Table can be adjusted. Master and Slave offsets can<br />

also be giv<strong>en</strong> to provide more flexibility to the programmer.<br />

b. MC_CamScaling<br />

A cam plate coupling can be scaled with the function block MC_CamScaling. The raw table data of the<br />

cam plate are not affected, the scaling refers to an existing master/slave coupling. The following<br />

parameters can be modified, scaling factors for master and slave, and offsets for the cam plate within<br />

the coordinate system.<br />

Optionally, the modification will only take effect from a certain master position, <strong>en</strong>abling precise scaling<br />

during the motion. Caution wh<strong>en</strong> scaling during motion! The slave position at the time of scaling should<br />

only be affected slightly by the change.<br />

The status flag Axis.Status.CamcalingP<strong>en</strong>ding can be used to check whether a scaling procedure is<br />

queued.<br />

Inputs<br />

VAR_INPUT<br />

Execute<br />

: BOOL;<br />

ActivationMode : MC_CamActivationMode;<br />

ActivationPosition : LREAL;<br />

MasterScalingMode : MC_CamScalingMode;<br />

SlaveScalingMode : MC_CamScalingMode;<br />

MasterOffset<br />

: LREAL;<br />

SlaveOffset<br />

: LREAL;<br />

MasterScaling : LREAL := 1.0;<br />

SlaveScaling : LREAL := 1.0;<br />

END_VAR<br />

Execute: The command is executed with a rising edge at input Execute<br />

361


Chapter: Camming<br />

ActivationMode: ActivationMode specifies the scaling time and position.<br />

ActivationPosition: Master position at which a cam plate is scaled, dep<strong>en</strong>ding on the ActivationMode<br />

If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used; the position refers to the nonscaled<br />

cam plate. If the position in the application refers to the scaled cam plate, it can be divided by the<br />

MasterScaling value before the function block is called.<br />

MasterScalingMode: Optional scaling mode for the master position of the cam plate<br />

SlaveScalingMode: Optional scaling mode for the slave position of the cam plate<br />

MasterOffset: Offset to the master position of the cam plate<br />

SlaveOffset: Offset to the slave position of the cam plate<br />

MasterScaling: Scaling of the master position of the cam plate<br />

SlaveScaling: Scaling of the slave position of the cam plate<br />

Outputs<br />

VAR_OUTPUT<br />

Done :<br />

Busy :<br />

Error :<br />

ErrorID : UDINT;<br />

END_VAR<br />

BOOL;<br />

BOOL;<br />

BOOL;<br />

Done: becomes TRUE, if the cam plate was created successfully.<br />

Busy: The Busy output becomes TRUE wh<strong>en</strong> the command is started with Execute and remains TRUE as<br />

long as the command is processed. Wh<strong>en</strong> Busy becomes FALSE again, the function block is ready for a<br />

new command. At the same time one of the outputs, Done or Error, is set.<br />

Error: Becomes TRUE, as soon as an error occurs.<br />

ErrorID: If the error output is set, this parameter supplies the error number.<br />

Inputs/outputs<br />

VAR_IN_OUT<br />

Master : AXIS_REF;<br />

Slave : AXIS_REF;<br />

END_VAR<br />

362


Chapter: Camming<br />

c. MC_CamScalingMode<br />

TYPE MC_CamScalingMode :<br />

(<br />

MC_CAMSCALING_USERDEFINED, (* user defines scaling parameters - scaling and offset *)<br />

MC_CAMSCALING_AUTOOFFSET, (* offset is calculated automatically for best result *)<br />

MC_CAMSCALING_OFF (* no modification accepted *)<br />

);<br />

END_TYPE<br />

Type and scope of the scaling of a cam plate coupling via function block MC_CamScaling.<br />

MC_CAMSCALING_USERDEFINED: The scaling and offset are retained unchanged. The user has to<br />

calculate the scaling and offset such that a jump in the position is avoided.<br />

MC_CAMSCALING_AUTOOFFSET: The scaling takes effect and the system adjusts the offset such that a<br />

jump in the position is avoided. Scaling should nevertheless occur during a phase with slave velocity 0,<br />

since otherwise a jump in velocity cannot be avoided.<br />

MC_CAMSCALING_OFF: The scaling and offset are ignored. This mode is used wh<strong>en</strong> only slave scaling<br />

(i.e. without master scaling) is to be implem<strong>en</strong>ted.<br />

Autooffset<br />

Autooffset mode <strong>en</strong>sures automatic adaptation of a cam plate offset. Autooffset can be used<br />

indep<strong>en</strong>d<strong>en</strong>tly for the master or slave axis of a cam plate and affects both switchover and scaling of cam<br />

plates. The function operates based on the rules described below.<br />

Master-Autooffset<br />

Master-Autooffset Prev<strong>en</strong>ts discontinuity of the master position of the cam plate in the axis coordinate<br />

system during switching of cam plates with differ<strong>en</strong>t master cycle or scaling of cam plates (master<br />

scaling). This function is required because the relative position of a cam plate in the axis coordinate<br />

system dep<strong>en</strong>ds on the master cycle. If the master cycle is changed, e.g. through scaling, the position<br />

would change.<br />

Master-Autooffset determines the master offset of the cam plate such that the master position within<br />

the cam plate is maintained. For scaling or switchover to a cam plate with a differ<strong>en</strong>t master cycle this<br />

means that the relative (perc<strong>en</strong>tage) position before and after the switchover is id<strong>en</strong>tical.<br />

363


Chapter: Camming<br />

i. Example:<br />

A cam plate has master cycle of 360° and is scaled by a factor of 2 to 720°. Scaling takes place at the 90°<br />

position within the cam plate, i.e. at 25% of the start of a cycle. After the scaling the relative master<br />

position in the cam plate at 180° is therefore also 25% of the start of a cycle.<br />

During a switchover at the edges of a cam plate (see MC_CamActivationMode<br />

MC_CAMACTIVATION_NEXTCYCLE), Master-Autooffset <strong>en</strong>sures a seamless sequ<strong>en</strong>ce of cam plates, both<br />

for cyclic and linear cam plates.<br />

364


Chapter: Camming<br />

Master-Autooffset cannot be used for a cam plate with relative coupling or switching, since these<br />

functions are mutually exclusive. Further restrictions apply to initial coupling. These are shown in the<br />

following table.<br />

Slave-Autooffset<br />

Slave-Autooffset calculates a slave offset such that discontinuities in the slave position are avoided<br />

during cam plate switching or scaling. The slave offset is adjusted to <strong>en</strong>sure that the slave position is<br />

id<strong>en</strong>tical before and after the action.<br />

If both Master Autooffset and Slave-Autooffset are used for cam plate switching or scaling, the master<br />

offset is calculated first, followed by the slave offset.<br />

Slave-Autooffset can be used with any MC_StartMode and will always adjust the cam plate such that the<br />

slave position doesn't jump.<br />

365


Chapter: Camming<br />

ii. Sample Code:<br />

IF VM.NcToPlc.ActPos > 540 THEN<br />

fbMC_CamScaling(<br />

Execute:=TRUE ,<br />

ActivationMode:=MC_CAMACTIVATION_NEXTCYCLE ,<br />

ActivationPosition:=721 ,<br />

MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET ,<br />

SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET ,<br />

MasterOffset:=0 ,<br />

SlaveOffset:=0 ,<br />

MasterScaling:= 0.5,<br />

SlaveScaling:=1 ,<br />

Slave:=Slave);<br />

END_IF<br />

366


Chapter: Camming<br />

46.Cyclic Cam Plates with Lift<br />

Please refer to MC_CamIn App<strong>en</strong>dix in the Information System or at the <strong>en</strong>d of this docum<strong>en</strong>t.<br />

This docum<strong>en</strong>t makes use of the Cam Design Tool to create the following cam table where the Slave axis<br />

travels 100 for each 360 degree revolution of the Master axis.<br />

Calculations for the Lift are handled internally. Only the configuration needs to be correct to implem<strong>en</strong>t<br />

this type of Cam Table.<br />

367


Chapter: Camming<br />

The Master Axis must be set for Rotation.<br />

The StartMode of the MC_CamIn FB must be set properly. In this example we are using<br />

MC_STARTMODE_MASTERABS_SLAVEREL<br />

Where the Master axis is calculated to an Absolute position and the Slave axis is calculated Relative to its<br />

curr<strong>en</strong>t position.<br />

368


Chapter: Camming<br />

a. MC_StartMode<br />

TYPE MC_StartMode :<br />

(<br />

MC_STARTMODE_ABSOLUTE := 1, (* cam table is absolute for master and slave *)<br />

MC_STARTMODE_RELATIVE, (* cam table is relative for master and slave *)<br />

MC_STARTMODE_MASTERABS_SLAVEREL, (* cam table is absolute for master and<br />

relative for slave *)<br />

absolute for slave *)<br />

);<br />

END_TYPE<br />

MC_STARTMODE_MASTERREL_SLAVEABS<br />

(* cam table is relative for master and<br />

StartMode is used for coupling with cam plates through MC_CamIn and defines whether a cam plate is<br />

interpreted absolute (based on the origin of the axis coordinate system) or relative to the coupling<br />

position. The mode can be specified as absolute or relative separately for both coordinate axes.<br />

With StartMode absolute the cam plate coordinate system is congru<strong>en</strong>t with the axis coordinate system<br />

and can be moved through an offset, if required (master or slave offset).<br />

With StartMode relative the origin of the cam plate coordinate system is at the axis position of the<br />

respective axis (master or slave) at the time of coupling or cam plate switching. The cam plate can<br />

additionally be moved through an offset.<br />

Note: The modes MC_STARTMODE_RELATIVE and MC_STARTMODE_MASTERREL_SLAVEABS cannot be<br />

used in conjunction with automatic master offset calculation (MC_CamScalingMode), since this would<br />

cause a conflict.<br />

369


Chapter: Camming<br />

As can be se<strong>en</strong> below, wh<strong>en</strong> running the Cam Table cyclically the Slave axis will increase from its curr<strong>en</strong>t<br />

position by 100 for each 360 degrees of travel by the Master Axis.<br />

The Red line is the Modulo position of the Master Axis.<br />

The Gre<strong>en</strong> line is the Absolute position of the Slave Axis.<br />

370


Chapter: Camming<br />

47.Cam Out and Restarting<br />

a. Overview<br />

MC_CamOut is used to decouple the Slave axis from the Master axis. The slave axis must be stopped<br />

after it is decoupled. To couple the axis back to the Master via the Cam Table simply call the MC_CamIn<br />

FB again. If the Slave axis has not changed positions th<strong>en</strong> the default values will suffice for Camming the<br />

Slave axis to the Master axis on the next cycle of the Cam Table. In the below Scope the Gre<strong>en</strong><br />

horizontal line shows the Slave axis not moving because it was decoupled from the Master for 3<br />

revolutions, and th<strong>en</strong> coupled again.<br />

371


Chapter: Camming<br />

b. MC_CamOut<br />

The function block MC_CamOut deactivates a master-slave coupling.<br />

Note: If a slave axis is uncoupled during the movem<strong>en</strong>t, it is not automatically stopped, but<br />

reaches a continuous velocity with which it will continue to travel <strong>en</strong>dlessly. The axis can be<br />

stopped with a Stop command.<br />

Inputs<br />

VAR_INPUT<br />

Execute<br />

Options<br />

END_VAR<br />

: BOOL;<br />

: ST_CamOutOptions; (*Not Yet Implem<strong>en</strong>ted*)<br />

Execute: The command is executed with a rising edge at input Execute.<br />

Options: Curr<strong>en</strong>tly not implem<strong>en</strong>ted<br />

Outputs<br />

VAR_OUTPUT<br />

Done :<br />

Busy :<br />

Error :<br />

ErrorID : UDINT;<br />

END_VAR<br />

BOOL;<br />

BOOL;<br />

BOOL;<br />

Done: Becomes TRUE, if the axis was successfully uncoupled.<br />

Busy: The Busy output becomes TRUE wh<strong>en</strong> the command is started with Execute and remains TRUE as<br />

long as the command is processed. Wh<strong>en</strong> Busy becomes FALSE again, the function block is ready for a<br />

new command. At the same time one of the outputs, Done or Error, is set.<br />

Error: Becomes TRUE, as soon as an error occurs.<br />

ErrorID: If the error output is set, this parameter supplies the error number.<br />

Inputs/Outputs<br />

VAR_IN_OUT<br />

Slave : AXIS_REF;<br />

END_VAR<br />

Slave: Slave axis data structure.<br />

The axis data structure of type AXIS_REF addresses an axis uniquely within the system. Among other<br />

parameters it contains the curr<strong>en</strong>t axis status, including position, velocity or error status.<br />

372


Chapter: Camming<br />

c. MC_Halt<br />

MC_Halt stops an axis with a defined braking ramp.<br />

In contrast to MC_Stop, the axis is not locked against further motion commands. The axis can therefore<br />

be restarted through a further command during the braking ramp or after it has come to a halt.<br />

Note: Motion commands can be passed to slave axes if they are explicitly <strong>en</strong>abled in the axis<br />

parameters. A motion command will th<strong>en</strong> decouple the axis and move it afterwards. In this case just<br />

Buffer-Mode Aborting can be used.<br />

Inputs<br />

VAR_INPUT<br />

Execute : BOOL;<br />

Deceleration : LREAL;<br />

Jerk<br />

: LREAL;<br />

BufferMode : MC_BufferMode;<br />

Options : ST_MoveOptions;<br />

END_VAR<br />

Execute: The command is executed with a rising edge at input Execute.<br />

Deceleration: Deceleration (≥0). If the value is 0, the deceleration parameterised with the last Move<br />

command is used.<br />

MC_Halt and MC_Stop as well cannot be executed with lower dynamical parameters than the curr<strong>en</strong>tly<br />

active motion command. Parameters will be adapted automatically.<br />

Jerk: Jerk (≥0). If the value is 0, the jerk parameterised with the last Move command is used.<br />

MC_Halt and MC_Stop as well cannot be executed with lower dynamical parameters than the curr<strong>en</strong>tly<br />

active motion command. Parameters will be adapted automatically.<br />

BufferMode: BufferMode is curr<strong>en</strong>tly not supported by MC_Halt. Halt takes effect immediately with a<br />

rising edge at Execute, similar to BufferMode=MC_Aborting<br />

Options: Curr<strong>en</strong>tly not implem<strong>en</strong>ted - The data structure option includes additional, rarely required<br />

parameters. The input can normally remain op<strong>en</strong>.<br />

373


Chapter: Camming<br />

Outputs<br />

VAR_OUTPUT<br />

Done<br />

: BOOL;<br />

Busy<br />

: BOOL;<br />

Active<br />

: BOOL;<br />

CommandAborted : BOOL;<br />

Error<br />

: BOOL;<br />

ErrorID<br />

: UDINT;<br />

END_VAR<br />

Done: The Done output becomes TRUE, if the axis was stopped and has come to a standstill.<br />

Busy: The Busy output becomes TRUE wh<strong>en</strong> the command is started with Execute and remains TRUE as<br />

long as the command is processed. Wh<strong>en</strong> Busy becomes FALSE again, the function block is ready for a<br />

new command. At the same time one of the outputs, Done, CommandAborted or Error, is set.<br />

Active: Active indicates that the command is executed If the command was queued, it becomes active<br />

once a running command is completed.<br />

CommandAborted: Becomes TRUE, if the command could not be fully executed. The running command<br />

may have be<strong>en</strong> followed by a Move command.<br />

Error: Becomes TRUE if an error occurs.<br />

ErrorID: If the error output is set, this parameter supplies the error number.<br />

Inputs/outputs<br />

VAR_IN_OUT<br />

Axis<br />

END_VAR<br />

: AXIS_REF;<br />

Axis: Axis data structure<br />

The axis data structure of type AXIS_REF addresses an axis uniquely within the system. Among other<br />

parameters it contains the curr<strong>en</strong>t axis status, including position, velocity or error status.<br />

374


Chapter: Camming<br />

48.MC_CamIn App<strong>en</strong>dix<br />

<strong>TwinCAT</strong> PLC Library: MC (Version 2)<br />

a. Axis coupling with cam plates<br />

The function block MC_CamIn can be used to establish a cam plate coupling (or table coupling) betwe<strong>en</strong><br />

a master axis and a slave axis. Note that prior to the coupling the slave axis has to be at a position<br />

defined by the cam plate. After the coupling and once the master has be<strong>en</strong> started, the slave position is<br />

calculated directly from the cam plate. The slave axis is therefore not slowly synchronized with the cam<br />

plate, but it will jump if it is not already at the table position.<br />

In practice the question arises; what position the slave should be in prior to the coupling, and how this is<br />

calculated. The following figures illustrate the procedure.<br />

Notes: For all subsequ<strong>en</strong>t calculations only axis set positions are used. The actual positions are not used<br />

in the calculations, since they would lead to calculation errors, particularly with cyclic cam plates.<br />

Only absolute table couplings are considered. For relative couplings, the coupling position of the master<br />

or slave axis is considered in the calculations as an additional offset.<br />

b. Linear cam plates<br />

A linear cam plate is only defined via a limited master position range. Outside this range the slave<br />

position is defined by the first or last table position. The slave therefore stops at the table edges as soon<br />

as the master leaves the defined range.<br />

The diagram shows that the absolute axis coordinate system (blue) does not have to be id<strong>en</strong>tical to the<br />

cam plate coordinate system (red). The cam plate coordinate system may be offset by a master offset or<br />

a slave offset. Scaling is also possible.<br />

375


Chapter: Camming<br />

The slave position relating to a certain master position can be determined via the function block<br />

MC_ReadCamTableSlaveDynamics . The block refers to the raw table data, which means that offsets and<br />

scaling factors have to be considered via the PLC program itself. Initially, the master offset is added to<br />

the curr<strong>en</strong>t master position. If the cam plate is to be scaled, it is divided by this scaling factor.<br />

MasterCamTablePosition := (MasterPosition + MasterOffset) /<br />

MasterScaling;<br />

The master table position is used as an input parameter for the function block<br />

MC_ReadCamTableSlaveDynamics. The result is converted to an absolute slave position with slave offset<br />

and scaling, if necessary.<br />

SlaveCamTablePosition := ReadSlaveDynamics.SlavePosition;<br />

SlavePosition := (SlaveCamTablePosition * SlaveScaling) +<br />

SlaveOffset;<br />

The slave is moved to this position prior to the coupling. Alternatively, the master may be moved to a<br />

position that corresponds to the curr<strong>en</strong>t slave position. However, g<strong>en</strong>erally this position cannot be<br />

determined from the cam plate, since the cam plate may be ambiguous.<br />

Note: Since the master offset is added in the first formula, a positive offset leads to the cam plate<br />

coordinate system being shifted to the left in negative direction. Accordingly, the master offset in the<br />

diagram is negative. A positive slave offset leads to the cam plate coordinate system being shifted<br />

upwards in positive direction.<br />

376


Chapter: Camming<br />

c. Cyclic cam plates without lift<br />

A cyclic cam plate without lift is characterized by the fact that the slave start and <strong>en</strong>d positions in the<br />

table are id<strong>en</strong>tical. The slave therefore moves cyclically within a defined range, without changing its<br />

position perman<strong>en</strong>tly in a particular direction.<br />

For these cam plate types, master/slave coupling requires the same preparation as for a linear cam<br />

plate. The starting position of the slave can therefore be calculated as described above. It is not<br />

necessary to use the modulo position of the master for the calculation, since the absolute position is<br />

already correctly tak<strong>en</strong> into account via the coupling command.<br />

377


Chapter: Camming<br />

d. Cyclic cam plates with lift<br />

The lift of a cyclic cam plate is the differ<strong>en</strong>ce betwe<strong>en</strong> the last and the first table position of the slave.<br />

Such a cam plate is continued cyclically at the <strong>en</strong>d of the table. The slave position does not jump back to<br />

the initial table value. Instead, the motion continues steadily. With each new cycle, the lift is therefore<br />

added as an additional internal slave offset or subtracted if the motion is reversed.<br />

378


Chapter: Camming<br />

e. Uncoupling and re-coupling for cyclic cam plates with lift<br />

If a slave is coupled to a cam plate with lift, the coupling is always done in the basic cycle (red coordinate<br />

system), i.e. without added lifting distances. If the slave is uncoupled after a few cycles and th<strong>en</strong> recoupled,<br />

the slave position returns to the basic cycle. If necessary, this behavior has to be tak<strong>en</strong> into<br />

account and comp<strong>en</strong>sated by re-calculating the slave offset.<br />

MasterCamTablePos := (MasterPosition + MasterOffset) / MasterScaling;<br />

The master table position is used as input parameter for the function block<br />

MC_ReadCamTableSlaveDynamics. The result is converted to an absolute slave position with slave offset<br />

and scaling, if necessary. In addition, the number of p<strong>en</strong>ding lifts must be calculated and added to the<br />

slave position.<br />

SlaveCamTablePosition := ReadSlaveDynamics.SlavePosition;<br />

Lift number := MODTURNS( (SlavePosition - SlaveOffset), SlaveHub );<br />

NewSlaveOffset := SlaveOffset + (SlaveHub * lift number);<br />

SlavePosition := (SlaveCamTablePosition * SlaveScaling) +<br />

NewSlaveOffset;<br />

The Autooffset function can simplify the calculation of offsets, particularly for switching of cam plates.<br />

379


Chapter: Camming<br />

49.<br />

Diagnostics<br />

a. Overview<br />

The following covers the error codes as provided by either the function blocks or the <strong>TwinCAT</strong> System<br />

Manager. The error codes provided by the system; although complete, are sometimes not easily<br />

understood by new users. The explanations of the error codes provided are based solely on the<br />

experi<strong>en</strong>ce of myself and others. The added descriptions are only relevant for helping to find a problem<br />

within <strong>TwinCAT</strong>, this docum<strong>en</strong>t will not suffice if your problem is within your .NET or other 3 rd party<br />

application.<br />

b. Error Format<br />

The error codes within <strong>TwinCAT</strong> are giv<strong>en</strong> in accordance with the following structure.<br />

All errors are g<strong>en</strong>erated in hexadecimal.<br />

The errors range from 0x0000 to 0xFFFF.<br />

The most significant byte 0xn000 can be considered as the grouping for the errors.<br />

Wh<strong>en</strong> needed a sub subgroup will be id<strong>en</strong>tified by the second byte 0x0n00.<br />

The remaining bytes are used to give the exact error code.<br />

The errors betwe<strong>en</strong> 0x0000 and 0x0FFF refer to the <strong>TwinCAT</strong> System itself. These errors indicate that<br />

something is fundam<strong>en</strong>tally wrong with your system. The cause of the errors can vary greatly; it can be<br />

anything from a corrupted file to forgetting to start the PLC, or an incorrect linking in the system<br />

manager. Remember that just because <strong>TwinCAT</strong> allows you to do something, that doesn’t mean that<br />

that’s what you wanted to do.<br />

380


Chapter: Camming<br />

Error Groups<br />

Offset<br />

0x0000<br />

0x0500<br />

0x0600<br />

0x0700<br />

0x0800<br />

0x1000<br />

0x1900<br />

0x2000<br />

0x3000<br />

0x4000<br />

0x6000<br />

0x7000<br />

0x7800<br />

Description<br />

ERR_GLOBAL<br />

ERR_ROUTERERRS<br />

ERR_TASKERRS<br />

ERR_ADSERRS<br />

ERR_SYSSMPLERRS<br />

ERR_RTIMEERRS<br />

ERR_TRACEERRS<br />

ERR_IOERRS<br />

ERR_SPSERRS<br />

ERR_NCERRS<br />

ERR_PLCERRS<br />

ERR_STRKERRS<br />

ERR_PRJSPECIFIC<br />

Global Error Codes 0x0000<br />

0x6<br />

0x7<br />

target port not found<br />

target machine not found<br />

These errors commonly occur wh<strong>en</strong> setting up a system for the first time, and the frequ<strong>en</strong>cy increases<br />

wh<strong>en</strong> switching betwe<strong>en</strong> developm<strong>en</strong>t, simulation, and machine. This error is trying to tell you that<br />

there is a communication problem, and is commonly an ADS communication problem. If all<br />

communication is local, th<strong>en</strong> make sure <strong>TwinCAT</strong> is running the correct System Manager file, and that<br />

the correct PLC program is loading and running. If you are unsure of what system manager file is<br />

running, the red folder in the system manager will ‘Op<strong>en</strong> from Target’. If communication is remote th<strong>en</strong><br />

check the AMS router on both PCs to make sure the info is valid. Ping the IP of address of one PC from<br />

the other to make sure cabling and network configuration is correct.<br />

G<strong>en</strong>eral ADS Error Codes 0x0700<br />

The common errors in this group are fairly self-explanatory. These normally occur because of something<br />

not being configured correctly. It could be an incorrect or missing link in the system manager or the PLC<br />

code that is calling the ADS service has an invalid parameter.<br />

381


Chapter: Camming<br />

NC Errors 0x4000<br />

The NC error group is comprised of 9 sub-groups. These sub groups cover all things motion, from<br />

Overtemp errors to syntax errors in G-Code to bad PLC commands.<br />

NC Error Sub Groups<br />

0x40nn<br />

0x41nn<br />

0x42nn<br />

0x43nn<br />

0x44nn<br />

0x45nn<br />

0x46nn<br />

0x4Ann<br />

0x4Bnn<br />

G<strong>en</strong>eral NC Errors<br />

Channel Errors<br />

Group Errors<br />

Axis Errors<br />

Encoder Errors<br />

Controller Errors<br />

Drive Errors<br />

Table Errors<br />

NC-PLC Errors<br />

G<strong>en</strong>eral NC Errors 0x40nn<br />

0x4016<br />

used,<br />

"Table id<strong>en</strong>tifier not allowed" Either an unacceptable value (not 1...255) has be<strong>en</strong><br />

or a table that does not exist in the system has be<strong>en</strong> named.<br />

Check your value of your TableID<br />

0x4052<br />

for<br />

"Axis not ready for operation" The axis is not complete, and is therefore not ready<br />

operation. This is usually a consequ<strong>en</strong>ce of problems at system start-up.<br />

If the Ready Status of the Axis is not TRUE and the axis receives a command th<strong>en</strong> this error will<br />

be giv<strong>en</strong>. This value is held in the NCDRIVESTRUCT_IN2 of the Axis 1_Drive and is linked to the<br />

‘Drive Status Word’ of the drive under the I/O Configuration.<br />

from<br />

For an AX5000 the first place to check is on the ‘Configuration’ Tab of the axis. Look at the<br />

ErrorID, it must be at D013: Axis Op. A value less than 13 or an F value will prev<strong>en</strong>t the axis<br />

being ready. The ‘R’ button on the right side of the ErrorID display will issue an IDN99 reset<br />

command to the drive.<br />

382


Chapter: Camming<br />

Channel Errors 0x41nn<br />

These errors are for NC-I and are not within the scope of this docum<strong>en</strong>t.<br />

Group Errors 0x42nn<br />

These errors are for NC-I also. However there is one here that should be covered.<br />

0x4208<br />

"Single step mode not allowed" The flag for the activation or deactivation of single<br />

step mode is not allowed. Value 0: Passive (buffered operation) Value 1: Active (single-block operation).<br />

Prior to MC2 if an axis was giv<strong>en</strong> a command while the Status bit ‘Has Job’ was TRUE this error<br />

would be giv<strong>en</strong>. This error does not stop the axis; it just appears in the Log window of the<br />

System Manager. With the new ‘Buffered Moves’ in MC2 this shouldn’t be an issue any more.<br />

However keep in mind that if you issue a second move before the first one is complete, where it<br />

previously would ignore the command, it will now Abort the previous command and Execute the<br />

new one.<br />

Axis Errors 0x43nn<br />

These Errors relate to the parameterization and monitoring of an axis. The majority of these errors are<br />

for incorrect (out of range) parameters or monitoring the control of the axes.<br />

Encoder Errors 0x44nn<br />

These Errors relate to the parameterization and monitoring of an <strong>en</strong>coder. The majority of these errors<br />

are for incorrect (out of range) parameters or monitoring the <strong>en</strong>coder of the axes.<br />

Controller Errors 0x45nn<br />

These Errors relate to the parameterization and monitoring of the axis controller. The majority of these<br />

errors are for incorrect (out of range) parameters or monitoring the control of the axis position.<br />

Drive Errors 0x46nn<br />

These Errors relate to the parameterization and monitoring of the drive and motor. The majority of<br />

these errors are for incorrect (out of range) parameters or monitoring the state of the drive and motor.<br />

383


Chapter: Camming<br />

Table Errors 0x4Ann<br />

These Errors relate to the parameterization and initialization of a cam table. The majority of these errors<br />

are for incorrect (out of range) parameters or invalid cam table data. The Flying Saw function blocks will<br />

g<strong>en</strong>erate these errors as well as Cam Table function blocks.<br />

0x4A06<br />

"Table is not monotonic" The value for the step size is not allowed, because, for<br />

example, it is less than or equal to zero.<br />

Wh<strong>en</strong> g<strong>en</strong>erating a Cam Table from the PLC or from the Flying Saw this error can happ<strong>en</strong>. The<br />

most common cause from the Flying Saw is the Master SetPos is within 1E-12 of the Master Sync<br />

position wh<strong>en</strong> the Execute turns TRUE. This can also happ<strong>en</strong> for a Cam Table g<strong>en</strong>erated by the<br />

PLC wh<strong>en</strong> the position would require the Master Axis to move backwards.<br />

PLC Errors 0x4Bnn<br />

The majority of these errors are well described within the Information System.<br />

NC-PLC Errors<br />

<strong>TwinCAT</strong> NC I<br />

TcMcCam<br />

TcNc<br />

TcRemoteSync<br />

TcMC2<br />

0x4B00..0x4B0F<br />

0x4B10..0x4B2F<br />

0x4B30..0x4B3F<br />

0x4B40..0x4B4F<br />

0x4B50..0x4B5F<br />

0x4B60..0x4B6F<br />

TcPlcInterpolation 0x4B70..0x4B7F<br />

384


Chapter: Remote Connections<br />

IX.<br />

Remote Connections<br />

50.Embedded Controllers<br />

• The <strong>TwinCAT</strong> AMS Router allows for <strong>TwinCAT</strong> to communicate betwe<strong>en</strong> computers<br />

• Configuring your local IP address<br />

• Establishing a Route to the Target<br />

• Op<strong>en</strong>ing the active system manager of the Target<br />

385


Chapter: Remote Connections<br />

• Click “Start”<br />

• Expand “Connect To”<br />

• Click “Show all connections”<br />

• The network card you are going to use should be the only one with a Status of “Connected”.<br />

• If the other cards are connected <strong>TwinCAT</strong> may try to one of scan these networks for devices and<br />

not scan the correct network.<br />

• Right-Click on the Network Card and select “Properties”<br />

386


Chapter: Remote Connections<br />

• Scroll to the bottom of the list.<br />

• Select “Internet Protocol (TCP/IP)”<br />

• Click on “Properties”<br />

387


Chapter: Remote Connections<br />

• Select “Use the following IP address”<br />

• Enter the following IP address. 192.168.0.2<br />

• Enter your Subnet mask<br />

• Click “OK”<br />

388


Chapter: Remote Connections<br />

• Click “OK”<br />

389


Chapter: Remote Connections<br />

• If the below window appears click on “STOP Installation”. If you click on “Continue Anyway”<br />

windows will install the Real-Time Ethernet driver for your network card. You can do this if you<br />

like, but it is not needed for connecting to remote devices.<br />

• Click on the <strong>TwinCAT</strong> icon in the Windows System Tray, and select System Manager.<br />

390


Chapter: Remote Connections<br />

• Op<strong>en</strong> a new System Manger file. Select File, th<strong>en</strong> New<br />

• Set/Reset <strong>TwinCAT</strong> to Config mode.<br />

• Click “Ok”<br />

391


Chapter: Remote Connections<br />

• Select “SYSTEM – Configuration”, th<strong>en</strong> “Choose Target”<br />

• Click “Search (Ethernet)”<br />

392


Chapter: Remote Connections<br />

• If you know the IP address of the remote device it can be <strong>en</strong>tered.<br />

• Click “Enter Host Name / IP:”<br />

• It is also possible to use the ‘Broadcast Search’ button to look for computers on the local<br />

network that are running <strong>TwinCAT</strong>, however a broadcast search will not go through a network<br />

router.<br />

• If the computer you are connecting to is using DHCP th<strong>en</strong> the ‘Address info’ should be set to<br />

‘Host Name’, if a static IP address is being used th<strong>en</strong> set ‘Address Info’ to ‘IP Address’<br />

• Select the computer form the list and select ‘Add Route’<br />

393


Chapter: Remote Connections<br />

• Enter User name and password of an Administrator account on the Target PC<br />

• Not required for Windows CE<br />

• Click “OK”<br />

• Verify the “X” appears in the “Connected” column. Click on “Close”.<br />

394


Chapter: Remote Connections<br />

• Select “BasePLC” Click “OK”<br />

395


Chapter: Remote Connections<br />

• Verify connection to “BasePLC” the red background indicates you are connected to a remote<br />

device.<br />

• Verify the device status. A gre<strong>en</strong> background indicates that <strong>TwinCAT</strong> is running on the remote<br />

device. A blue background indicates the remote device is in config mode. A yellow background<br />

indicates a Timeout.<br />

• Click on the red folder to “Op<strong>en</strong> from Target”<br />

• If the below window appears click on “Yes”<br />

396


Chapter: Remote Connections<br />

• File name of the System Manager *.tsm file<br />

• Name of remote device<br />

• List of hardware connected to the device<br />

397


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

X. App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

51.Scope<br />

The following programming guidelines support the creation and maint<strong>en</strong>ance of consist<strong>en</strong>t programs<br />

with the following goals:<br />

<br />

<br />

<br />

Improve readability<br />

Speed developm<strong>en</strong>t<br />

Facilitate the incorporation of third-party software compon<strong>en</strong>ts<br />

These guidelines are based on a history of experi<strong>en</strong>ce in software developm<strong>en</strong>t by Beckhoff and our<br />

customers. The programming guidelines must be used for the developm<strong>en</strong>t of new programs, unless the<br />

customer has specified other guidelines for the project. The programmer can judge the ext<strong>en</strong>t to which<br />

the guidelines can be applied to existing programs.<br />

398


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

52.Programming System Settings<br />

The TwinCat project options must be defined uniformly to achieve id<strong>en</strong>tical notation for individual<br />

editors and for docum<strong>en</strong>tation. This is especially true in multi-user projects.<br />

a. Font<br />

A non-proportional font is recomm<strong>en</strong>ded with the following settings: This can be adjusted under<br />

"Project -> Options -> Editor -> Font".<br />

Font: Tahoma<br />

Font style: Regular<br />

Size: 12<br />

Character set: Western<br />

b. Tab Width<br />

A tab width of 4 is recomm<strong>en</strong>ded. This can be adjusted under "Project -> Options -> Editor".<br />

399


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

53.Naming<br />

a. G<strong>en</strong>eral<br />

This naming conv<strong>en</strong>tion applies to variables, constants, and program organization units (POU). Choose a<br />

relevant, short, description for each designator name and the designator should be self-explanatory. The<br />

first letter of each word in the designator is capitalized (example: FileSize). Please limit the name to 20<br />

characters, the fewer the better.<br />

Prefixes are included with the designator name to indicate scope, property, and type as will be explained<br />

below.<br />

b. Case S<strong>en</strong>sitivity<br />

Pay close att<strong>en</strong>tion to case s<strong>en</strong>sitivity, especially for prefixes, to improve readability.<br />

NOTE: The TwinCat IEC compiler is not case s<strong>en</strong>sitive.<br />

c. Valid Characters<br />

Names should contain the following letters, numbers, and special characters only:<br />

<br />

<br />

<br />

0...9, A...Z, a...z<br />

Underscore<br />

Designators always begin with a letter.<br />

The underscore is used to display prefixes more clearly. The syntax is explained in the respective prefix<br />

section. Because data type designators are usually formed from capital letters, the individual words are<br />

put together with an underscore as a separator to increase readability. The underscore should not be<br />

used otherwise.<br />

400


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

d. Prefix Types<br />

Prefixes are used to quickly id<strong>en</strong>tify a designator’s function. The prefix types are as follows:<br />

<br />

<br />

<br />

<br />

Type – designator type such as Boolean or integer<br />

Scope – designator scope as either local or global<br />

Property – designator property such as retained or VAR_IN_OUT<br />

POU – POU type such as function or function block<br />

The g<strong>en</strong>eral syntax for variables and constants is as follows:<br />

<br />

[Scope][Property] _ [Type][Name]<br />

<br />

<br />

<br />

<br />

g_diFirstUserFault<br />

xEnable<br />

c_iNumberOfAxes<br />

gc_sMyGlobalStringConstant<br />

The g<strong>en</strong>eral syntax for POU’s is as follows:<br />

<br />

[POU] _ [Name]<br />

<br />

<br />

<br />

<br />

FB_AxisController<br />

FB_HeatGun<br />

P_Main<br />

F_GetLeftString<br />

401


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

e. Scope Prefix<br />

Scope prefix indicates the scope of variables and constants. You can see if it is a local or a global variable<br />

or a constant from the scope prefix.<br />

Global variables are indicated by a lower case "g". A lower case "c" is added to global constants.<br />

VAR_GLOBAL CONSTANT<br />

gc_diMaxFaults : DINT := 100; (* Maximum Quantity of Active Faults *)<br />

gc_diMaxEv<strong>en</strong>ts : DINT := 100; (* Maximum Quantity of Ev<strong>en</strong>ts *)<br />

END_VAR<br />

VAR_GLOBAL<br />

g_stMasterFaultList<br />

g_stMasterEv<strong>en</strong>tList<br />

g_xReset<br />

: ST_FAULTLIST;<br />

: ST_EVENTLIST;<br />

: BOOL;<br />

END_VAR<br />

Scope Prefix Type Use Example<br />

No prefix VAR Local variable xEnable<br />

g_ VAR_GLOBAL Global variable g_xRunning<br />

gc_ VAR_GLOBAL CONSTANT Global constant gc_iCurr<strong>en</strong>tRecipe<br />

Table 3.5 Scope Prefix<br />

402


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

f. Type Prefix<br />

Type prefixes id<strong>en</strong>tify the data type of variables and constants. The IEC 61131-3 standard data type<br />

prefixes are listed in the following table.<br />

Type Prefix Type Use (Bytes) Example<br />

x BOOL Boolean (1) xName<br />

b BYTE Byte (8) bName<br />

w WORD Word (16) wName<br />

dw DWORD Double Word (32) dwName<br />

si SINT Short Integer (8) siName<br />

i INT Integer (16) iName<br />

di DINT Double Integer (32) diName<br />

usi USINT Unsigned Short Integer (8) usiName<br />

ui UINT Unsigned Integer (8) uiName<br />

udi UDINT Unsigned Double Integer (32) udiName<br />

r REAL Floating Point Value (32) rName<br />

lr LREAL Long Floating Point Value (64) lrName<br />

date DATE Date (32) dateName<br />

tod TOD Time of Day (32) todName<br />

dt DT Time and Date (32) dtName<br />

t TIME Time Duration (32) tName<br />

s STRING Character String (x Chars + 1) sName<br />

p POINTER Pointer pxName<br />

a ARRAY Array adiName<br />

e ENUM List Type eMotorType<br />

403


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

Type Prefix Type Use (Bytes) Example<br />

st STRUCT Structure stRecipe<br />

fb FUNCTION BLOCK Function Block fbTrigger<br />

Table 3.6 Standard Date Type Prefixes<br />

The type prefix can also be composites, for example, for pointers and arrays. The pointer or array is<br />

listed first, followed by the prefix of the pointer type or array type as the following examples show:<br />

piCounter<br />

aiCounter<br />

paiRefCount<br />

astList<br />

: POINTER TO INT;<br />

: ARRAY [0..10] OF INT;<br />

: POINTER TO ARRAY [1..10] OF INT;<br />

: ARRAY[0..gc_diMaxFaults] OF ST_FAULT;<br />

404


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

g. Property Prefix<br />

Property prefixes are used for id<strong>en</strong>tifying the properties of variables and constants as shown in the<br />

following table:<br />

Property Prefix Type Use Example<br />

c_ VAR CONSTANT Local constant c_xName<br />

r_<br />

VAR RETAIN<br />

Remnant variable type<br />

retain<br />

r_xName<br />

p_<br />

VAR PERSISTENT<br />

Remnant variable type<br />

persist<strong>en</strong>t<br />

p_diName<br />

i_ VAR_INPUT Input variable of POU i_xEnable<br />

q_ VAR_OUTPUT Output variable of POU q_xError<br />

iq_ VAR_IN_OUT In/out variable of POU iq_stParameters<br />

AT %IX<br />

ati_<br />

AT %IB<br />

AT %IW<br />

Direct access to input<br />

memory<br />

ati_bName<br />

AT %ID<br />

AT %QX<br />

atq_<br />

AT %QB<br />

AT %QW<br />

Direct access to output<br />

memory<br />

atq_bName<br />

AT %QD<br />

AT %MX<br />

atm_<br />

AT %MB<br />

AT %MW<br />

Direct access to<br />

memory location<br />

atm_bName<br />

AT %MD<br />

405


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

Table 3.7 Property Prefix<br />

NOTE: Do not declare constants as RETAIN or PERSISTENT.<br />

The name of the AT-declared variable also contains the type of the target variable. It is used like the type<br />

prefix:<br />

atm_rMyVar1 AT %MW0 : REAL;<br />

atm_rMyVar2 AT %MW4 : REAL;<br />

406


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

h. POU Prefix<br />

The program organization units defined in IEC 61131-3 are:<br />

<br />

<br />

<br />

<br />

Function<br />

Function block<br />

Program<br />

Action<br />

The designator is composed of a POU prefix and as short a name as possible (e.g. FB_GetResult). Just like<br />

a variable, the first letter of each word in the POU name is capitalized. We recomm<strong>en</strong>d that you form a<br />

composite POU name from a verb and a noun. The prefix comes with an underscore before the name<br />

and id<strong>en</strong>tifies the type of POU on the basis of the following table:<br />

POU Prefix Type Use Example<br />

P_ PROGRAM Program P_RecipeManagem<strong>en</strong>t<br />

FB_<br />

FUNCTION_BLOCK<br />

Function block<br />

declaration<br />

FB_AxisController<br />

F_ FUNCTION Functions F_GetLrealString<br />

A_ ACTION Action A_GetCommand<br />

Table 3.8 POU Prefix<br />

407


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

i. Structures<br />

The name of each structure data type consists of a prefix ST_ and a short, meaningful description in<br />

upper case (e.g. ST_STATION_NUMBER). If several words have be<strong>en</strong> put together, they are separated by<br />

an underscore. Each compon<strong>en</strong>t of the structure must be id<strong>en</strong>tified with a type prefix.<br />

TYPE ST_FEED_PARAMETERS :<br />

(* Parameters for MC_MoveVelocity FB *)<br />

STRUCT<br />

lrVel : LREAL := 100.0;<br />

lrAcc : LREAL := 2000.0;<br />

lrDecel : LREAL := 2000.0;<br />

lrJerk : LREAL := 10000.0;<br />

eDirection<br />

: MC_Direction := MC_Positive_Direction;<br />

END_STRUCT<br />

END_TYPE<br />

lrStopPos : LREAL := 0.0;<br />

Declaration example:<br />

stAxis1Feed : ST_FEED_PARAMETERS;<br />

408


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

j. List Types<br />

The name of a list type consists of a prefix ET_ and a short, meaningful description in upper case (e.g.<br />

ET_WORKING_DAY). If several words have be<strong>en</strong> put together, they are separated by an underscore. The<br />

individual elem<strong>en</strong>ts of list types are id<strong>en</strong>tified with the prefix E_.<br />

TYPE ET_EVENT_TYPES :<br />

(<br />

E_EVENT_NO_EVENT := 0,<br />

E_EVENT_FAULT_ACTIVE := 1, (* Fault Just Occurred *)<br />

E_EVENT_FAULT_RESET := 2, (* Fault Is Gone and Acknowledged By AutoReset *)<br />

E_EVENT_FAULT_ACK := 3, (* Fault Is Are Gone and Ack By Reset Input *)<br />

E_EVENT_USER_1 := 10 (* User Ev<strong>en</strong>t *)<br />

);<br />

END_TYPE<br />

Variables and constants declared as a list type are prefixed with a lower case:<br />

eMyEv<strong>en</strong>t : ET_EVENT_TYPES;<br />

NOTE: 2 bytes of memory are reserved for each list variable.<br />

409


Chapter: App<strong>en</strong>dix I – Variable Naming Conv<strong>en</strong>tion<br />

k. Libraries<br />

Designators contained within a library and the library name itself is prefixed with a code to quickly<br />

id<strong>en</strong>tify the source and to match the designator with the library.<br />

<br />

<br />

MyLib_gc_diMaxConvCount<br />

MyLib_ConveyorControl.lib<br />

410


Chapter:<br />

54.Good Programming Practices<br />

a. Comm<strong>en</strong>ts<br />

Comm<strong>en</strong>ts are ess<strong>en</strong>tial for understanding source code; however, each individual line of code does not<br />

need to be comm<strong>en</strong>ted. Limit your comm<strong>en</strong>ts to the necessary minimum. It is more important to keep<br />

code clear and understandable. This minimizes the amount of comm<strong>en</strong>ts required. If all POUs and<br />

variables have meaningful names, comm<strong>en</strong>ts can be shorter. However, if the code is difficult to<br />

understand and there are no comm<strong>en</strong>ts, ev<strong>en</strong> the programmer will have trouble understanding it after a<br />

short time. If variables have be<strong>en</strong> giv<strong>en</strong> unusual values, for example, it is extremely important to explain<br />

the reason for this to prev<strong>en</strong>t future misunderstandings. Write your comm<strong>en</strong>ts so that they are not only<br />

notes for the programmer but can also be understood by third parties.<br />

b. Array Indexing<br />

Array should always be index starting at zero to prev<strong>en</strong>t range errors. This typically occurs wh<strong>en</strong> the<br />

variable used to index an array is not initialized properly as shown below.<br />

iCurr<strong>en</strong>tRecipe : INT;<br />

astRecipes : ARRAY[1..10] OF ST_RECIPE;<br />

The problem is corrected as follows:<br />

astRecipes : ARRAY[0..10] OF ST_RECIPE;<br />

The first elem<strong>en</strong>t of the array, 0, is either not used or used as a default.<br />

c. Program Calls<br />

Par<strong>en</strong>thesis should be used wh<strong>en</strong> calling programs and actions as shown below:<br />

<br />

P_SearchData();<br />

411


Chapter:<br />

Index<br />

A<br />

Actions .................................................................. 28, 96, 97<br />

AMS ...................................... 20, 21, 22, 178, 179, 375, 379<br />

Array ....................................... 103, 104, 106, 317, 398, 406<br />

F<br />

FBD .......................................................... 12, 77, 79, 83, 170<br />

I<br />

IL 12, 13, 77<br />

Instruction List ........................................................... 405<br />

LD 12, 77, 78<br />

L<br />

P<br />

PLC 10, 11, 12, 13, 14, 15, 16, 22, 23, 25, 26, 29, 41, 42, 43,<br />

45, 57, 59, 65, 66, 67, 68, 69, 72, 73, 74, 75, 76, 77, 84,<br />

87, 107, 108, 109, 110, 112, 132, 133, 139, 140, 144,<br />

153, 155, 156, 165, 168, 199, 200, 202, 204, 208, 215,<br />

216, 217, 218, 220, 221, 222, 225, 228, 230, 263, 266,<br />

267, 268, 269, 270, 271, 273, 275, 281, 284, 285, 290,<br />

297, 298, 299, 300, 305, 309, 311, 315, 318, 320, 323,<br />

329, 330, 337, 369, 370, 374, 375, 376, 378<br />

POU .8, 67, 68, 69, 75, 84, 97, 135, 153, 163, 164, 165, 166,<br />

170, 171, 186, 187, 196, 200, 205, 206, 210, 214, 240,<br />

265, 270, 284, 285, 286, 288, 289, 394, 396, 400, 401,<br />

402<br />

Priorities ........................................................................... 34<br />

R<br />

Registration ......................................... 23, 24, 50, 58, 63, 64<br />

Remote .............................................. 21, 22, 37, 58, 59, 379<br />

S<br />

SFC ........................................................... 12, 77, 80, 81, 135<br />

ST 12, 13, 77, 81, 82, 135, 164, 187, 326, 366, 367, 397,<br />

399, 403, 406<br />

T<br />

<strong>TwinCAT</strong> 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,<br />

25, 26, 29, 30, 31, 32, 37, 38, 46, 47, 48, 49, 50, 57, 58,<br />

59, 60, 61, 62, 63, 64, 65, 69, 70, 77, 82, 86, 88, 107,<br />

110, 112, 132, 133, 134, 139, 168, 170, 171, 172, 175,<br />

177, 178, 263, 268, 290, 298, 299, 304, 306, 307, 310,<br />

311, 312, 318, 320, 335, 337, 340, 369, 374, 375, 378,<br />

379, 380, 384, 385, 387, 391<br />

412

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!