You are on page 1of 412

Beckhoff New Automation Technology

TwinCAT 2

Revised: November 8, 2013 Brian McClure b.mcclure@beckhoff.com

Preface

This Manual is intended for anyone who is interested in the TwinCAT software. From electricians, to electrical engineers, and even computer scientists; all levels of experience can benefit from the material covered in this manual. The material is a result of the combined efforts of many engineers within Beckhoff Automation. We have reviewed and revised the information in an effort to make it as precise and correct as possible; however, nothing is perfect. But, we would like for it to be. If you find any issues, or items that you think need more explanation, please let us know by contacting the author at b.mcclure@beckhoff.com.

Revision Notes V3.0.0 Added Chapter Digital I/O This chapter covers the first section of The Inspection Conveyor utilizing Digital Inputs and Outputs to control the conveyor. Index Added Table of Contents and Page numbering modified V3.0.1 Added Code Changes to PLC Overview Added Lamp Test to Trouble shooting Index Updated Page Number Wrapping Fixed Added - Labs

I.

Contents
II. TWINCAT OVERVIEW 11 11 18 26 44 45 45 47 62 64 64 68 69 72 77 83 87 96 97 99 102 106 108 112 130

1. 2. 3. 4.

OVERVIEW SYSTEM SERVICE SYSTEM MANAGER PLC CONTROL

III. TWINCAT SOFTWARE INSTALLATION 5. TWINCAT VERSIONS 6. SOFTWARE, DOWNLOAD & INSTALLATION 7. LICENSING AND REGISTRATION IV. PLC OVERVIEW 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. IDE PROGRAMS DATA TYPES AND CONVERSIONS VARIABLES LANGUAGES FUNCTIONS FUNCTION BLOCKS ACTIONS STRUCTURES ENUMERATIONS ARRAYS BOOT PROJECT SOURCE CODE DOWNLOAD CODE CHANGES

V. PLC PROGRAMMING THE INSPECTION CONVEYOR

22. MACHINE CONTROL WITH TOP-DOWN PROGRAMMING 23. DIGITAL I/O VI. TROUBLE SHOOTING 24. 25. 26. 27. 28. 29. 30. LAMP TEST CODE SEQUENCING BREAK POINTS FLOW CONTROL GLOBAL SEARCH CROSS REFERENCE SCOPE VIEW

130 206 241 241 256 260 265 271 277 283 290 290 301 302 305 305 306 306 310 313 314 314 315 316 317 318 318 318 318 320 322 322 322 322 323

VII. LABS 31. LANGUAGES 32. LINEAR SCALING USING A RATIO 33. LINEAR SCALING USING AN EQUATION VIII. CAMMING 34. PREFACE 35. INTRO TO TCMC2.LIB A. OVERVIEW B. MIGRATION FROM TCMC TO TCMC2 C. STATUS INFORMATION 36. WHEN TO USE A CAM TABLE A. OVERVIEW B. GEARING C. LINEARLY INCREASING GEAR RATIO (DYNAMIC) D. CAM TABLE 37. CREATING A CAM TABLE WITH FUNCTION BLOCKS A. OVERVIEW B. DEFINING THE POINTS ON THE CAM TABLE I. MOTION FUNCTION POINT II. SAMPLE CODE: 38. DEFINING THE CAM TABLE IN THE PLC A. OVERVIEW B. MC_CAM_REF I. EXAMPLE 1: POSITION TABLE STRUCTURE DESCRIPTION II. EXAMPLE 2: STRUCTURE DESCRIPTION OF A MOTION FUNCTION

C.

MC_TABLETYPE I. SAMPLE CODE: 39. CREATING THE CAM TABLE A. OVERVIEW B. MC_CAMTABLESELECT I. SAMPLE CODE: 40. IMPORTING A CAM TABLE FOR VERIFICATION A. OVERVIEW B. CREATING A BLANK TABLE C. IMPORTING THE CAM TABLE 41. CAMMING THE TWO AXES TOGETHER A. OVERVIEW ONCE THE CAM TABLE HAS BEEN DEFINED, VERIFIED, AND CREATED; THE TWO AXES ARE NOW READY TO BE CAMMED TOGETHER. B. MC_CAMIN I. SAMPLE CODE: 42. CHANGING A TABLE POINT VIA THE PLC A. OVERVIEW B. MC_WRITEMOTIONFUNCTIONPOINT C. MC_SETCAMONLINECHANGEMODE D. MC_CAMACTIVATIONMODE I. SAMPLE CODE: 43. MOTION FUNCTIONS VS. POSITION TABLES A. POSITION TABLES B. MOTION FUNCTIONS C. DEFINITION OF A POINT D. POINT STRUCTURE E. POINT TYPES 44. CAM DESIGN TOOL A. OVERVIEW B. CREATING A CAM TABLE I. MASTER TAB II. SLAVE TAB C. GRAPHIC WINDOW D. TABLES WINDOW I. FUNCTION TYPES II. COMMANDS 45. CAM TABLE SCALING A. OVERVIEW B. MC_CAMSCALING C. MC_CAMSCALINGMODE I. EXAMPLE:

324 324 325 325 325 326 327 327 327 330 333 333 333 333 335 336 336 336 337 339 340 342 342 344 345 345 346 347 347 348 353 354 355 357 358 359 361 361 361 363 364

II.

46. A. 47. A. B. C. 48. A. B. C. D. E. 49. A. B.

SAMPLE CODE: CYCLIC CAM PLATES WITH LIFT MC_STARTMODE CAM OUT AND RESTARTING OVERVIEW MC_CAMOUT MC_HALT MC_CAMIN APPENDIX AXIS COUPLING WITH CAM PLATES LINEAR CAM PLATES CYCLIC CAM PLATES WITHOUT LIFT CYCLIC CAM PLATES WITH LIFT UNCOUPLING AND RE-COUPLING FOR CYCLIC CAM PLATES WITH LIFT DIAGNOSTICS OVERVIEW ERROR FORMAT

366 367 369 371 371 372 373 375 375 375 377 378 379 380 380 380 385 385 398 398 399 399 399 400 400 400 400 401 402 403 405 407 408 409 410 411 411

IX. REMOTE CONNECTIONS 50. EMBEDDED CONTROLLERS X. APPENDIX I VARIABLE NAMING CONVENTION 51. SCOPE 52. PROGRAMMING SYSTEM SETTINGS A. FONT B. TAB WIDTH 53. NAMING A. GENERAL B. CASE SENSITIVITY C. VALID CHARACTERS D. PREFIX TYPES E. SCOPE PREFIX F. TYPE PREFIX G. PROPERTY PREFIX H. POU PREFIX I. STRUCTURES J. LIST TYPES K. LIBRARIES 54. GOOD PROGRAMMING PRACTICES A. COMMENTS

B.

ARRAY INDEXING C. PROGRAM CALLS

411 411

1 0

II.

TwinCAT Overview
1. Overview
The Windows Control and Automation Technology The Beckhoff TwinCAT software system turns any compatible PC into a real-time controller with a multi-PLC system, NC axis control, programming environment and operating station. TwinCAT replaces conventional PLC and NC/CNC controllers as well as operating devices with: open, compatible PC hardware embedded IEC 61131-3 software PLC, software NC and software CNC in Windows NT/2000/XP/Vista, Windows 7, NT/XP Embedded, CE programming and run-time systems optionally together on one PC or separated connection to all common fieldbuses PC interface support data communication with user interfaces and other programs by means of open Microsoft standards (OPC, OCX, DLL, etc.)

Architecture TwinCAT consists of run-time systems that execute control programs in real-time and the development environments for programming, diagnostics and configuration. Any Windows programs; for instance, visualization programs or MS Office programs, can access TwinCAT data via Microsoft interfaces, or can execute commands. A practical oriented software solution TwinCAT offers a precise time base in which programs are executed with the highest deterministic features, independently of other processor tasks. The real-time load on a PC is set with TwinCAT; defined operating behavior is achieved in this way. TwinCAT indicates the system load for programs that are running. A load threshold can be set in order to assure a defined computing capacity for the operating programs and for Windows NT/2000/XP/Vista. If this threshold is exceeded, a system message is generated.

11

Chapter: TwinCAT Overview

TwinCAT supports system diagnosis The general use of hardware and software from the open PC world requires some checking: Unsuitable components can upset the PC system. Beckhoff has integrated a practical indicator of the real-time jitter, giving administrators an easy way to evaluate the hardware and software. A system message during operation can draw attention to incorrect states. Start/Stop behavior Depending on the setting, TwinCAT is started and stopped manually or automatically. Since TwinCAT is integrated into Windows NT/2000/XP/Vista and Windows 7as a service, an operator is not needed to start the system: switching on is enough. Restarting and data backup When a program is started or restarted, TwinCAT loads programs and remnant data. To back up data and to shut down Windows NT/2000/XP/Vista and Windows 7 correctly, a UPS (uninterruptible power supply) is of great value. World-wide connection through message routing remote connection is inherent to the system According to the requirement for operating resources, the TwinCAT software devices can be distributed: TwinCAT PLC programs can run on the PCs or on Beckhoff Bus Terminal Controllers. A message router manages and distributes all the messages, both in the system and via TCP/IP connections. PC systems can be connected with each other via TCP/IP; Bus Terminal Controllers are integrated via serial interfaces and fieldbuses (EtherCAT, Lightbus, PROFIBUS DP, CANopen, RS232, RS485, Ethernet TCP/IP). World-wide access Since standard TCP/IP services of NT/2000/XP/Vista/CE and Windows 7 can be used, this data can be exchanged across the world. The system offers scalable communication capacity and timeout periods for the supervision of communications. OPC provides a standardized means for accessing many different SCADA/MES/ERP packets.

12

Chapter: TwinCAT Overview

PLC and Motion Control on the PC TwinCAT I/O universal I/O interface for all common fieldbuses Many PC fieldbus cards from various manufacturers are supported. It is possible to operate more than one fieldbus card per PC. Master and slave functionality is supported, depending on the selected fieldbus card. The fieldbus cards can be configured and diagnosed conveniently via the TwinCAT System Manager. TwinCAT I/O includes the TwinCAT real-time system for operating the fieldbuses and a DLL interface to application programs. TwinCAT PLC the central pillar of automation software Conceived as a pure software PLC, TwinCAT PLC allows up to four virtual PLC CPUs, each running up to four user tasks, on one PC. The PLC program can be written in one or more of the languages provided for in the IEC 61131-3 standard: IL (Instruction List), LD (Ladder Diagram), FBD/CFC (Function Block Diagram), SFC (Sequential Function Chart) and ST (Structured Text).

TwinCAT PLC running under the Windows NT/2000/XP/Vista operating systems includes both the programming environment and the run-time system, so that an additional programming device is not required. Under the CE operating system and the embedded operating systems for the series BX and BC controllers, only TwinCAT run-time is available. Program modifications are implemented via network-capable powerful communication with the run-time system. Programming can be done locally, via TCP/IP or via the fieldbus (BXxxxx and BCxxxx). Chapter: TwinCAT Overview

13

IEC 61131-3 advanced programming standard for all Beckhoff controllers The TwinCAT PLC is programmed in accordance with IEC 61131-3 independently of the manufacturer. TwinCAT supports all the IEC 61131-3 programming languages with convenient editors and a fast, effective compiler, so that the development cycle for the creation even of large PLC programs of several megabytes can be short. Incremental compilation prevents long turnaroand times. Only genuinely new sections are compiled. Powerful editor features, such as autoformat, autodeclare or find and replace enable fast programming. For all programming languages, the project comparison function facilitates differences to be identified and accepted if appropriate. If a project (comments, directories, etc.) is to be translated into a language other than the original language, all terms can be exported into a table, translated and re-imported. If a team is dealing with the development, all objects (blocks, data types, lists) can be managed within a source code management tool via the TwinCAT Engineering Interface. This enables changes to be traced back and differences between individual versions to be displayed. The concept of the instantiation of function blocks, in which each instance is associated with its own data, leads naturally to object-oriented and structured programming styles. All common data types specified in IEC 61131-3 are supported. Multi-dimensional fields and structures are possible, as are enumeration and subrange types. TwinCAT PLC is certified for the languages IL and ST (base level). The online change function can be used for code and/or data modifications while the PLC is running, providing maximum data retention. Source code can be stored in the target system (except for BCxxxx series controllers). The criteria analysis function is very helpful for the detection of process errors. Code can very easily be reused via the convenient library manager. For know-how protection, multi-stage password protection can be applied to programs and libraries. Many target platforms one tool The PLC programs created with TwinCAT PLC can be executed on a number of target platforms. Apart from Industrial PCs and the Embedded PCs, the PLC project can also be loaded into the BC and BX series fieldbus controllers from Beckhoff. Program development and debugging proceed in the same working environment, regardless of which unit is executing the program. Extensive supplementary libraries As an extension to the blocks defined by the IEC language standard, Beckhoff offers a wide range of supplementary libraries for the execution of tasks typical in automation technology: e.g. libraries for controlling electrical and hydraulic axes via TwinCAT NC, serial communication libraries, system libraries for message outputs, write/read files, control technology blocks, etc. Chapter: TwinCAT Overview

14

Helpful practice tools Extensive fault finding functions in TwinCAT PLC facilitate the solution of problems either on site or via remote maintenance. For this purpose, the PLC programming environment in TwinCAT offers: Online Monitoring Power Flow (flow control) Break Points Sampling trace of PLC variables Single step Watchlist Call hierarchy Forcing of variables. In addition, the TwinCAT ScopeView (a software oscilloscope) can be used to record one or several variables simultaneously. TwinCAT NC Motion Control on the PC A software NC consists of: positioning (set value generation and position control) integrated PLC with NC interface operating programs for commissioning purposes I/O connection for axes via fieldbus With TwinCAT NC, the position controller is calculated on the PC processor as standard. It exchanges data cyclically with drives and measurement systems via the fieldbus. Chapter: TwinCAT Overview Central NC positioning on the PC The computing capacity of a PC enables axis motion simultaneously with the PLC, whereby the position controller is usually calculated on the PC: The computing capacity of a PC enables many axes to be positioned simultaneously. TwinCAT enables a PC to process the operating programs, the PLC and the NC at the same time. The division of the system load is supported by TwinCAT with appropriate functions.

15

Analytical path calculation The algorithms that TwinCAT NC/NC I/CNC uses to control axes take account of the dynamic parameters of the axis: speed, acceleration and jerk. In this way, the axes are moved at any time within the limits of what is dynamically possible, and are precisely analytically coordinated. A range of different regulation algorithms are available in order to reduce the deviations from the ideal trajectory that will occur in practice. Individual or joint Based on the normal methods for positioning an individual electrical axis, moving from its starting point to its destination (point-to-point positioning), TwinCAT NC also allows the coordinated movement of a number of axes in multi-stage master-slave operation (e.g. gearing functions or cam plates) to be executed. TwinCAT NC I further allows the interpolated path sequencing described in accordance with DIN 66025 to be carried out involving up to three axes. Software PLC included TwinCAT combines software NC and software PLC to form a powerful controller. The communication between the two packages is a pure software/software channel with minimum delay times. The NC functionalities are called from the PLC program via standardized, PLCopencertified function blocks. Axis movements can be simulated without hardware; the actual value is instructed to ideally track the set value, and the complete machine flow is checked. TwinCAT ScopeView is helpful for commissioning and maintenance. It records all axis variables such as position, speed, acceleration and jerk.

Convenient commissioning Commissioning is simplified significantly by the configuration and diagnostic dialogs offered in the TwinCAT System Manager. For each axis, all main data are displayed at a glance. The axes can be moved via function keys. Special functions such as couplings, cam plates or distance compensation can be triggered and observed via the System Manager. A convenient dialog enables the dynamic parameters of an axis to be determined. Chapter: TwinCAT Overview

16

TwinCAT NC I axis interpolation in three dimensions TwinCAT NC I (interpolation) is the NC system for linear and circular interpolated path movements of axis groups each involving two or three drives. The system includes interpreter, set value generation and position controller. PLC functionality is integrated, as is the connection of the axes with the fieldbus. The interpreter interprets the code described in DIN 66025. Comprehensive PLC libraries enable interaction between NC and PLC. NC programs, for example, can be loaded directly from the PLC program into the interpreter. TwinCAT CNC the software CNC for toughest requirements TwinCAT CNC expands TwinCAT NC I with classic CNC features: Up to 32 interpolating axes and comprehensive coordinate and kinematic transformations are possible. Parts programming is carried out according to DIN 66025 using high-level language extensions. TwinCAT CNC can operate with up to 64 axes or 32 path axes and controlled spindles that can be distributed across up to twelve CNC channels. In a CNC channel, up to 32 axes can be interpolated simultaneously, enabling even the most difficult motion tasks to be solved.

17

Chapter: TwinCAT Overview

2. System Service
The TwinCAT System Service is represented by the TwinCAT icon in the Windows system tray.

The TwinCAT System Service can be accessed through the TwinCAT icon in the windows system tray (Right-Click and Left-Click provides the same menu)

From this menu the other parts of the TwinCAT system can be accessed and the TwinCAT System Properties can be changed

18

Chapter: TwinCAT Overview

The General tab of the system properties provides the version number and registration information of TwinCAT Note that the 30 day counter has started and the Reg. Key is empty

19

Chapter: TwinCAT Overview

The upper half of the System Tab shows which TwinCAT servers are installed The lower half provides settings for how TwinCAT will act when windows boots up

Auto Boot: Disable The TwinCAT System Service will boot in Stop Mode Enable The TwinCAT System Service will boot in Run Mode This would be the preferred setting on a running machine

Config Mode The TwinCAT System Service will boot in Config Mode ADS services are running, remote communication is possible Chapter: TwinCAT Overview

Auto Logon: Enabling this option and providing a User Name and Password will allow for the Windows Logon screen to be bypassed, this is ideal for a running machine but not for a development laptop as this information is stored in plain text in the windows registry.

Note: See the security section for protecting the windows registry.

20

AMS Router Automation Machine Specification

AMS Router Automation Machine Specification The AMS Router is the communication router for TwinCAT Every piece of information that travels from one piece of software to another must go through the AMS Router

AMS NetID xxx.xxx.xxx.xxx.1.1 The address of the local TwinCAT Service Every address on the network should be unique The default address is generated by the IP address of the network card with an additional .1.1 added to the end The first four octets of the address can be changed to any number between 0 and 255. They do not have to match the IP address The last two octets should not be changed as .1.1 represents the external address and other values are used internally Chapter: TwinCAT Overview

21

Remote Computers The lower section provides a list of remote computers than have been previously configured for AMS communication Remote Computers can be manually added or removed from here The list of computers is loaded when TwinCAT enters either Config or Run mode, therefore if a computer is added or removed from here, TwinCAT must be restarted to update the list of Target Computers in the System Manager

22

Chapter: TwinCAT Overview

PLC Up to 4 PLC Run-Times can be configured The path of the Boot Project can be changed The selection to enable the Boot Project and Retain Data can be made

23

Chapter: TwinCAT Overview

Registration The System ID is needed for licensing It is advised that on a running machine the customer should record the System ID and Registration Key. In the event of a Hard Disk failure these two numbers and the new System ID can be used to generate a new Registration Key Otherwise the original PO is needed to generate a new Registration Key

24

Chapter: TwinCAT Overview

The System Manager and PLC Control can also be accessed through this menu or the Windows Start menu Additionally the local TwinCAT System can be placed into its different modes Stop Mode The system is not capable of communication and no services are running

Config Mode The ADS Router is running and communication is possible Scanning of hardware is done is this mode only I/O values are updated at the hardware level

Run Mode (Requires License beyond 30 day Trial) All services are enabled and running if configured to do so (i.e. Boot Project)

25

Chapter: TwinCAT Overview

3. System Manager
The TwinCAT System Manager is used to configure the links between Hardware and Software I/O Configuration All Fieldbus Hardware PLC Configuration PLC Run-Times (up to 4) NC Configuration Axes (real and virtual), Cam Tables, Interpolation Channels System Configuration Properties of the Target System and Real-Time Usage

26

Chapter: TwinCAT Overview

Menus and Controls File Menu Allows for creating a new file or opening a saved file. Additionally provides a way to open the CurrentConfig.tsm file from the Boot folder, by using Open from Target also referred to as The Red Folder.

27

Chapter: TwinCAT Overview

Actions Any time a change is made to the System Manager, the Activate Configuration must be done to implement this change into the running system. Note: The first 6 commands in the Actions menu will be sent to the Target system either local or remote.

28

Chapter: TwinCAT Overview

The tree view on the left provides access to the configurations of the system manager. When an item on the left is selected its information will be displayed on the right. Items can be added to the System Manager be Right-Clicking on an existing item. Become familiar with this, almost every item you wish to add in both the system manager and the PLC will be done by RightClicking and select Add... or Append System Configuration Provides information and settings for the overall TwinCAT System The settings available from the Properties of the TwinCAT icon can be accessed from here on a remote system.

29

Chapter: TwinCAT Overview

General The TwinCAT version is provided here in bold The Choose Target button can be used to access a remote TwinCAT system.

30

Chapter: TwinCAT Overview

Boot Settings can be used to set the TwinCAT Mode on startup and the Auto Logon When pointed to a remote system these setting will be applied to the remote system. The Apply button must be used, and an Administrator level user name and password must be provided.

31

Chapter: TwinCAT Overview

Real-Time Settings

Settings Here the Base Time is set; no task can be set to a faster interval than the base time. The CPU limit of 80% means that TwinCAT will consume no more than 80% to run all of its tasks.

32

Chapter: TwinCAT Overview

Online The Real Time Usage is graphed and the limit from the Settings tab is indicated by the thick green line System Latency should be no more than 5 micro seconds

Note: Image taken from a laptop with power save features and CPU throttling enabled, both of these create latency problems.

33

Chapter: TwinCAT Overview

Priorities The list of tasks and their priorities can be seen here

34

Chapter: TwinCAT Overview

Additional Tasks

Task 1 (added by Right-Clicking on Additional Tasks) These additional tasks are used by C++ code to talk to variables that are linked to hardware I/O They can also be used for simulation

35

Chapter: TwinCAT Overview

When used for simulation the Auto start must be checked

36

Chapter: TwinCAT Overview

Route Settings

Current Routes The Remote Computers shown in this list are the same as in the Properties of the TwinCAT icon.

37

Chapter: TwinCAT Overview

NC Configuration (Numerical Control) This is the software based motion controller of TwinCAT. The software side of all axes are configured here.

Axes The software limits the total number of axes to 255, the real limit is the amount of CPU and RAM in the computer.

38

Chapter: TwinCAT Overview

The Online tab provides an overview of the status of all axes

39

Chapter: TwinCAT Overview

Axes 1 Online The Online tab of each axis provides a useful interface to setup and troubleshoot an axis

40

Chapter: TwinCAT Overview

PLC Configuration

IEC Project The PLC editor will create a .tpy file that contains addressed variables that can be linked to hardware. The name of the PLC project file is shown directly below the PLCConfiguration The IEC1131 Tab shows the path of where the .tpy file was located when it was added to the project. If addressed variables are added to the PLC program the ReScan button can be used to update the list of variables in the System Manager

41

Chapter: TwinCAT Overview

Standard Task The default task in the PLC is the Standard task and runs every 10ms

Inputs of the PLC Program Input variables have a yellow icon, Output variables have a red icon

42

Chapter: TwinCAT Overview

Once a variable has been linked (connected) to hardware the icon changes as below

43

Chapter: TwinCAT Overview

4. PLC Control
The PLC Control provides the user with a combination of tools. The IEC 61131-3 Language editors A Visualization Editor Task Configuration Utility The Beckhoff Compilers specific to the Target Hardware (BC, BX, CX-ARM, X86)

44

Chapter: TwinCAT Overview

III.

TwinCAT Software Installation


5. TwinCAT Versions
There are several builds within each version New builds are released primarily to accommodate new hardware New versions are released when features are added A Brief History TwinCAT 2.6 Build 315 August 2, 1999 TwinCAT 2.7 TwinCAT 2.8 Change from wsm to tsm Use of XML for system configuration Config Mode for scanning hardware

TwinCAT 2.9 TwinCAT 2.10 TcMC2.lib

TwinCAT 2.11 Build 1552 TwinCAT 2.11 R2 Change in preparation for TwinCAT 3 Chapter: TwinCAT Software Installation Required for CX5000

TwinCAT 2.11 R3

45

Release Notes:
Changes from 2.10 to 2.11 TwinCAT Base System
Integration of MDP (Modular Device Profile a generic interface for device information) Integration of configuration tool for AX5xxx drives Optimized behavior for use with Windows Vista and Windows 7 Optimization for TwinCAT running on Quad-core and Octo-core CPUs Time synchronization with EL6692 (EtherCAT bridge) Time synchronization with EL6688 (IEEE 1588/Precision Time Protocol) New modular structure of I/O drivers Base for new supplement products like TwinCAT Kinematic Transformation

In addition to the features available in 2.11, the following new features were implemented in Release 2 (2.11 R2):
support for CX50xx controllers support for CU2508 (port multiplier) support for AX5805 (safety card for AX5xxx) support for EP1908 new Motion Control feature: multi-cam extended slave error handling for NC multi-linear coupling (multi-GearIn)

In addition to the features available in 2.11 R2, the following new features were implemented in Release 3 (2.11 R3):
CX50xx, additional interfaces like EtherCAT Slave EL7201 support (NC PTP) Supports new PCIe fieldbus adapters New Phasing functionality for NC PTP

46

Chapter: TwinCAT Software Installation

6. Software, Download & Installation


The TwinCAT software can be downloaded from www.beckhoff.com Select Download from the top of the page

47

Chapter: TwinCAT Software Installation

Scroll down to the Software section and select TwinCAT 30 days version

Select TwinCAT

48

Chapter: TwinCAT Software Installation

The form must be filled in with a valid email address Below the form you can select the version and build of TwinCAT you would like to download After selecting the Registration button an email will be sent; to the address provided, containing a link to download the software

49

Chapter: TwinCAT Software Installation

Selecting the link in the email will start the download

Double-Click the exe file to start the installation process The file name will match the version number and build that you selected during the registration process

50

Chapter: TwinCAT Software Installation

If you receive the following warning select Run

Select your preferred language and then select next

51

Chapter: TwinCAT Software Installation

The InstallShield Wizard will begin the install process

52

Chapter: TwinCAT Software Installation

When prompted select next

53

Chapter: TwinCAT Software Installation

Accept the license agreement and select next

54

Chapter: TwinCAT Software Installation

Fill in the User Name and Company Name (This information will be viewable in the software) Use DEMO for the serial number

55

Chapter: TwinCAT Software Installation

Selecting the level of TwinCAT to install (All levels are inclusive of lower levels) CP Includes the ADS driver, used for OPC Server, Beckhoff Control Panels, and other ADS communication I/O Includes the system manager for configuring hardware, used when writing C/C++ code to control the I/O PLC Includes the IEC 61131-3 PLC editor and the Beckhoff compilers NC PTP Numerical Control for Point to Point motion with associated libraries NC I Numerical Control for Interpolated motion with associated libraries

56

Chapter: TwinCAT Software Installation

Registration Type 30 Day demo Full functionality for 30 days, after 30 days TwinCAT will no longer go into run mode. Development and Remote connections are still possible. Re-installing will provide another 30 days Register now A System ID will be provided for you to call in with The recommended practice is to select the 30 Demo and then send screenshots of the System ID via email. Licenses can be provided within 24 hours except weekends and holidays

57

Chapter: TwinCAT Software Installation

Select the additional features to install with TwinCAT The desired features should be selected here, afterwards select Next to continue

TwinCAT I/O Allows the direct access to IO via a DLL. Can be installed with TwinCAT PLC or TwinCAT NC PTP. TwinCAT Scope View A software Oscilloscope for monitoring variables in real time TwinCAT Cam Server A Cam tool for setting outputs on Lightbus, has never been sold in North America, replaced by newer technology Chapter: TwinCAT Software Installation TwinCAT EDS and GSD files files for DeviceNet and Profibus hardware TwinCAT Remote Manager For managing different versions of TwinCAT on one PC. TwinCAT Drive Manager Used for Configuring the AX5000 servo drives TwinCAT BACnet/IP BACnet Server for building Automation and HVAC systems.

58

Specify the path for the TwinCAT installation The default path is highly recommended, project files that the user creates can be stored in any desired location

59

Chapter: TwinCAT Software Installation

Specify the Program Folder for the TwinCAT installation The default path is highly recommended, project files that the user creates can be stored in any desired location

The installer will now install the needed components Chapter: TwinCAT Software Installation

60

You must reboot the PC after the installer has completed

After rebooting the PC you will see the TwinCAT icon in the Windows System Tray TwinCAT is in Stop Mode by default

61

Chapter: TwinCAT Software Installation

7. Licensing and Registration


Single left click the TwinCAT Icon in the system tray, and select properties

62

Chapter: TwinCAT Software Installation

Once properties is selected the TwinCAT System Properties window will appear. Select the last tab (Registration) on the top of the window. At this point you can take a screen capture of the current System ID and report it to your Inside Sales Representative.

63

Chapter: TwinCAT Software Installation

IV.

PLC Overview
8. IDE
The Integrated Development Environment (IDE) of TwinCAT provides a complete set of development tools for the PLC. TwinCAT PLC Control puts a simple approach to the powerful IEC languages at the disposal of the PLC programmer. Use of the editors and debugging functions is based upon the proven development program environments of advanced programming languages.

The Left column provides four tabs at the bottom.

64

Chapter: PLC Overview

POUs Program Organizational Units This will contain the code written by the programmer, Programs, Function Blocks, and Functions

Data Types Here the programmer can create Structures and Enumerations to be used in the PLC code

Visualizations Interface screens for use by Maintenance personnel or Operators can be created.

65

Chapter: PLC Overview

Resources The resources tab contains several items. The Global Variable Lists, Library Manager, PLC Configuration, and Task Configuration are all accessible from this tab.

A POU is opened by double-clicking on it.

66

Chapter: PLC Overview

The POU contains 2 parts, the Declaration section, and the Code section. The first line of the declaration section defines the type of POU and the name of the POU. Following this is the local variable declaration, the variables that are local to this POU are defined between the Keywords VAR and END_VAR. Below the Declaration section is the Code section, this part of the window will contain the PLC code of the POU.

Additionally there is a Message Window at the bottom.

The Message window will show Errors, Warnings, and compile information.

67

Chapter: PLC Overview

The Message Window can be hidden or shown, from the Window menu select Messages or the keyboard shortcut Ctrl + ESC

9. Programs
A program is a POU which returns several values during operation. Programs are recognized globally throughout the project. All values are retained from the last time the program was run until the next. Programs are called from either a PLC Task or another Program. If a one program calls another program, and if the values of the program are changed, then these changes are retained the next time the program is called, even if the program has been called from within a different program. Programs can call all types of POUs, they can call Functions, Function Blocks, and other Programs. By default when a new Project is started, a Standard Task is created that calls the Program MAIN, from MAIN all other POUs are called. Because Programs are recognized globally, the local variables declared inside of them will referenced by first using the name of the program and then the name of the variable, separated by a dot .. In the below example; the variable bStart is defined with an address as a local variable in MAIN, in the PLC-Configuration of the TwinCAT System Manager the variable will be MAIN.bStart, whereas a variable defined globally will only show the name of the variable.

68

Chapter: PLC Overview

10. Data Types and Conversions


Elementary data types form the foundation of the programmers tools to represent and use information. The elementary data types within TwinCAT Plc Control are below.

69

Chapter: PLC Overview

The BOOL data type is used to define a Boolean or Bit-wise variable. The BOOL data type takes the value of either TRUE or FALSE at runtime. The conversion operator BOOL_TO_INT may be used to convert a TRUE/FALSE into 1/0, respectively. Declaration syntax: VariableName : BOOL := InitialValue ; Example: pushButton01 : BOOL ;

Declaration with Initial Value: drainValveOpen : BOOL := TRUE ; Use the {BYTE, WORD, DWORD, SINT, USINT, INT, UINT, REAL, LREAL} data set to define an appropriate value range for a variable. Declaration syntax: VariableName : DataType { := <Initial_Value } ; Example: (*Declares a double-word sized variable named MyDWord with the initial value of 12345*) MyDWord : DWORD := 12345 ;
The data set {BYTE, WORD, DWORD} are considered bitwise data types; an individual bit of the data type may be extracted using the following syntax: VariableName.bitOffset NOTE: bitOffset cannot be a variable e.g. it must be a constant Example: Declaration: VAR Status : WORD; (*Example Status Word*) END_VAR Use: IF Status.6 THEN (* Evaluate Bit 6 of the WORD Status *) (* Execute necessary logic *) END_IF Floating point number representation and subsequently numerical calculations are realized with the {REAL, LREAL} data set. The Plc Control editor recognizes a number as an integer unless explicitly defined as a REAL type. For example, 15/9 input into a typical calculator will result in 1.667; however, the Plc Control editor evaluates such an expression in integer division resulting in the value 2. One must explicitly code 15.0/9.0 or, equally, REAL#15/REAL#9 to evaluate as a floating point calculation.

70

Chapter: PLC Overview

The STRING data type is utilized to define and use ASCII character strings. Declaration Example: VariableName : STRING { := StringValue } ; (* Declares STRING-type variable MyString with initialized value of This is my string *) MyString : STRING := This is my string ; A STRING always occupies a memory size equal to the string size plus one byte for a null termination character. The default size for a STRING is 80 bytes + one byte for a null terminating character, the maximum size is 255 bytes + one byte for a null terminating character.

The {TIME, TIME_OF_DAY, DATE, DATE_TIME} data set supports duration measurement and/or time stamping. The necessary data type is selected depending on scope of measurement. For example, DATE_TIME for a time stamp vs. TIME for, say, the duration of a timer. The Standard attempts to remove a major source of errors compared to conventional Ladder-Language PLC programming errors with a mandate of Strong Data Types. The Plc Program Compiler should be able to detect when a programmer, for example, attempts to assign a WORD variable to another variable of type TIME. As such, Conversion Functions are integrated within Plc Control to provide explicit conversion from one elementary data type to another. The conversion operation is defined as a function.

The function returns the arguments value as the desired, converted data type. The general scheme is defined as DataType1_TO_DataType2 ( VariableToConvert ) Where DataType1 is the data type of the variable being converted and DataType2 is the desired data type. For example, the code snippet converts MyWordVariable from WORD to INT (integer). WORD_TO_INT(MyWordVariable) The variable, MyReturnedInt, is assigned to this converted value. MyReturnedInt := WORD_TO_INT(MyWordVariable) ;

71

Chapter: PLC Overview

11. Variables
A Variable is a name given to a location in memory that stores a value A Variable has up to 5 properties 1. Name 2. Size (Defined by the Type) 3. Value 4. Memory Location 5. PLC Address In accordance with IEC 61131-3 a variable name must adhere to the following rules 1. Must begin with a Letter or an Underscore 2. Can followed by Letters, Underscores, or Numbers No distinction is made between Uppercase and Lowercase Letters Special characters cannot be used (!@#$%^&*) Blanks or Spaces are not allowed Repeated or Sequential Underscores are not allowed

Descriptive abbreviations aid in understanding the value that is held by the variable

72

Chapter: PLC Overview

The use of abbreviated data types in the name of the variable help in the understanding of what the variable is. By placing a lower case b in front of all BOOLEAN variables the person reading the program will know that this variable is of type BOOL without having to refer to the variables declaration. Additionally using a Capital letter at the beginning of each word in the variable name will aid in understanding For example: bStartConveyor is much easier to read and understand than bstartconveyor

Declaration All variables must be defined between VAR and END_VAR Place the name of the variable to the left of the colon Place the data type to the right of the colon VariableName : VariableType ; bStart : BOOL ; (*bStart is of type BOOL*) iProductNumber : INT; (*iProduct Number is of type INT*) lrPressure : LREAL ; (*lrPressure is of type LREAL*) Chapter: PLC Overview

Variable Scope Global Variables can be read and written to from anywhere in the PLC program

73

Local Variables can only be written to from within the POU where they are defined The local variable of any POU can be read by first accessing the POU instance that the variable is defined in and then using the . to access the local variables defined within that POU Local variables cannot be written to from another POU

74

Chapter: PLC Overview

Initial Values All Variables have the option of assigning an initial value This value will be written to memory when the PLC starts, after which the code of the PLC will control the value bStart : BOOL := FALSE ; (*bStart is of type BOOL and has an initial value of FALSE*) iProductNumber : INT := 1 ; (*iProduct Number is of type INT and has an initial value of 1*) lrPressure : LREAL := 2.3 ; (*lrPressure is of type LREAL and has an initial value of 2.3*)

It is also possible to assign an initial value to a variable in an instance of a function block fbTON1 : TON := (PT := T#1s) ; (*fbTON1 is of type TON and the PT input has an initial value of 1 second*)

Constants Variables defined as Constants cannot be written to by the PLC Constants are declared similar to initial values Use of the keyword Constant at the beginning of the declaration section signals the compiler that the variable is a constant.

75

Chapter: PLC Overview

Remnant Variables Remnant variables can retain their value throughout the usual program run period. These include Retain variables and Persistent variables. Retained Data These variables maintain their value even after an uncontrolled shutdown of the controller as well as after a normal switching off and on of the controller or at the command 'Online', 'Reset. When the program is run again, the stored values will be processed further. A concrete example would be a piece-counter in a production line that recommences counting after a power failure. Retain-Variables are reinitialized at a new download of the program unlike persistent variables. Variables stored with RETAIN are initialized after a "Rebuild all" of the PLC program. With a Reset all RETAIN variables are initialized.

Persistent Data These variables are stored with the complete symbol. Therefore symbol generation must be selected. Persistent variables conserve their old values after a "Rebuild all" of the PLC program. To initialize the PERSISTENT variables choose Reset all. On a TwinCAT shutdown the persistent variables are written in a special file. This file contains the old values of the persistent variables and is read on a TwinCAT start.

76

Chapter: PLC Overview

12. Languages
The IEC 61131-3 specifies 5 languages for writing PLC code. TwinCAT provides these plus 1 extra IL Instruction List LD Ladder Diagram FBD Function Block Diagram SFC Sequential Function Chart ST Structured Text CFC Continuous Function Chart (Non-IEC)

IL Instruction List IL has a similar structure to assembly language and is comparable to the statement list language provided by Siemens. In IL only 1 command can be processed per line of code. The command is then followed by a variable or a literal value. For example the following will increase the variable Speed by a value of 5

77

Chapter: PLC Overview

LD Ladder Diagram LD was created with the intention of representing the electrical wiring diagrams of relay logic LD is a graphical language that displays a power rail on each side that represents the supply and the common of the wiring diagram The below examples shows a common latching circuit in LD

78

Chapter: PLC Overview

FBD Function Block Diagram FBD is a graphical language that is similar to an electronic circuit diagram The below example has the same functionality as the above latching circuit

79

Chapter: PLC Overview

SFC Sequential Function Chart SFC; although defined as a language, is better thought of as a way to organize code and control the sequence of operation Each Step and Transition in SFC has code inside of it that can be written in any of the other languages including SFC

80

Chapter: PLC Overview

ST Structured Text ST is a high level language which looks similar in syntax to PASCAL ST is the most powerful and flexible of all the languages When using ST it is important to remember that the variable being written to (the output) is on the left The below example provides the same latching circuit operation as the ones above

81

Chapter: PLC Overview

CFC Continuous Function Chart (Non-IEC) CFC is an additional language provided within TwinCAT, yet it is not a part of the IEC 61131-3 Standard CFC is a graphical language very similar to FBD The order of execution is determined by the number, and is able to be modified by the programmer

82

Chapter: PLC Overview

13. Functions
A Function is a re-useable piece of code that will process the defined inputs and return a single result AND, OR, SQRT, SIN, COS, GT, LE are all examples of Functions The programmer can also create their own Functions that normally involve more complicated tasks, such as converting a temperature value from Celsius to Fahrenheit or scaling an analog input value from 0-32767 to 0-10 Functions can be called from any other POU type, but are only capable of calling other functions Note: Functions have no memory space and therefore they do not retain any values from one PLC scan to the next. Each function starts new each PLC scan.

Declaration The Declaration of a Function contains 4 parts The Name of the Function The Return type of the Function The Variables to be passed into the Function The local variables used by the Function The Name of the Function Following the Beckhoff coding convention, the name of the Function starts with F_ The same IEC rules for naming of variables apply to the naming of Functions

Following the Name of the Function is the Return Type A Function can only Return one variable

83

Chapter: PLC Overview

The Variables to be passed into the Function In the below example iTempInCelsius is the Variable that is being passed into the function

84

Chapter: PLC Overview

Code The working code of the Function Tf := 9/5 * Tc + 32 In the example code the integer value iTempInCelsius is converted to a real number. This is a Function that is built into TwinCAT The literal values of 9 and 5 both have a decimal point to signify them as REAL numbers and not integers. Before writing the calculated value to the output the number is converted back to an integer. (Yes, this does cause inaccuracy due to rounding.)

85

Chapter: PLC Overview

Implementation iTempC is declared as an INT with an initial value of 100 iTempF is declared as an INT with no initial value In the code the Function F_CtoF is called and iTempC is passed into it. The result of the Function is then stored in iTempF.

86

Chapter: PLC Overview

14. Function Blocks


A Function Block is a re-useable piece of code that can have multiple inputs and outputs. Function Blocks are instantiated; therefore each time a Function Block is used it must be assigned a unique instance name. Each instance receives its own space in memory and therefore will retain its values from one PLC scan to the next. TON, CTU, R_Trig, FB_FileOpen, ADSREAD, are just a few examples of Function Blocks The programmer can also create their own Function Blocks to perform a variety of tasks. Function Blocks can be called by Programs or other Function Blocks. Function Blocks can all other Function Blocks and Functions. Note: It is possible to call a Program from a Function Block. Just because you can doesnt mean you should. TwinCAT provides you with the flexibility to do many things (some good, some not so good), once you understand the inner workings of the software you will understand why doing this can cause problems, all of which must be handled by the programmer.

87

Chapter: PLC Overview

Declaration The Declaration of a Function Block contains 4 parts The Name of the Function Block The Variables to be passed into the Function Block The Variables to be passed out of the Function Block The Variables that are internal to the Function Block The Name of the Function Block Following the Beckhoff coding convention, the name of the Function Block starts with FB_ The same IEC rules for naming of variables apply to the naming of Function Blocks

88

Chapter: PLC Overview

The Variables to be passed into the Function Block Below the Enable, Time On, and Time Off values are being passed into the Function Block

89

Chapter: PLC Overview

The Variables to be passed out of the Function Block Below the Output variable has been added

90

Chapter: PLC Overview

The Variables that are internal to the Function Block Below the two timers to be used have been instantiated fbTON is of type TON fbTOF is of type TOF

91

Chapter: PLC Overview

Code The working Code of the Function Block Below the two timers are called with their instance name The := symbol signifies that a value of the variable is being passed into the FB and the => symbol signifies that a value of the variable is being passed out of the FB

92

Chapter: PLC Overview

The IN of fbTON is TRUE if bEnable is TRUE and fbTOF.Q is FALSE What is fbTOF.Q? Anytime the . symbol is used it signifies that the variable on the right exists inside of the variable on the left. Q is an output of a TOF, therefore calling the instance name fbTOF followed by . will allow access to the variables that are declared inside of fbTOF

93

Chapter: PLC Overview

Also notice that fbTON.Q is passed into fbTOF, this will cause the two timers to toggle based on the values of tTimeOff and tTimeOn Finally the output of fbTOF is passed to bPulse. bPulse is the output of FB_Pulse This could have been done with the following bPulse := fbTOF.Q;

94

Chapter: PLC Overview

Implementation fbPulse1 is of type FB_Pulse fbPulse1 is an instance of FB_Pulse bSwitch is passed into the bEnable input of fbPulse1 tTimeOn and tTimeOff are assigned literal values in the proper TIME format bPulse is passed out of fbPulse1 into bLight1 fbPulse2 is a second instance of FB_Pulse. It is coded differently but works exactly the same.

In the above example of fbPulse2 the input variables are first assigned; followed by a call of the Function Block instance on line 6. This is extremely important to understand; if line 6 was removed from the code then the Function Block would never run. The line of code that calls the instance name and uses the parentheses is the line of code that updates the values inside of the Function Block.

95

Chapter: PLC Overview

15. Actions
Actions are used to organize code. Both Programs and Function Blocks can use Actions (They are not allowed with Functions). Actions share their local declaration section with the POU they are attached to. To add an Action to a POU, right-click on the POU and select Add Action The name of the Action must follow the rules of the IEC Standard, the language can be of any type In the below example the Program MAIN has four Actions. A_Enable is called from the code of MAIN. The instance of fbMC_Power_Ax1 is called inside of the action A_Enable, but is declared locally in MAIN

96

Chapter: PLC Overview

16. Structures
Structures are used to define elements of a larger item and are commonly referred to as custom data types A temperature sensor; for example, is more than just the temperature value The status of the Analog input card, the scaling parameters, and the offset are all possible elements that are directly related to the temperature sensor In order to keep these elements together and make the code more re-useable a structure of these elements can be created

Declaration The structure is created with its element names and data types Initial values can be given A structure can also contain other structures

97

Chapter: PLC Overview

Implementation A structure must be instantiated just like a Function Block After typing the instance name of the structure place a . immediately after it and the intellisense window will appear, showing what elements exist inside of the structure

The elements in a structure can be written to and/or read from

98

Chapter: PLC Overview

17. Enumerations
Enumerations can be used to assign a variable name to a number. Enumerations can be used in two different ways; with or without being instantiated. If the Enumeration is not instantiated then the Enumeration works similar to a list of constants. If the Enumeration is instantiated then the instance of the enumeration will hold the variable of the current value of the Enumeration When the Enumeration is defined the first variable in the list will be assigned a value of 0, the variables following will be assigned their values in ascending order Manual = 0 Semi_Auto = 1 Auto = 2

If a variable in the list is explicitly assigned a value then the following variables will be incremented from this value Manual = 1 Semi_Auto = 2 Auto = 3

99

Chapter: PLC Overview

Manual = 1 Semi_Auto = 2 Auto = 3 Maintenance = 10 Unknown = 11

Using Enumerations in this manner allows for easier understanding of the code when it is being read In this Case statement the Variables in the Enumeration are used to represent the number equivalent of iStep1. As iStep1 changes in value the Case statement will change states iStep1 can be assigned a numerical value or an Enumeration variable The displayed online value of iStep1 will always be an INT value because iStep1 is declared as an INT

100

Chapter: PLC Overview

If an instance of the Enumeration is declared then the instance of the Enumeration holds the variable name of the value of the Enumeration If iStep2 is of type E_Mode then iStep2 holds either Manual, Semi_Auto, or Auto

101

Chapter: PLC Overview

18. Arrays
An Array is a list of data, the data in the Array can be of any type An Array can contain more than one dimension Think of a notebook of graph paper The column on a single sheet of paper would be a 1 dimensional array The entire sheet with its rows and columns would be a 2 dimensional array The notebook with all of its sheets would be a 3 dimensional array

1 Dimensional Array The Array is defined from 1 to 10 of type INT This Array will hold 10 integer values

The position in the Array is referred to as the index The Array name along with an index can be used just like any other variable

102

Chapter: PLC Overview

2 Dimensional Array The Array is defined from 1 to 10 and 1 to 3 of type String This Array will hold 30 (3*10) String values The comma , is used to denote the multiple dimensions of the array

3 Dimensional Array

103

Chapter: PLC Overview

Initializing each index of an array

Initializing multiple indexes with the same value 2(3) indicates that the first 2 Indexes will be given a value of 3

The above 2 examples can be mixed together

104

Chapter: PLC Overview

Indexing through an Array with a FOR loop A FOR loop can be used to easily fill an Array or read the values in an array The following will set all values in the Array to 0

105

Chapter: PLC Overview

19. Boot Project


The TwinCAT Boot Project is used on a production machine as the PLC code to be run when TwinCAT starts. The Boot Project must be enabled and also created.

Enabling Enabling the Boot Project is done through the TwinCAT System Service Right Click on the TwinCAT icon in the Windows system tray and select properties Click on the PLC tab and place a check mark in the Run-Time

106

Chapter: PLC Overview

Creation

To create the Boot Project: login with the PLC and select Create Boot Project from the Online menu

107

Chapter: PLC Overview

20. Source code Download


The use of the Source Code Download allows for a copy of the code to be placed on the device. This copy of the code can be opened later either directly on the PC or through a remote connection. To create the Source Code Download file you must be logged in to the PLC From the Online menu select Sourcecode Download

108

Chapter: PLC Overview

The Source Code file will be created in the C:\TwinCAT\Boot folder The name of the file will be TCPLC_S_x.wbp where x will be a number from 1 to 4 which represents the runtime number.

To open the Source Code Download file, Select Open from the File Menu

On the Open file dialog select the PLC button

109

Chapter: PLC Overview

Select the correct Target System Type

Select the Run-Time on the Target

110

Chapter: PLC Overview

The files will be copied in to your local Upload folder C:\TwinCAT\PLC\Upload If any of the files already exist you will be asked if you would to overwrite these files

The code will then open

If the source code download has not been performed you will get the following error message

111

Chapter: PLC Overview

21. Code Changes


To make changes on an existing system, use the following steps when making changes to a PLC program to ensure the best results. Verify PLC program file matches running code Edit Code Compile Code Load Changes Save File Create Boot project Perform a Source Code Download

Verify the PLC Program To ensure the correct version of the code is being edited you should first verify the PLC Program file matches the PLC Code that is running in TwinCAT. Open the file From the Online menu select Login If the PLC Program goes online without prompt, then you can be certain that the code matches exactly.

You will also see in the bottom right corner of the PLC Control the current status of the PLC

112

Chapter: PLC Overview

When logging in to the PLC, if you receive a prompt; pay close attention to the question being asked, and the available options.

Online Change Notice at the end of the question you are notified that this will be an (ONLINE CHANGE) Yes This will perform the Online Change described in more detail on next page

No Dont use this option. If you accidentally press it, simply Log Out of the PLC Cancel Cancels the operation Load all Stops the execution of the PLC and Loads all of the Code including the changes. The PLC must be started again.

Online Change The following is a description of the internal process for an Online Change that is only suitable for your understanding. The actual process is much more intricate and complicated Imagine the below represents the RAM of the Computer and the programs that are currently using it The PLC Code runs from the first line to the last line and then repeats.

113

Chapter: PLC Overview

When an Online Change is performed The New PLC Code is loaded into a separate memory location When the current scan of the PLC Code has completed, instead of looping back around. The PLC will start running the New PLC Code on the next scan.

The New code is now repeated each PLC Scan and the memory where the old code was located is released, to be used by another process

114

Chapter: PLC Overview

Load Changes The other possible option when logging in to the PLC is that the code is different enough that the PLC is not able to do an Online Change In the below prompt notice that it does not say Online Change. It simply asks if you would like to Download the new program? Yes Will stop the PLC and load the code. The PLC must be started after this. No - Dont use this option. If you accidentally press it, simply Log Out of the PLC Cancel Cancels the operation

At this point we are still trying to verify that we have the correct version of the PLC program One of 3 possibilities have happened 1. The PLC logged in without prompt 2. Online Change 3. Download the Program

If you are able to Login without a prompt then you can go to the next section about Editing the Code If an Online Change or a Download of the Program is required then a couple of things need to be considered. In both situations the first choice should be to look for another copy of the program. An Online Change is required for many things. Anything from adding a variable to changing the value of a timer.

115

Chapter: PLC Overview

If a change was made, but the PLC Program was closed without saving the change, then an Online Change will be required to Login. However, this will be loading the older version of the code. A Download will be required if the computer has been restarted and the Boot Project was not updated. Also, if the auxiliary files for the PLC Project do not exist (someone emailed only the .pro file) then a Download of the program will be required. Locating the PLC Project can be done by searching for the .pro file on the hard drive. Press the Start button or the Windows key on the keyboard, then press the F3 key In the Search Box type in *.pro and press the Enter key

Depending on the size of the hard drive this might take a few minutes

Source Code Download File The last option is to open the Source Code Download file When created this file is saved in the C:\TwinCAT\Boot directory as TCPLC_S_1.wbp for the first PLC Run-Time To open this file, open the PLC Control, then select Open from the File menu

116

Chapter: PLC Overview

In the Open File Dialog window, select the PLC button

Select the CPU type, and click OK

117

Chapter: PLC Overview

Select Run-Time1, and click OK

Click Yes, all

If the file exists it will be opened If this file has been kept up to date and matches with the PLC Code that is running inside of TwinCAT, then you should be able to Login with this Code. If it does not match exactly then you will have to perform either an Online Change or a complete Download of the PLC Program.

118

Chapter: PLC Overview

Edit the Code Now the we have a program that matches with the running code, we can make the required changes. We will start with a simple Ladder program that needs a contact changed from Normally Open to Normally Closed

Left-Click on the symbol of the Contact to select it. Notice the dotted selection box around the symbol Hold the Ctrl key and press N This will Negate or invert the Contact This same command will work for changing a NC contact to NO

119

Chapter: PLC Overview

It is also possible to Right-Click on a symbol and select one of the options from the context menu When making changes to code in FBD (Function Block Diagram) the same steps apply. In FBD the location of the cursor is extremely important The options in the context menu will change based on the location of the cursor Chapter: PLC Overview

120

Cursor inside the box Changes here effect the box itself

Cursor on the input of the box Changes here are for the way the input interacts with the box

121

Chapter: PLC Overview

Cursor on the right side of the box Changes here effect what will be to the right of the box, typically an Assignment to another variable or another box

Cursor on the Assignment Changes here will affect the specific output or add more outputs

122

Chapter: PLC Overview

Compile Code Once the changes have been made, it is time to Compile the code and check for errors. From the Project menu select Build This will compile the code In the message window you should see

If you have any warnings they can typically be ignored. Note: If you use the Rebuild All command, your Retain Data will be initialized. If you have an error, press the F4 key

The F4 key will take you to the location of the first error in the message window and also open the code to the location where the error was found.

123

Chapter: PLC Overview

Sometimes error messages can be misleading. Most of the time 1 problem will cause multiple error messages. The problem with the below line of code is that the ; is missing from the end of the line The error message says the problem is on Line 3. The reason for this is that the compiler ignores spaces. After the variable c the compiler is expecting to find a ; (End of Line) or an := (Assignment). It doesnt find it so it continues to line 2 and then line 3 Line 3 is the last line of code so this is where the compiler is at when the error is detected

The second error is caused by the first error When the first error is corrected the second error will no longer exist

124

Chapter: PLC Overview

Load Changes Once all of the errors have been corrected, the changes can be loaded into the PLC From the Online menu, select Login

Click Yes to perform an Online Change

If additional changes need to be made First Logout of the PLC and then repeat the process

125

Chapter: PLC Overview

Save File When you are done making changes the new File should be saved From the File menu, select Save This will replace the existing file on the hard drive with the current file and the changes

Boot Project Once all changes have been made, and before restarting TwinCAT a new Boot Project must be created. From the Online menu, select Create Boot Project If a new Boot Project is not created, then the next time that TwinCAT is restarted or the computer is rebooted, the old Boot Project will be loaded. If this happens then a Download of the program will be required before you can log in again. It is extremely important that the Boot Project be kept up to date and match the PLC Program.

126

Chapter: PLC Overview

Source Code Download From the Online menu select Sourcecode Download This will create a file in the C:\TwinCAT\Boot directory that can be opened later If this file is kept up to date, and matches the Boot Project then this file can also be used to Login to the PLC This file is also useful for keeping a copy of the code on a CX device that only has the TwinCAT Run-Time and not the full development

Options From the Project menu, select Options In the left column select Source download

127

Chapter: PLC Overview

Implicit at load Create a new source code download file every time a change is loaded

Notice at load Every time a change is loaded, ask the user if they would like to create a new source code download

Implicit on create boot project Each time a new boot project is created, also create an new source code download Note: If this option is selected then the source code download and the boot project will always match

Only on demand The source code download command must be manually given from the Online menu

128

Chapter: PLC Overview

How much data should be placed in the file All Files This will place everything inside the file, including all bitmaps for any visualizations If you have enough room on the hard drive, then this is the best option

Source code only This will only place the code and other auxiliary files needed for logging in to the PLC on the hard drive

Source code only(exclude compile info) Only the code A download must be performed to login to the PLC

129

Chapter: PLC Overview

V.

PLC Programming The Inspection Conveyor


22. Machine Control with Top-Down Programming
Intro This section is going to cover the design and programming of a modular conveyor. With each module a new concept and/or topic will be introduced. As the saying goes Prior proper planning, prevents poor performance. With that in mind the first topic will cover the overall machine control and the use of a state machine for automatic or manual operation. The first conveyor module will be for adding product to the system using only digital Inputs and Outputs. The second module will use an analog input to measure the size of the product. Next an analog output will be added to control the conveyor speed using a Variable Frequency Drive (VFD).

Machine Control/State Machine There are many ways to do overall machine control and to implement a state machine, both of which are outside the scope of this document. For the purpose of this document I have chosen to use a state machine that best serves the purpose of learning to use the TwinCAT software. The overall machine control will be handled in a CASE statement. The machine will have the following States: Undefined: When no State is defined by the PLC this will be the default State. This State is not allowed to be set by the operator. This State will be used when the machine is first powered on and when a problem in the PLC code occurs. Maintenance: Used for making adjustments to the machine or for troubleshooting individual components. Operations will be allowed in this State that could be harmful to the equipment. Access to this mode will be restricted. Manual: Used to start up the machine and prepare for operation, or to shut down the machine after Automatic operation. Requires operator intervention for all functions of the machine. Automatic: Used for routine production. The machine will process product based on the conditions of the I/O with minimal operator intervention.

130

Chapter: PLC Programming The Inspection Conveyor

Modular Conveyor System Each conveyor module will need to work as a standalone piece and also in conjunction with other modules in front of and/or after it. Using a photo eye at each end of the conveyor will aid in this process. For the programming of this system each conveyor module will be a Function Block; therefore, if multiples of a module are needed they can be easily instantiated. Additionally, standard data Structures for all conveyor modules will be used by each of the Function Blocks to aid in communication between modules. Machine data Structure: contains status information for the overall machine including the current State. Module data Structure: contains information about the configuration of the module, including information about the previous and following module.

Creating the program Open the PLC Control by selecting the TwinCAT icon in the Windows System Tray and the select PLC Control

131

Chapter: PLC Programming The Inspection Conveyor

From the File menu, select New

For most of this project we will not be connecting to hardware. Therefore everything will run in simulation on the computer you are using. Note: The TwinCAT 2 Run-Time is only available on Windows 32-bit Operating Systems In the Choose Target System Type window, select PC or CX (x86), then click on OK

132

Chapter: PLC Programming The Inspection Conveyor

In the New POU window the Type of POU should be a Program The Name of the new POU: should be MAIN The Language of the POU should be set to ST for Structured Text

Note: Even if you are an experienced programmer in one of the other languages, it is my recommendation that when starting a new project the MAIN program should always be done in ST. This will allow the programmer to easily call other programs and also easily comment out large parts of the program. Additionally I would advise that the MAIN program never be done in SFC, doing so will make using the special SFC flags much more difficult, if not impossible.

133

Chapter: PLC Programming The Inspection Conveyor

You should now have the following

Place a semicolon on Line 1 of MAIN. This is the smallest program you can write.

134

Chapter: PLC Programming The Inspection Conveyor

From the Project Menu, select Rebuild All

135

Chapter: PLC Programming The Inspection Conveyor

In the Message Window at the bottom, you should receive 0 Errors and 1 Warning.

The Warning is because we have not saved the file with a name.

136

Chapter: PLC Programming The Inspection Conveyor

From the File Menu, select Save As

The file can be saved anywhere you would like. I would recommend against saving it on the desktop, the PLC Control will also create other supporting files that will clutter your desktop quickly. I have created a folder called TwinCAT 2 Manual Samples directly on the root of my C:\ drive. Give your project a name and press the Save button. I would recommend that you use the same file name that I have used.

137

Chapter: PLC Programming The Inspection Conveyor

Adding a version number to your project name is an easy way to have multiple versions of the program, so that you can go back to a previous version later on. You will now see that the file name of the project is placed across the top of the PLC Control

Before writing any real code we will first declare all known variables that will later be connected to hardware. Select the Resources tab at the bottom of the left column

138

Chapter: PLC Programming The Inspection Conveyor

Expand the Global Variables folder by clicking on the + sign

In the Global Variables folder there are two lists by default. The Global_Variables and the Variable_Configuration The Variable_Configuration list is only used for the BC line of controllers. The Global_Variables list is included by default; however, on large machines it is good practice to create multiple lists to help organize the variables into smaller more manageable lists. Therefore, we are going to start by creating a couple of Global Variable Lists. Right Click on the Global Variables folder, select Add Object

139

Chapter: PLC Programming The Inspection Conveyor

Change the name of the list by adding _IO to the end of the name, and then click on OK Note: The name of this list must follow the IEC 61131-3 naming rules, the same as variable names. If it does not, or the name has already been used the OK button will be grayed out.

Double-Click on Global_Variables_IO This will open the Global Variable list. Place the cursor at the end of line 1 and press the enter key a couple of times.

140

Chapter: PLC Programming The Inspection Conveyor

Between the key words VAR_GLOBAL and END_VAR is where we will declare our variables. Note: Please refer to Appendix I Variable Naming Convention for a better understanding of the variable names used throughout this project. Comments can be added to the code by placing (* at the beginning of the comment, and *) at the end of the comment. All comments will turn green. (*Machine Control*) The following will be Boolean inputs of type BOOL, therefore when the hardware detects 24 Volts DC the PLC will represent this with TRUE, when the hardware detects 0 Volts DC the PLC will represent this with FALSE. gati_xMan_Auto_SS will be a two position Selector Switch between Manual and Auto. When the switch is in the Manual position the input will be off, when the switch is in the Auto position the input will be on. gati_xMaintenance will be a push button to request the State Machine to go into Maintenance gati_xReset will be a push button for resetting faults

141

Chapter: PLC Programming The Inspection Conveyor

(*Stack Lights*) The use of Stack Lights allows everyone in the area of the machine to easily know the status of the machine. The definitions of what the colors represent vary between industries and countries. For this project the following colors will be used as defined here: Yellow will be used when the machine is in Automatic Green will be used when the machine is in Manual Red will be used when a Fault is active Blue will indicate that the machine is in Maintenance Between Yellow, Green, and Blue only one of the can be on at any given time. Red can be on in addition to any of the others gatq_xAutoLight will be written with a value of TRUE when the machine is in Auto, thereby applying 24 Volts DC to the output and turning on the light. gatq_xManualLight will be written with a value of TRUE when the machine is in Manual, thereby applying 24 Volts DC to the output and turning on the light. gatq_xFaultLight will be written with a value of TRUE when the machine is Faulted, thereby applying 24 Volts DC to the output and turning on the light. gatq_xMaintenanceLight will be written with a value of TRUE when the machine is in Maintenance, thereby applying 24 Volts DC to the output and turning on the light.

142

Chapter: PLC Programming The Inspection Conveyor

Next we will create an Enumeration that will be used to represent the possible States of the State Machine. Select the Data Types tab at the bottom of the left column

143

Chapter: PLC Programming The Inspection Conveyor

Right-Click on the Data Types folder and select Add Object

Type in E_MachineState as the Name of the new data type, and click OK

You should now have the following

144

Chapter: PLC Programming The Inspection Conveyor

Data Types always default to a STRUCT, this can be changed to an Enumeration by simply removing STRUCT and END_STRUCT from lines 2 and 3 and replacing them with ();

When creating an Enumeration the first Variable will receive a value of zero by default, each value after that will be incremented by one. The variables of the Enumeration must be placed between ( and ) and each one separated by a comma ,.

145

Chapter: PLC Programming The Inspection Conveyor

Now would be a good time to save the changes that have been made. From the File menu, select Save. Or simply press and hold the Ctrl key and the press the S key.

Notice that the asterisk * and the end of the file name disappears. The asterisk is there to indicate that changes have been made but not saved. To check the Enumeration and the Global Variables for any possible typing errors go to the Project menu, and select Rebuild All

If you have any errors, they should be fixed before moving on. As an example I have removed the semicolon from the end of one of the Global Variable declarations. When preforming a Rebuild All this generates 2 errors, which can be seen in the Message Window

146

Chapter: PLC Programming The Inspection Conveyor

Place your mouse at the top of the Message Window

Click and Drag the bar upwards to see more of the Message Window

It is best to start with the first error in the list, many times one problem will create others for the compiler. The easiest way to find the first error in the list is to press the F4 key. Repeatedly pressing F4 will go to the next error in the list. You could also scroll through the error list and Double-Click on the error.

147

Chapter: PLC Programming The Inspection Conveyor

When the error is selected, the location of the error will be shown, and the line of code that has the problem will be highlighted. Repeatedly pressing F4 will go to the next error in the list. The full error message states that the complier is Expecting the end of line character or an assignment before seeing a new variable name. To the compiler the problem occurred on line 9, the appropriate way to fix the problem is to find the variable declared before line 9 and place the semicolon at the end of the line.

After fixing any errors you may have had, preform another Rebuild All from the Project menu. Once, you have zero errors, you will get 7 warnings. Generally speaking warnings can be ignored. These 7 warnings are created by the use of %I* and %Q* variables. The warning simply states that the VAR_CONFIG file has not been created for these variables. F4 will scroll through the warnings. Ignore them for now and continue on.

Now would be a good time to Save your project.

148

Chapter: PLC Programming The Inspection Conveyor

Finally, it is time to write some code. Click on the POUs tab at the bottom of the left column.

149

Chapter: PLC Programming The Inspection Conveyor

Double-Click on the MAIN program. Note: You may or may not have the small blue arrow next to the icon for MAIN. This blue arrow simply indicates that changes have been made to this POU that have not been downloaded into the running PLC.

In the local declaration section of MAIN define a variable called eStep as of type E_MachineState

The best way to do this is to first type in the new variable name eStep, then place a colon after it, then press the F2 key which opens the Input assistant. Chapter: PLC Programming The Inspection Conveyor

150

Select User defined Types from the left column and then E_MachineState, press OK

This will bring you back to the declaration section; place a semicolon at the end of the line.

By declaring eStep to be of type E_MachineState the value of the variable eStep will be the text in the Enumeration. eStep will be used as the condition variable of the CASE statement that will control the State Machine.

151

Chapter: PLC Programming The Inspection Conveyor

The general layout of a CASE statement is as follows:

The variable between CASE and OF must use an integer value (INT,DINT,SINT,USINT). Enumerations hold an integer value. The numbers that follow on the next lines represent the possible values of that variable. Therefore when iStep is equal to 0 the code between 0 and the next number will be run. The code following all other numbers will not be run. For example if iStep is equal to 10 then the code on lines 5 and 6 would be run the next line of code would be line 12, or the first line after the END_CASE command. The ELSE case is a safeguard, if iStep is ever set to a value that is not defined the code in the ELSE command will be run. The values of the condition variable are limited to integer values. In the above picture, values are skipped to allow for the possibility to easily add steps in between. It is generally a good practice to do this, otherwise when a step has to be added then all following steps must be changed. The value of iStep is set by conditions in the PLC code. The value can be changed from within the CASE statement or from outside the CASE statement. For our project the Enumeration is declared as having 4 possible values, therefore the need for skipping numbers is not necessary. However the ELSE command should always be included. Chapter: PLC Programming The Inspection Conveyor

152

Note: when using an Enumeration both of the above are valid; however, the use of the variable name from within the Enumeration makes the code easier to read. By default when the PLC starts all values are 0, unless given an initial value. To ensure that our state machine starts at zero, an initial value will be placed on the variable eStep. To do this, double-click on the variable eStep in the declaration section of MAIN. This will highlight the variable name

153

Chapter: PLC Programming The Inspection Conveyor

Press and hold the Shift key then press F2. The Declare Variable window will open

Place a zero in the Initial Value box, and click OK

The declaration of eStep now has an initial value of 0. The first thing we will setup is the control of the value of eStep. We have a Selector Switch for Manual or Auto and a pushbutton for Maintenance. With the initial value of eStep being 0 the case statement will be in E_Undefined. Inside this step we will set eStep to go to E_Manual. Chapter: PLC Programming The Inspection Conveyor

154

However, we should also look at the condition of the Selector Switch. The input is negated with the NOT command because the switch being in the ON position is for Auto.

Remember to use F2 for the Input Assistant to select gati_xMan_Auto_ss from the Global Variables

155

Chapter: PLC Programming The Inspection Conveyor

We now are able to put the machine into Manual Operation. From Manual, there needs to be a way to go into either Maintenance or Auto.

Now would be a good time to Save your project. It would also be a good time to check for errors. Go to the Project Menu and select Rebuild All Chapter: PLC Programming The Inspection Conveyor

You should get one error. Press F4 to go to the error.

156

Each value for the CASE statement must have some code in it. When the complier sees two values for eStep with no code in between them it causes an error. The easy way to avoid this is to place a semicolon after the colon. It should be removed later, but if you forget it wont hurt anything.

You will also need to do this after E_Auto and ELSE

If you have any other errors, please address them before moving on.

157

Chapter: PLC Programming The Inspection Conveyor

As the programmer it is your duty to ensure that all possible conditions are accounted for. Currently it is possible to get into the Auto state but it is not possible to get out of it. The selector switch will place the machine into the Manual state.

This is the same code that was used to go from E_Undefined to E_Manual. From the Maintenance mode, pressing the Maintenance push button will place the machine back into Manual.

In the ELSE command eStep will be set to E_Undefined.

158

Chapter: PLC Programming The Inspection Conveyor

The entire body of MAIN, now looks like the following

Now would be a good time to check for errors using Rebuild All from the Project menu, and save your project. At this point the control for the state machine is finished. Later in the section on Fault Handling we will add to the state machine for what needs to be done when a fault occurs. The plan is to have a function block for each conveyor module. Each function block will be capable of controlling the conveyor module in each possible machine state. Therefore the machine state will be passed into the function block. Before creating the function blocks, we will create the code that is going to call the function blocks.

159

Chapter: PLC Programming The Inspection Conveyor

In the POU column right click and select Add Object.

Name the POU P_MachineControl. Leave the Type as a Program and set the Language to ST for Structured Text. Then click on OK

160

Chapter: PLC Programming The Inspection Conveyor

Before writing any code in the new program we should call the program from MAIN. Double-click on MAIN to open it. Below the code for the CASE statement, place the cursor and press F2.

This will call the new program every PLC scan. The open and close parenthesis are not required but should be used to indicate that it is a POU call.

161

Chapter: PLC Programming The Inspection Conveyor

In the Input Assistant select User defined Programs from the column on the left, select P_MachineControl from the window on the right, then press OK.

Now double-click on P_MachineControl in the POU column. Later we will add code to this program for calling the Function Blocks that will control the machine. For now add a semicolon to prevent any build errors.

Next, add another program by right-clicking in the POU column and selecting Add Object

Name the new Program P_MachineMonitoring

In the Machine Monitoring program we will add some function blocks from a couple of libraries, to monitor things going on in the background.

162

Chapter: PLC Programming The Inspection Conveyor

First we will add the new library. From the Window menu, select Library Manager.

The STANDARD.Lib is always included in every project by default. The Standard library contains timers, counters, triggers, and other basic function blocks.

163

Chapter: PLC Programming The Inspection Conveyor

Under the STANDARD.Lib right click and select Additional Library.

The Open dialog box will open to the default location of C:\TwinCAT\PLC\Lib In this folder are all of the libraries that are included with the level of TwinCAT that you installed.

164

Chapter: PLC Programming The Inspection Conveyor

Add the TcUtilities.lib by either scrolling to the right or typing the name into the File name: box, if you choose to type in the name, you will notice that windows filters the results of possible options as you type.

After selecting TcUtilities.lib press the Open button. TcUtilities requires the use of TcBase and TcSystem, therefore these libraries are included as well. Chapter: PLC Programming The Inspection Conveyor

165

Select TcUtilities in the list of libraries.

Notice that libraries can contain POUs, Data Types, Visualizations, and Global Variables. In the POU column of the TcUtilities library expand the TwinCAT System folder and select TC_CpuUsage. This will display a picture of the Function Block as it would appear in the FBD language; it also displays part of the local variable declaration section for the Function Block. If the Beckhoff Information System is installed on your computer then it is possible to highlight the name of the Function Block and press F1 to view the documentation for the Function Block. Chapter: PLC Programming The Inspection Conveyor

166

The Tc_CpuUsage Function Block will monitor the percentage of the CPU that TwinCAT is using. In the POU column double click on P_MachineMonitoring. Chapter: PLC Programming The Inspection Conveyor

Now place the cursor on line 0001 in the code window and press F2 to open the Input Assistant

167

From the Input Assistant select Standard Function Blocks from the left column and then expand TcUtilities in the window on the right.

Scroll down to TwinCAT System and expand that folder

168

Chapter: PLC Programming The Inspection Conveyor

Select Tc_CpuUsage and click OK.

This will add a generic version of the Function Block to the code.

169

Chapter: PLC Programming The Inspection Conveyor

The name on line 1 is the Implementation name of the Function Block, everything between the open and close parenthesis are variables that are defined inside of the Function Block. When using large function blocks in Structured Text the variables are each placed on their own line to make them easier to view. Each variable is followed by either an input or output symbol and then a comma. The assignment statement := is used to indicate that the variable is of type VAR_INPUT, the output assignment => is used to indicate that the variable is of type VAR_OUTPUT. Each use of a Function Block will receive its own memory space; therefore, each Function Block must be given a unique instance name. Add fb to the beginning of the implementation name TC_CpuUsage.

When you click on any line other than line 1 the Declare Variable window will appear.

The Class drop down list will allow for the selection of where the variable is to be declared, leave this on VAR to declare it in the local variable declaration section.

170

Chapter: PLC Programming The Inspection Conveyor

Change the Type from BOOL to TC_CpuUsage, this can be done by either typing in the type or pressing the Ellipse button.

When you press the Ellipse button the Input Assistant will open and allow you to select the type from the list. Select Standard Function Blocks from the column on the left, then expand TcUtilites, then TwinCAT System, finally select TC_CpuUsage and click OK.

171

Chapter: PLC Programming The Inspection Conveyor

The Declare Variable window should look like the following.

Press OK, and notice that the instance of the Function Block has been declared in the local variable section.

Next the variables to be passed into the Function Block need to be added.

The NETID is the AMSNETID of the TwinCAT Run-Time that is to be read. According to the Documentation the variable type is T_AmsNetID, which is of type string with a length of 23 bytes.

172

Chapter: PLC Programming The Inspection Conveyor

In this example we are going to read the local CPU Usage, therefore the local AmsNetID can be provided. Click on your TwinCAT Icon in the windows system tray, the select Properties.

Select the AMS Router tab

The AMS Net ID can be copied from here.

173

Chapter: PLC Programming The Inspection Conveyor

In the code place an empty string after the assignment statement of NETID, then paste the AMS Net ID in between the quotes.

When using the local AMS Net ID it is also possible to just use an empty string , internally the Function Block will read the local AMS Net ID in this case. When the START input variable rises from False to True, internally the Function Block will execute an ADSREAD one time. Each rising edge that is seen on the START input will cause another read of the CPU usage. For now add the variable xReadCpuUsage to the START input.

174

Chapter: PLC Programming The Inspection Conveyor

When you click away from line 3 the Declare Variable window will appear. Leave it defined as a Local variable and a BOOL.

The TMOUT variable is the amount of time to wait for a response, before throwing a TimeOut error. If the input is left empty the default time of 5 seconds will be used. Time values always start with T# and must end with time unit being used. Place a time value of 500 milliseconds in the TMOUT variable.

We will now create local variables that the Function Block will write to.

175

Chapter: PLC Programming The Inspection Conveyor

Use the following variable names for the outputs and declare them as shown below.

Now would be a good time to compile the code and check for errors, by selecting Rebuild all from the Project menu. When there are no errors, save your project. A commonly used Function Block is NT_GetTime. This Function Block will read the Windows Clock each time the START input is triggered. The time value can then be added to log information.

176

Chapter: PLC Programming The Inspection Conveyor

Place the cursor on line 11 and press F2. Select Standard Function Blocks from the left column, expand the NT, W2K, XP, XPe, CE Operating System folder.

177

Chapter: PLC Programming The Inspection Conveyor

Select the NT_GetTime Function Block and press OK

The generic Function Block has now been added to the code.

178

Chapter: PLC Programming The Inspection Conveyor

Change the name to fbNT_GetTime.

Click away from line 11 and declare the Function Block as a type NT_GetTime.

179

Chapter: PLC Programming The Inspection Conveyor

Set the NETID to local by using an empty string. (Two single quotes, with no space between them.

Set the START variable to xGetTimeStart and declare it as Type BOOL. Set the TMOUT to 500ms. Set the output variables and declare them as they are below.

The local declaration section should have the following

180

Chapter: PLC Programming The Inspection Conveyor

Notice that stGetTimeValue is of Type TIMESTRUCT. This structure is defined inside of the TcUtilities library, and contains the following information.

wYear : Specifies the year: 1970 ~ 2106; wMonth : Specifies the month: 1 ~ 12 (January = 1, February = 2 and so on); wDayOfWeek : Specifies the day of the week: 0 ~ 6 (Sunday = 0, Monday = 1 and so on ); wDay : Specifies the day of the month: 1 ~ 31; wHour : Specifies the hour: 0 ~ 23; wMinute : Specifies the minute: 0 ~ 59; wSecond : Specifies the second: 0 ~ 59; wMilliseconds : Specifies the millisecond: 0 ~ 999; The out stGetTimeValue will hold values similar to the following.

From the POU column right-click and select Add Object

181

Chapter: PLC Programming The Inspection Conveyor

The previous two Function Blocks were provided by Beckhoff. It is also possible to create your own. In order to get regular updates of the CPU Usage the START input of the TC_CpuUsage Function Block needs to toggle between TRUE and FALSE repeatedly. To do this we will create a Function Block that pulses its output at a regular interval.

In the New POU window, name the POU FB_Pulse. The Type of POU should be Function Block. The language will be ST for structured text. Click OK to create the Function Block.

At the top of the declaration section you will see on line 1 that this is a Function Block not a Program or Function, the name of the Function Block is also included on this line. Following line 1 is the VAR_INPUT, VAR_OUTPUT, and VAR sections. In the VAR_INPUT section variables will be declared that have values passed into them from the calling code, the VAR_OUPUT section will declare variables that have their values passed out to the calling code. The VAR section will declare values that are only used internally within the Function Block.

182

Chapter: PLC Programming The Inspection Conveyor

In the VAR_INPUT section declare the following variables

i_xEnable :BOOL;

(*When TRUE the Function Block is Running, When FALSE the Function Block is stopped all values a reset and the outputs are FALSE*) (*Length of TIME for the Output to be TRUE*) (*Length of TIME for the Output to be FALSE*)

i_tTimeOn : TIME; i_tTimeOff : TIME;

In the VAR_OUTPUT section declare the following variable

q_xPulse : BOOL; In the VAR section declare the following variables

183

Chapter: PLC Programming The Inspection Conveyor

These are the two timers that will be used to control the output. They are in the STANDARD library.

In the code, window use F2 to place the two timers in the Function Block.

184

Chapter: PLC Programming The Inspection Conveyor

Now change the name of the TON and TOF to match the declaration section. Chapter: PLC Programming The Inspection Conveyor

The TON will start when the i_xEnable input is TRUE and the TOF output is FALSE. The i_xEnable variable can be added by placing the cursor between the := and the ,

185

Then press F2, in the left column of the Input Assistant select Local Variables, then select i_xEnable from the right window.

Next, add the code to monitor the output of fbTOF If you type in the code, notice that once you have added the dot ( . ) after fbTOF a drop list will appear that contains all of the variables declared inside of the TOF.

Red icons indicate VAR_OUTPUT, Yellow icons are for VAR_INPUT, and Purple icons are for VAR.

186

Chapter: PLC Programming The Inspection Conveyor

When the drop down list appears you can either continue typing to filter the list or use the arrow keys to move the cursor up and down. If you use the arrow keys, both the ENTER key and the space bar will select the variable and add it to the code. You code should now look like the following

Next, add the TIME variable to PT:= Note: this is the tTimeOff variable Again, use F2 and select the variable from the Local Variable list.

The input for fbTOF will be the output of fbTON

This time to add the i_tTimeOn variable do not use the F2 key, instead place the cursor after the := and before thecomma ( , )

Now press the dot ( . ) key

This list includes every variable in the project, including libraries. If you know the beginning of the variable name this can be an easy way to access it and still guarantee that typos are not made. After pressing the . press the i key.

187

Chapter: PLC Programming The Inspection Conveyor

Pressing the down arrow will show the next variable in the list, which is the one we want to use.

With i_tTimeOn highlighted, press the Enter key.

Next add the output q_xPulse to the Q output of the fbTOF

If you use the . and select the variable from the list, when selecting an output the . is not removed as it was on the input variable, the . must be removed or the compiler will throw an error.

188

Chapter: PLC Programming The Inspection Conveyor

Also notice that if you hover the mouse over the variable name in the list, that the comment from the declaration section appears as a tool tip.

Note: The following code would provide the exact same result

Now would be a good time to compile the code by selecting Rebuild all from the Project Menu and then save the file. When viewing code online that was written in Structured Text the code window is split, the left side shows the code as it appears offline, the right side show each variable and its value. Using the above as an example i_xEnable, fbTOF.Q, and i_tTimeOff will all be listed on the same line

In order to make the code easier to read it is possible to place each variable on its own line. The common practice is to place the instance name of the Function Block and the open parentheses on the first line, then on each following line place one variable leaving the comma at the end of the line. The easiest way to do this, is place the cursor after each comma and press the Enter key, resulting in the following

Using the TAB key to indent the lines of code that are part of the Function Block helps in reading the code, this allows the person viewing the code to easily see the beginning of each Function Block. The width of the displayed variables in the right window can be adjusted by single clicking on the variable and then grabbing the right edge of the box click and drag to adjust the size.

189

Chapter: PLC Programming The Inspection Conveyor

It is also possible to select Monitoring Options from the Extras menu, then set the Distance of two variables value.

190

Chapter: PLC Programming The Inspection Conveyor

A pulsing output can be used for many different things, flashing stack lights or other indicator lights, or triggering a function block to start repeatedly. We will now add the new Function Block to the Machine Monitoring code and use the pulsing output to trigger the TC_CpuUsage Function Block. In the POU column double-click on P_MachineMonitoring. Place the cursor on line 20 and press F2. From the Input Assistant select User defined Function Blocks from the left column and the FB_Pulse from the window on the right. Then press OK

This will add the generic code for the Function Block to the program.

191

Chapter: PLC Programming The Inspection Conveyor

Replace the name FB_Pulse with a specific instance name of fbPulseCpuUsage.

After clicking away from line 20 the Declare Variable Window will appear. Change the Type to FB_Pulse by either typing it in or using the Ellipse button and selecting it from the list of User defined Function Blocks. Click OK

The declaration section should now contain the following

Add the following values to the inputs of the Function Block.

192

Chapter: PLC Programming The Inspection Conveyor

Before assigning variable name to the inputs and outputs format the code for easier reading.

For the output use the variable that was used on the TC_CpuUsage START input.

Now when the code is running the output will toggle on and off at a rate of 1 second. By writing to xReadCpuUsage the fbTC_CpuUsage START input will toggle and read the CPU Usage every other second.

Creating logging information can be done in several ways. There is a File Read and Write Function Block in the TcSystem library for interacting with a text file, there is also Database and XML supplements for working with those file types. Beckhoff also provides the possibility to write logging information to the Windows Application Log. Using the ADSLOGSTR Function it is possible to write custom string values from the PLC into the Windows Application Log. For this example we will create a log message every time the Machine State changes based on the value of E_MachineState. We will be creating a Function Block to monitor the variable eStep which holds the current value of the State Machine. When the value changes the code needs to create the message to be logged, and then log that message. Chapter: PLC Programming The Inspection Conveyor Start by adding a new Function and name it FB_LogStateMachine

193

Declare the following in the local variable declaration section

i_eState will be the current value of the State Machine control by the MAIN POU q_udiErrID will be the output result of the ADSLOGSTR Function ePreviousState will be updated at the end of the code and hold the value of i_eState from the previous PLC scan fbRT_StateChange is a Rising Trigger, the R_TRIG Function Block monitors its CLK input and when it changes from FALSE to TRUE the Q output will be on for one PLC scan sStateLog will be the STRING representation of the State Machine

194

Chapter: PLC Programming The Inspection Conveyor

Add the below code to the Function Block. Note: The Function on Line 8 (F_StateMachineLookup) does not yet exist. When the Declare Variable window appears press the Cancel button.

The IF statement on line 1 uses the not equal to <> operator to compare the previous state to the current state If they are not equal then the CLK input of the Rising Trigger is set to true (Line 2), else it is set to false (Line 4). Chapter: PLC Programming The Inspection Conveyor Note: Any time a variable is set to TRUE inside an IF statement, code must be added to set that variable to FALSE. When using a Rising Trigger Function Block the input must see the transition from FALSE to TRUE, if lines 3 and 4 were not included the Function Block would only work once. This code could also be done by using the following instead of lines 1 through 5

The IF statement on line 7 monitors the Q output of the Rising Trigger. When the output is TRUE lines 8 through 14 will be executed and when the Q output is false line 16 will be executed. Line 8 passes the value of i_eState into the F_StateMachineLookup Function. Lines 10 calls the ADSLOGSTR Function in the TcSystem library.

195

Calling a Function is different from calling a Function Block. A Function Block requires an instance name and is assigned its own memory space. A Function does not have an instance name and does not have its own space in memory. Functions do not retain any values from one PLC scan to the next. For Example a Timer or Counter must be a Function Block and not a Function. Additionally Functions only return a single result. The most basic Functions are the Math Operators: ADD, SUBTRACT, MULTIPLY, DIVIDE, etc. each of these are a function and return a single result. When calling a function the result of that function must be stored into another variable, for example adding two numbers together would be done in the following manner

The + sign represents the ADD Function Functions that are not common Math Functions are called in a different manner. The following line of code does not compile however for the sake of explanation let us assume that it would.

The variable a is assigned a value of Call the ADD function and pass in the value of the variables b and c Chapter: PLC Programming The Inspection Conveyor The single result of the ADD Function will be stored in the variable a

The ADSLOGSTR Function returns a UDINT (Unsigned Double Integer) ADSLOGSTR has three inputs msgCtrlMask : DWORD; msgFmtStr : T_MaxString; strArg : T_MaxString;

196

msgCtrlMask is used to define the parameters of the logged event

HINT

, WARN

, and ERROR

are the type of Message

LOG will write the message to the Windows Application Log MSGBOX will display a pop up box that shows the message

msgFmtStr is a string that contains the text of the message and ends with %s Note: the text in the sample code and the %s are inside of single quotes Chapter: PLC Programming The Inspection Conveyor

strArg is also a string, the value that is passed into the Function will replace the %s in msgFmtStr

The code sets the Control Mask to Hint and Log

197

The message in the log will be a value of Auto

Machine State Changed to: Auto

if sStateLog has

q_udiErrID will hold the value of the result of the ADSLOGSTR Function, these values are ADS Return Codes, any value other than 0 is an error.

Line 19 copies the value of i_eState into ePreviousState so that on the next PLC scan the two values can be compared and a change can be detected.

198

Chapter: PLC Programming The Inspection Conveyor

Note: The ADSLOGSTR should always be called conditionally using a Rising Trigger Function Block; otherwise it will create a log message every PLC scan.

Now would be a good time to Rebuild the code and save the file. However the call to F_StateMachineLookup is going to throw an error. To prevent this and check the code place comment markers around the code on Line 8

Now, Rebuild all and save the project.

Lets now add the code for F_StateMachineLookup. The Purpose of this Function will be to pass in the current value of the machine state and then convert that to a string value. Right-Click in the POU column and select Add Object

199

Chapter: PLC Programming The Inspection Conveyor

Define the Function as below.

In the declaration section add the Input Variable

The Input Variable eState holds the STRING representation of the Enumeration. This Function will convert this value to an actual STRING that can be passed into the ADSLOGSTR Function. There are several ways to do this, the most common way would be to create nested IF statements as below.

200

Chapter: PLC Programming The Inspection Conveyor

Note: Because Functions only have one output there is no VAR_OUTPUT section. The Name of the Function is the output variable, and its type is defined on line 1 of the declaration section. If you forget to change the type in the New POU window, it can be changed on line 1.

Using nested IF statements in this manner will allow for the code to jump to the END_IF after the correct value of eState has been found and its code has been run. Let us assume that eState has a value of 2, representing Manual. On line 1 eState will be compared to 0, this will return FALSE and the code will then go to line 4. On line 4 eState will be compared to 1, this will return FALSE and the code will then go to line 7. On line 7 eState will be compared to 2, this will return TRUE and the code will continue to line 8. On line 8 the output variable F_StateMachineLookup will be set to a value of Manual. Chapter: PLC Programming The Inspection Conveyor Line 9 is empty Line 10 is another ELSIF, because line 7 return a TRUE the code is now looking for the END_IF statement and will skip all lines until it is found. On line 13 the END_IF statement is found The code will continue to run until the end of the Function and then return to the calling code and write the value of F_StateMachineLookup in the variable sStateLog

The above code will work as needed however there is a more efficient way to do this.

201

The use of a CASE statement will allow for only the minimum amount of code to be run. The traditional use of a case statement would not work correctly inside of a function. Remember that a Function does not hold any data from one PLC scan to the next, and a CASE statement takes one PLC scan to change to the next step.

Even in this very simple example it would be on the 4th PLC scan that iStep would have a value of 3. This code would never work inside of a Function. However if the variable to be evaluated is the variable that is passed into the Function as a VAR_INPUT then the one step that is equal to the value of the variable that was passed in, that one step will run. In the below code eState is passed into the Function eState is then evaluated by the CASE statement to determine which part of the CASE statement to run

202

Chapter: PLC Programming The Inspection Conveyor

When the Function is called and eState has a value of 2 Line 1 will evaluate the value of eState and determine that it is 2 The code will then go to line 7 where it finds 2: and then run the code until it finds the next number that is followed by a : and then jump the END_CASE on line 12. By using a CASE statement in this way, the amount of code to be processed is less than the above example of IF and ELSIF statements, therefore the amount of CPU usage is reduced.

Place the code for the CASE statement into the body of the Function

Now would be a good time to Rebuild all and Save your project.

203

Chapter: PLC Programming The Inspection Conveyor

You might notice that F_StateMachineLookup is grayed out in the POU column. This is because the Function is not being used.

The comment markers need to be removed from the FB_LogStateMachine.

Do another Rebuild all and then Save. After the Rebuild all F_StateMachineLookup should now be in black Chapter: PLC Programming The Inspection Conveyor

204

At this point we have covered the following: 1. 2. 3. 4. 5. 6. 7. 8. Starting a new project Creating Global Variables with addresses Adding Comments to Variable names. Using a CASE statement to create a state machine How to call a Program from another Program Adding an existing library Using Functions and Function Blocks from a library Creating custom Functions and Function Blocks and the using them.

205

Chapter: PLC Programming The Inspection Conveyor

23. Digital I/O


The purpose of this section is to introduce the first mechanical part of the Inspection Conveyor. We will be adding code to the program that allows the conveyor to be loaded and material to enter the system. The first conveyor will be manually loaded by an operator and then index the box along the conveyor. We will start by creating a PROGRAM to control a single conveyor, and then we will convert this PROGRAM to a FUNCTION BLOCK so that we can create multiple instances of it. We will start by adding a call to the P_MachineControl program from MAIN. Left click at the end of line 33 in MAIN. This will place the cursor on that line. Then press the Enter key twice. The cursor is now on line 35

Press the F2 key to open the Input Assistant In the left column select User Defined Programs, in the window on the right, select P_MachineControl. Then press OK.

206

Chapter: PLC Programming The Inspection Conveyor

P_MachineControl will now be called and scanned after P_MachineMonitoring.

Double-click on P_MachineControl in the POUs column.

Right-Click in the POUs column and select Add Object.

207

Chapter: PLC Programming The Inspection Conveyor

From P_MachineControl we will be adding code to call the control program of the conveyor. Eventually there will be several specialized conveyors in our conveyor system. For now let us create the Infeed Conveyor.

Create a Program and Name the POU P_InFeedConveyor.

Double-Click on P_MachineControl and use the F2 key to call the P_InFeedConveyor program from P_MachineControl.

In keeping with Top-Down programming principles we will add some code that is more descriptive than functional. To prevent the Declare Variable window from popping up we will create all of this as comments The first comment will be a general overview of what the code in this POU does.

By placing (* at the beginning and *) at the end, all text in between is ignored by the compiler.

208

Chapter: PLC Programming The Inspection Conveyor

The next thing to do is add comments for what we expect to need the program to do. These are not in any specific order and more might be added later, but this gives us a place to start.

This program will control this conveyor in all modes of operation; Auto, Manual, and Maintenance. There are several ways to do this, we could set up a selection statement and write code for what to do when in each mode or each command (output) could monitor each mode and decide what to do. It is best to only write to an output in one location. If you attempt to control an output from more than one location then the last one to write to the outputs will determine its final state. As a simple example let us consider the following: When in Auto a light should flash at 1Hz, when in Manual the same light should flash at 2Hz. We could try the following: Note: (eMode = E_Manual) in the code will compare the two values and return either a TRUE or FALSE value. Chapter: PLC Programming The Inspection Conveyor

However, both of these Function Blocks are writing to the same output (bLight) every PLC Scan; therefore, the Function Block fbPulseAuto always has control of the output.

209

The following IF statement could be used to properly select which Function Block to call

Only one of the two Function Blocks will be called at a time; therefore, only one of them will be attempting to control the value of bLight. With only two possibilities (Auto or Manual) an IF statement works well; however, a CASE statement is more efficient. The following provides the same functionality as above:

Both of these examples have an inherent issue, however. Because we are writing to the same output from two different Function Blocks when the transition happens the value of the output might not be what we expect. Let us assume the current value of eMode is E_Manual, after a period of time eMode changes to E_Auto. The light has changed from a 1Hz pulse to a 2Hz pulse. However in the code shown there is nothing to reset the fbPulseManual Function Block, the code just stops calling the Function Block. The value of all of the variables have been frozen, either the TON or the TOF was in the process of timing. Internally the TON and TOF Function Blocks do not need to increment each PLC scan, they record the start time and compare that to the current time to calculate the elapsed time. Therefore, it is not possible to Pause a timer. When eMode changes back to E_Manual the elapsed time (ET) will jump. For a light this probably will not cause a problem; however, if the output is something more critical it could be a serious issue.

210

Chapter: PLC Programming The Inspection Conveyor

In order to remove this problem we can use one Function Block to write to the output, but adjust the time value based on eMode:

In the above example the value of tTime will change based on the value of eMode. The time value will be loaded into the TON and TOF inside of fbPulseLight on the same PLC scan. If eMode has a value of E_Auto and the active timer has an ET of greater than 500ms then when eMode changes to E_Manual that timer will instantly be done and the Q output of the timer will be TRUE.

In the below example the Pulse Function Block is called and the Enable input is set to FALSE when the value of eMode Changes

In this scenario both the TON and TOF will be restarted when the value of eMode changes. With the exception of the first example, all of these samples do the same thing. The difference between them is how the output reacts on the PLC scan where the value of eMode changes, it is ultimately up to the programmer to choose the implementation that best fits the specific implementation.

211

Chapter: PLC Programming The Inspection Conveyor

When writing a PLC program the above situation can cause many problems for new programmers. The small changes that can happen in one PLC scan can create unexpected results that are difficult to detect and troubleshoot. If the output was not controlling a Light, but instead being used as an input to a Rising Edge or Falling Edge trigger, the R_Trig and F_Trig Function blocks will see this transition but you may never see it simply by visually looking at the code. This is where a program like Scope View can be used to detect these short pulses.

If we look at a simple conveyor that has an Entry and Exit Photo Eye (PE), and one Motor Starter, when a box is placed on the conveyor, the Entry PE is blocked which causes the Motor Starter to energize and the conveyor moves forward. Once, the box has reached the Exit PE the Motor Starter is de-energized and the conveyor will stop. I would like to explore some options for how to write this control code before moving on to our slightly more complex example with a Middle PE.

The below code uses the EntryPE to start the conveyor and the ExitPE to stop the conveyor, this would achieve the desired result; however, if both Photo Eyes are blocked, what happens? In this case the ExitPE is looked at last and therefore the MotorStarter would be set to FALSE. If the two IF statements were reversed and both PEs were blocked, the conveyor would continue to run.

To fix this problem, and try to optimize the code we could also do the following.

212

Chapter: PLC Programming The Inspection Conveyor

This does a couple of things. The ExitPE will have a value of FALSE when there is not a box blocking the PE. Therefore anytime a box is present at the ExitPE the nested IF statement to look at the EntryPE will not be executed. This makes the code more CPU friendly and also ensures that any time the ExitPE is blocked (TRUE) the conveyor will stop. The last option I want to explain will be the most difficult to understand; however, it will provide the most flexibility, and as PEs or other conditions are added to the system it will be the easiest to manage and change. Although as a programmer it is good to optimize your code, remember that at some point in the future, you or someone else is going to have to read your code. Finding a balance between efficiency and readability is always a difficult task. Normally as efficiency increases, readability decreases and vice versa.

Truth Tables are used to describe a Boolean function that has multiple inputs and one output. Our conveyor has two PEs and one Motor Starter. The Truth Table for our conveyor would look like the following.

213

Chapter: PLC Programming The Inspection Conveyor

Each of the two inputs can only be either TRUE or FALSE. The first line shows them both being FALSE, the second line shows that the EntryPE is FALSE and the ExitPE is TRUE, the third line shows the EntryPE is TRUE and the ExitPE is FALSE, the fourth line shows that both inputs are TRUE. This covers all possible input situations. In the Motor Starter column is the state of the output that we would like, based on the input conditions. Notice that the only situation where the Motor Starter will be TURE is when the Entry PE is true and the ExitPE is FALSE. The numbers on the far left are decimal numbers starting at 0; notice that the numbers under the Input conditions are the binary equivalent to these decimal numbers.

To translate this into code we will start by converting the Boolean inputs and combining them into an integer number. Let us assume that iStep is declared in the PLC as an integer. If we then assign the ExitPE to the first bit of iStep and the EntryPE to the second bit of iStep, iStep will represent the decimal equivalent of the status, of the two PEs.

We can then control the output based on the value of iStep. iStep has four possible values 0,1,2, and 3 When iStep is 0, 1, or 3 the Motor Starter is False. When iStep is 2 the Motor Starter is True. We can now use a CASE statement to control this:

214

Chapter: PLC Programming The Inspection Conveyor

It is also possible to combine the CASES where the code is the same, simply separate the values with a comma.

Although we are writing to the variable in multiple places, because they are inside of a CASE statement only one of them will be written to in a given PLC scan. If the value of iStep was to change, it will be the next PLC scan before the CASE would change.

This also gives us the flexibility to easily add more functionality based on the status of the inputs. If you wanted to start a timer when the ExitPE was blocked and the EntryPE was not, you could simple add that code to CASE 1, which would be much easier than trying to add it to the IF statements in the first examples.

The below could be used, but if all three PEs are on then the PLC is writing to the output in two places, within the same PLC scan.

215

Chapter: PLC Programming The Inspection Conveyor

Adding the MiddlePE to the system will be simple in the CASE statement; however, I would first like to repeat the first two IF statements to show why and how this method becomes more complicated.

In the next example the code has been made more efficient and the PLC is only writing to the output once during the PLC scan, but it is more complicated to follow, and therefore more difficult to debug.

If the CASE statement is used then we will see how flexible it really is. Previously there were two PEs, to add a third PE, simply add a third bit, copy and adjust which inputs are copied to which bits.

216

Chapter: PLC Programming The Inspection Conveyor

Expand the Truth Table to include the new possible combinations

From the Truth Table we now see that the Motor Starter will be energized when iStep is equal to 2, 4, or 6

217

Chapter: PLC Programming The Inspection Conveyor

This can be reduced to:

For an example of how to use a Truth Table and Boolean Algebra for the most efficient coding of this example please refer to Appendix II Truth Tables and Boolean Algebra.

For this program we will use the CASE statement as it is easier to make changes to. I have changed the variables names to match the naming convention.

xConvRunEnable is defined as a local BOOLEAN. This variable will be used to know when the Photo Eyes are in the correct states to start the conveyor. It will not be used to directly start and stop the conveyor. The xConvRunEnable will provide one of the start commands, each Photo Eye will provide a stop command. If we start with the following code we will see that the code gets locked up, because any time the middle PE is blocked the Conveyor cannot move. Therefore we need to monitor the PE and select when it will have an effect on the conveyor.

218

Chapter: PLC Programming The Inspection Conveyor

There are several ways to do this; the simplest is to use a Rising Edge Trigger R_Trig from the Standard libray. The PE will provide the input and the output will be TRUE for one PLC scan. This will allow the program to know that a new boxed has arrived, and the Q output of the R_Trig can be monitored for stopping the conveyor while the PE itself is ignored.

In order to start the conveyor the enable needs to be TRUE and we are also going to pause the conveyor for 5 seconds each time a PE is blocked, this will allow the operator to place a new box at the Entry PE.

The timer needs a condition that will stay TRUE for the duration of the PT (Preset Time). If the IN goes FALSE then the timer will reset and start again with an ET (Elapsed Time) of zero. When a box reaches a PE the conveyor should stop, 5 seconds later the conveyor should start again. Using each PE to stop the conveyor, then a 5 second timer to pause the conveyor, then monitoring the xConvRunEnable will give us everything we need. This sequence of steps is easily handled in a CASE statement.

219

Chapter: PLC Programming The Inspection Conveyor

Add the three R_Trig functions blocks to the code below the CASE statement. The Q outputs of the function blocks were removed, because they will not be used on this line of code. It will be used later to stop the conveyor.

The basic framework of the CASE statement will look like the following.

Each step has a comment that describes what will happen in that step. Each step number also increases by a value of 10, this allows for steps to be added without having to change all of the step numbers. The Init step is there because it is a good habit to start, most CASE statements are going to need to use it; therefore, I always include it. As an example we will be adding a TON (Timer On) in step 20, this timer will be reset in the Init step.

220

Chapter: PLC Programming The Inspection Conveyor

Below is the entire CASE statement.

221

Chapter: PLC Programming The Inspection Conveyor

Step 0 is the Init step; here we set all Function Blocks that are going to be used within the CASE statement to FALSE. The last command of the step is to increase the value of iStepSequence by 10. On the next PLC scan step 10 will be executed. Step 10 monitors the xConvRunEnable from the previous CASE statement. IF the PEs are in their correct state, then iStepSequence will be increased by 10. On the next PLC scan step 20 will be executed. Step 20 calls the timer with a FALSE command; this will reset the ET of the timer to 0. Next the same timer is called with a TRUE command and given a time value of 5 seconds. Then iStepSequence is increased by 1. On the next PLC scan step 21 will be executed. Step 21 calls the timer and monitors the Q output of the timer. After 5 seconds has elapsed the Q output will be TRUE, the timer will be reset with a FALSE command and the value of iStepSequence will be set to 30. The reason for the extra step is to ensure that the timer is reset before being used, because the timer is reset in step 20 we must go to another step to wait for it to finish. If the code stayed in step 20 the timer would be reset every PLC scan and therefore it would never complete. Step 30 sets the Motor output to TRUE and increases iStepSequence by 10. Step 40 monitors the outputs of the three R_Trig Function Blocks, when any one of them is TRUE the motor output is set to FALSE and iStepSequence is set to 0. The process will then repeat. The ELSE step is a good practice, if for some reason a change is made to the code and iStepSequence is given a value that is not defined then the commands in the ELSE step will be executed. Without the ELSE step the code would get stuck. Additionally iErrStepNumber is given a value of iStepSequence to help find what the value of iStepSequence was that sent us to the else statement, this is purely used for debugging purposes.

222

Chapter: PLC Programming The Inspection Conveyor

Also notice how the code is indented using the TAB key. This is done to help make the code more readable. If we look at step numbers, it is easy to move downward and find the next step number. Also the IF and END_IF have nothing in between them, which makes the END_IF easy to locate. Compare the two pictures below to see the difference this makes.

If nothing ever went wrong our conveyor would be mostly complete at this point; however, if it can go wrong it will. It is unlikely that you as a programmer will think of every possible situation that could cause a problem. Over time you will start to learn the most common problems. One of them is the possibility of a glitch in the Photo Eye. When using a very sensitive PE it is possible that the PE will transition from FALSE to TRUE at times other than when a box appears in front of it on the conveyor. Let us assume that a fly is in the building and it crosses in front of the path of the PE, depending on the hardware of the PE it may or may not be detected. If it is detected then the conveyor is going to stop as if a box was present. To prevent this type of problem we can add a De-bounce circuit to the code. The idea of a De-bounce circuit is to detect that a BOOLEAN condition has changed and stayed at its new state, and not bouncing between TURE and FALSE. There are a couple of ways to do this; all of them deal with timing.

223

Chapter: PLC Programming The Inspection Conveyor

We will start with an obscure example because it makes for good sample code.

In the above example when the PE is TRUE iCount will increase by a value of 1 each PLC scan. If the PLC scan is 10ms then after 100ms (iCount >= 10) xInputDebounced will be set to TRUE. We would then have to monitor xInputDebounced in our code and possibly look at other conditions for setting it to FALSE and set iCount back to 0. The above example inherently uses the PLC cycle time as the timer. If this was done on the machine and then for some other reason the PLC task time needed to change, then all of the places in the code where we de-bounced an input would need to change. In my opinion using the PLC scan to control your code is never a good idea. For another version of the above, please refer to Appendix III De-bouncing and Input.

D=R*T Distance = Rate of travel * Time If the box is 10 inches long and we want to limit it so that no more than 25% of the box moves past the PE then our Distance will be 2.5 inches

224

Chapter: PLC Programming The Inspection Conveyor

When de-bouncing an input that involves motion the speed at which the product is moving needs to be considered. Imagine we have a simple conveyor with a PE on the end of the conveyor. The box should stop at the end of the conveyor without stopping erroneously, but also should not allow boxes to fall into the floor. If the conveyor is moving extremely slow then the code could wait for the PE to be True for 1 second before stopping the conveyor. However as the conveyor increases in speed the 1 second wait might cause the box to move to far before stopping the conveyor. This would be another reason not to use the above counter and rely on it to work in all situations. If there is a way to know the velocity of the conveyor then we can calculate the precise time we need to ensure a box is present and still stop the conveyor before it falls off.

The Rate of travel will be the speed of the conveyor. We will assume that out conveyor is moving at 1 foot per second (fps). Our reaction is now Time = Distance / Rate of travel Time = 2.5 inches / 1fps Time = 2.5 seconds Therefore we could implement the following code with a simple timer

Note: The above sample will not compile, Distance / Rate will return a LREAL value which cannot be stored in a variable of type TIME When the input is True for tTime (2.5 seconds) the output will then be True. The output will turn False immediately when input turns False. To make this more flexible and reusable we will place this into a Function Block and allow the values of Distance and Rate to adjusted by a variable. Add a Function Block with a name of FB_DebounceInputFalseToTrue

225

Chapter: PLC Programming The Inspection Conveyor

Declare the follow in the Function Block

Add the following code to the body of the Function Block

The LREAL_TO_TIME conversion will convert the 2.5 into T#2.5ms, multiplying by 1000.0 before converting will result in tTime having a value of T#2.5s Open P_InFeedConveyor and use the Function Block to de-bounce the 3 PEs on the Conveyor.

226

Chapter: PLC Programming The Inspection Conveyor

xExitPE, xMiddlePE, and xEntryPE are declared as local variables of type BOOL. In the Check if clear to advance and the Conveyor Advance sections we are using the real inputs in the code, these must be replaced by our new de-bounced inputs.

227

Chapter: PLC Programming The Inspection Conveyor

In review of where we started

We see that the following sections of code have been completed. De-bounce, Check if clear to Advance, and Conveyor Advance The On/Off delay was built into the CASE Statement for Conveyor Advance, so it can be removed. The next thing to implement is Jam Detection. The jam detector on this conveyor will detect when a box leaves either the Entry or Middle PE and does not reach the next PE. Because there will be two Jam Detectors we will implement this as a Function Block. This basic idea for the code is as follows

If both PEs are False then start a Timer. If the timer completes within the given amount of time then this will indicate that the Box is stuck on the conveyor. A few things to consider: We dont want the Jam Detector to cause an error if there are no boxes on the conveyor.

228

Chapter: PLC Programming The Inspection Conveyor

We need to know how long it is supposed to take for the box to get from one PE to the Next. We can do a calculation similar to the one we used for the de-bounce D=R*T. The last thing to keep in mind is what happens if the conveyor starts and the box gets jammed before clearing the first PE. Therefore, instead of using the NOT PE we will use the command for the Conveyor to start moving. Create a Function Block with the following name FB_JamDetection

Declare the following in the Function Block.

229

Chapter: PLC Programming The Inspection Conveyor

Add the following code to the body of the Function Block.

Lines 1-5 A rising edge of i_xStart will be used to start Jam detection (xJamDectectEnable). Line 7 Calculate the amount of time that can pass before turning on the error (q_xJamDetected). Line 9 Call the timer. Lines 11-16 If the destination is reached, disable the Jam Detection, disable the timer, and set the Jam Detected output to False. Chapter: PLC Programming The Inspection Conveyor

230

Place the following in P_InfeedConveyor

fbJamDetection_MiddlePE and fbJamDetection_ExitPE are defined locally as type FB_JamDetection xJamDetectedMiddlePE and xJamDetectedExitPE are defined locally as type BOOL We are using the destination as the Jam Detection PE. Therefore the Function Blocks are for the Middle and Exit PEs. The variable gatq_xMotorOn will be used to start the monitoring for a Jam. The destination PE will stop the monitoring. A distance of 50 with a Rate of 1 will make the timer run for 50 seconds before turning on the Jam Detected output. Chapter: PLC Programming The Inspection Conveyor

231

Mode Handling In the Program MAIN we created a CASE statement that would select the Mode based on the input selector switches, which were defined in Global_Variables_IO. eStep was defined locally in MAIN. We will need to change this to a global variable. Cut eStep :E_MachineState :=0; from the local declaration in MAIN, and Paste it into Global_Variables. Use the Resources tab to see the Global Variable lists. MAIN should now have no local variables.

Global_Variables should now have eStep.

232

Chapter: PLC Programming The Inspection Conveyor

The current code inside of P_InfeedConveyor is for how we want it to operate when machine is in Auto. We still need code for Manual, and Maintenance. In order to organize the code we will use Actions. One Action will be created for each possible state of E_MachineState. To review E_MachineState has four possible values: E_Undefined, E_Maintenance, E_Manual, and E_Auto. To add an Action, Right-Click on P_InfeedConveyor and select Add Action from the context menu.

233

Chapter: PLC Programming The Inspection Conveyor

Name the Action A_Auto, and set the language to ST. Then click OK.

Notice tha P_InfeedConveyor is now expandable, and the Action is shown when it is expanded.

If you Double-Click on the Action, you will notice that it does not have a local variable declaration section. It only has a code window. Actions will use the same local variable list from the POU in which it is contained. Create actions for the other possible Modes of E_StateMachine, E_Maintenance, E_Manual, and E_Undefined. Chapter: PLC Programming The Inspection Conveyor

Place a semicolon ; in each of the Actions. Preform a Project-> Rebuild All to compile the code. You should get 1 error.

Double-click on the error and look at the code

234

In P_MachineMonitoring we were looking at the status of eStep, which was previously declared in MAIN. Since we have now moved eStep to a Global Variable we need to correct this line of code. Simply remove MAIN. In front of eStep.

Preform another Project -> Rebuild All, and then Save your program. We now need to move parts of the code from P_InfeedConveyor into the A_Auto Action De-bouncing the Input PEs, Jam Detection, and Faults are not mode dependent and will stay in P_InfeedConveyor. Check if clear to advance and Conveyor advance could happen in both Manual and Auto, but the code was written for Auto, and the code for Manual will be different. Copy and Paste the Check if clear to advance and Conveyor advance code from P_InfeedConveyor to A_Auto. Starting at line 40

Ending at Line 97

235

Chapter: PLC Programming The Inspection Conveyor

We must now call the Action A_Auto (and the other Actions) from P_InfeedConveyor. We will create a new CASE statement that selectively calls the Actions based on the value of eStep.

The code in A_Auto is complete for now.

236

Chapter: PLC Programming The Inspection Conveyor

In A_Manual we will add code for Jogging the Conveyor.

Declare gatq_xJogConveyor as a Global Input

For now A_Maintenance and A_Undefined have no use. Leave them with only a semicolon ; in them.

237

Chapter: PLC Programming The Inspection Conveyor

Fault Handling Creating faults for every possible situation is a never ending task. We will create some faults for the most obvious conditions that could happen in our program. Starting with Jam Detection, create a fault for each of the two Function Blocks Create a new Global Variable list called Global_Variables_Faults

Declare the two new Fault Variables Chapter: PLC Programming The Inspection Conveyor

In the Fault section of P_InFeedConveyor place the following code.

This code will turn on the two fault variables when a Jam is detected.

238

Add the following code to reset the faults.

Note: This reset code will only reset the fault variable, if the fault condition still exists, then the fault variable will set back to True. In the CASE statement that handles the conveyor in Auto we created an Error Step Number variable called iErrStepNumber. Add the following code to create a fault when this error happens.

gxConveyorAutoSequenceErr, giConveyorAutoSequenceErrID, and gsConveyorAutoSequenceErrMsg are defined in the Global_Variables_Faults list

When the variable iErrStepNumber has a value other than zero three types of faults will happen. gxConveyorAutoSequenceErr is a BOOL that will be set to TRUE. giConveyorAutoSequenceErrID is an INT that will hold the value of the Error Step. gsConveyorAutoSequenceErrMsg will hold a STRING that gives a description of the error and the Error Step number.

239

Chapter: PLC Programming The Inspection Conveyor

These Errors should be Reset by use of the variable gati_xReset. However, there is currently no code to change iErrSStepNumber back to 0. We could do this somewhere in the CASE statement, but there could potentially be a problem caused by the PLC scan. Instead we will set it back to zero when the Reset button is pressed. Add the following code

As we expand upon our Faults in further chapters we will explore more efficient was to handle Faults, and resetting them.

At this point our conveyor is complete. I would like to remind you of a point I made earlier. The more efficient the code is, the more difficult it is to read. However the easier it is to read the harder it is to program when changes have to be made. Chapter: PLC Programming The Inspection Conveyor The core of the program we just created could be summed up in 1 line of code

However, this program is not flexible. Not IF, but WHEN someone decides that the machine needs to be modified it will be more difficult to do. Comparing the above line of code with the program that we created gives the impression that we wrote a bunch of code for no reason. However as we expand the machine, the power of this modular approach using Functions and Function Blocks will become very obvious.

240

VI.

Trouble shooting
24. Lamp Test
One of the key points of trouble shooting any system is knowing where to dissect the system. If you know where to break the system apart and what to look for then the problem can be more easily isolated. In the below picture is a simple circuit consisting of a power supply, a push button, and a LED. If the LED is not illuminated then the first step is to decide where to start searching for the problem. Test the power supply, if it is good then test the continuity of the wire, if that is good, then test the push button, and so on.

With a PLC the method of trouble shooting does not change. Over the next few pages we will look at how the hardware is wired and how the communication happens when using a PLC to control our simple system.

241

Chapter: Trouble shooting

The Power Rail is powered by an external source. The I/O cards receive their power from the cards to their left, and then pass power to the cards on their right. Be aware that not all cards use and/or pass the power rail.

242

Chapter: Trouble shooting

The push button will be wired from Connection Point 2 on the EL1002 through the push button, and then back to Connection Point 1 on the EL1002. When the contacts are closed power is sent from the positive connection to the input.

The LED will be wired from Connection Point 3 on the EL2002 through the LED, and then back to Connection Point 1 on the EL2002. When the output is turned on, the LED will illuminate.

243

Chapter: Trouble shooting

The EtherCAT Coupler must be powered for communication to occur. Note: This power should be supplied separately from the power rail.

244

Chapter: Trouble shooting

The EtherCAT Coupler is connected to a network port on the Controller by an EtherCAT Cable.

245

Chapter: Trouble shooting

The Controller will communicate with the I/O through the coupler. When the Input is true this will be sent to the controller to be processed by the PLC. The PLC will then send a command to the output to turn on the LED. Note: The Coupler power and power rail power are supplied separately.

246

Chapter: Trouble shooting

In the TwinCAT System Manager the EtherCAT Coupler can be found under the I/O Configuration I/O Devices Device 1 EtherCAT Term 1 EK1100 (These are the default labels, they will probably be different on your machine.) The I/O Terminals can be found under the Coupler

247

Chapter: Trouble shooting

In the TwinCAT System Manager the Hardware is linked to the PLC variables.

248

Chapter: Trouble shooting

In the PLC the variables are declared with addresses so that they may be linked to the hardware

When the code is run, Light1 will have the same value as Switch1

Power passes from the supply through the power rail and to the Push Button, when the button is pressed power is supplied to the input

249

Chapter: Trouble shooting

When the EtherCAT update happens the status of the input will be given to the EtherCAT packet The EtherCAT card in the PC will pass the data directly to the PCs memory where it can be read by the System Manager

250

Chapter: Trouble shooting

The system manager will then pass the data from the I/O Configuration to the PLC Configuration

The PLC will then process the code

251

Chapter: Trouble shooting

The system manager will then pass the data from the PLC Configuration back to the I/O Configuration

252

Chapter: Trouble shooting

The EtherCAT card in the PC will read the data directly from the PCs memory and send out the EtherCAT packet over the network.

When the data reaches the Output card the output will be energized and the LED will illuminate.

253

Chapter: Trouble shooting

Electricity and Data flow downstream From the Push Button to the LED Along the path there are several places where the signal can be tested and/or monitored At the wiring connection of the card, in the I/O or PLC configuration of the System Manager and in the PLC Code itself.

254

Chapter: Trouble shooting

When testing hardware it is possible to Write and to Force data into the system A Write is applied one time and then control is given back to the system A Force in the System Manager is applied before each update of the I/O or PLC task If a Write is applied to a variable that is not linked then nothing in the system will tell that variable to have any other state When Writing or Forcing in the system manager the Flow of data must be taken into consideration If the Force is applied to an Input in the I/O Configuration then everything downstream will react accordingly, just as if the Push Button had been pressed However, if the Output in the PLC Configuration is Forced then only the hardware will be effected. The PLC Code will have no idea that the output has been energized.

When a variable is Forced inside the PLC, the Force is applied and then the PLC Code is allowed to run as it normally would. The Force is then applied again at the end of the PLC Scan. Here b has been Forced to a value of 1 and a is assigned a value of b + 1 or 2

Here b has also been forced to a value of 1 However, the first line of code assigns a value of 2 to b This will result in a being assigned the value of 3

255

Chapter: Trouble shooting

25. Code Sequencing


TwinCAT can control up to 4 PLC Run-Times Each Run-Time can have up to 4 Tasks This allows for up to 16 tasks each with their own update rate. In the Task configuration of the Resources Tab you will find the Default Standard task with its call to the program MAIN Task Standard is configured here with a Priority of 0 and an interval of 10ms

256

Chapter: Trouble shooting

The below tasks are configured with a SlowTask at 50ms and a Priority of 2, task Standard runs at 10ms with a Priority of 1, and the task FastTask has an interval of 1ms and a Priority of 0 The highest Priority 0 should always have the fastest interval time

In this configuration the Standard task calls the program MAIN MAIN will then call its subsequent POUs

257

Chapter: Trouble shooting

In the below example MAIN is calling the other programs The first line of code in MAIN calls the program Manual Manual will run its code from top to bottom and then return to MAIN MAIN will then call Semi_Auto Semi_Auto will run its code from top to bottom and then return to MAIN

Note: To view the Call Tree, right click on a POU and select Show Call Tree

258

Chapter: Trouble shooting

If a Function Block is called from a program the same process applies

When the last line of code in MAIN is reached the PLC will return to the first line and repeat the process Below is an online view of MAIN The dark gray lines are code that is running, line 6 is the last line of code

259

Chapter: Trouble shooting

26. Break Points


WARNING! A Breakpoint will stop the PLC Note: If a breakpoint is set by accident the fastest way to remove it is to Logout of the PLC (F12), but with the PLC running every 10ms you probably wont make it in time. Breakpoints are enabled and disabled in the Project -> Options menu

260

Chapter: Trouble shooting

In the left column select TwinCAT Select Enable breakpoints then click OK

Breakpoints can be used to aid in debugging the PLC code When the line is selected where the Breakpoint is to happen the PLC code will run until that line of code is reached When the breakpoint is reached the PLC will stop running and the status of variables can be seen in their current state This will allow the checking of the code to determine if the code is executing properly Note: Breakpoints can NOT be set in an instance of a function block they must be set in the implementation of the function block and therefore each instance of that function block will stop when the breakpoint is reached. To set a breakpoint, click on the rung or line number where you wish the PLC to stop

261

Chapter: Trouble shooting

Here the breakpoint has been set on line 4. bSwitch is currently TRUE and therefore the PLC is still running

Also note that the breakpoint indicator is set in the bottom right corner of the PLC Control

When bSwitch turns FALSE the breakpoint on line 4 will stop the PLC The code on line 4 is not executed

We can also see in the status bar that the PLC is no longer running

262

Chapter: Trouble shooting

The Online menu provides the programmer with a list of options The Run (F5) command will start the PLC again and it will run until it hits a breakpoint The Toggle Breakpoint(F9) command will remove or add a Breakpoint at the line where the cursor is currently located Step over (F10) will execute the line of code and go to the next line of code. If a call to another POU is on the line of code being executed, the POU will run in its entirety

Step in (F8) will perform the same action as Step over with the added functionality of opening the called POU and stepping through its code line by line

Note: The Step in command will not open a POU inside of a library Single Cycle (Ctrl+F5) will run the PLC to the next breakpoint.

If only one breakpoint is set then the PLC will run from the breakpoint thru the last line of code, upon the next Single Cycle command the PLC will run from the first line of code up to the breakpoint. Note: Once a breakpoint has been reached the Single Cycle command will still stop at the breakpoint even if the code would not normally execute the line of code where the breakpoint exists.

263

Chapter: Trouble shooting

The Breakpoint Dialog command opens the below window From here you can see a list of all breakpoints that exists in the PLC Breakpoints can also be added and removed from here

264

Chapter: Trouble shooting

27. Flow Control


Flow control allows you to see which lines of code are being executed In the sample lines 1 and 4 are running because 1 is greater than 0

265

Chapter: Trouble shooting

Flow Control can be turned on thru the Online menu or with the keyboard shortcut Ctrl+F11

Flow Control may appear at times to not be working, there are 3 possible reasons for this. 1. You must be Logged In to the PLC 2. The program you are monitoring is not being called

3. The task that is responsible for calling the program you are monitoring must be set to the Debug Task

266

Chapter: Trouble shooting

In this example when a is greater than b the program Light_On is called First take note that the code for Light_Off will only show the flow control if the program Light_Off is being called and you can see from MAIN that it is not being called unless a is not greater than b Secondly note that only the selected window will display the flow control

267

Chapter: Trouble shooting

The debug task can be set in the Task configuration when you are logged in to the PLC Right click on the Task name and set it as the Debug task Flow Control is only displayed for the Debug task

Warning!!! Flow control should never be used inside of a function block Only use Flow control in a Program If Flow Control is on inside of a Function Block it will display the values and status of the first instance of that Function Block

268

Chapter: Trouble shooting

In the below picture you see that the second instance of the Function Block indicates that it is running even though it is not being called from MAIN

269

Chapter: Trouble shooting

Notice in this picture that bPulse is blue indicating that it has a value of TRUE However fbPulse2 is not being called from MAIN and bPulse in the local delaration has a value of FALSE NEVER use Flow Control inside of a Function Block

270

Chapter: Trouble shooting

28. Global Search


The Global Search tool allows for the search of anything inside of any part of the project or the entire project A Global Search can be started in 3 different ways Project -> Global Search Ctrl+ Alt + S Tool Bar Icon

271

Chapter: Trouble shooting

Selecting Global Search from the Project Menu will open the following window Ctrl+Alt+S will open the same window From here the sections of the program to be searched can be selected Holding the Ctrl key will allow for selecting multiple sections

Note: Using the Tool Bar icon skips this selection window and will search the entire project.

272

Chapter: Trouble shooting

Once the sections have been selected press the OK button

273

Chapter: Trouble shooting

From this dialog box type in the search phrase If text was selected (highlighted) before starting the Global Search it will appear in the box Set the filter options for Match whole word only and Match Case The Find Next button will search for the first occurrence of the search phrase, and each time the button is pressed it will go to the next occurrence Cancel will close the search box Message Window will search for all occurrences and list them in the message window. Note: If you are Logged In to the PLC, the message window is hidden by default. Selecting Message Window from the Window menu or pressing Shift+Esc on the keyboard will open the Message Window

274

Chapter: Trouble shooting

Searching for the letter a will return everywhere the letter a is used in the sections selected

The first line shows the search phrase The last line shows how many times the search phrase was found

275

Chapter: Trouble shooting

The second line below is stating the following

Double Clicking a line in the Message Window will take you to that line of code in the program When using the search tools on a structure remember that the Global Search will search for anything and the Cross Reference needs an exact variable name The Global Search tool can be used to search for an element within a structure, the instance of the structure or both

276

Chapter: Trouble shooting

29. Cross Reference


The Cross Reference tool allows for searching specific items in the PLC Variable Address POU

The tool can be started 2 ways Project -> Show Cross Reference Ctrl+Alt+C

Note: The code must compile with no errors before a cross reference can be done. Additionally if a Build has not been done since the last change was made the cross reference could return incorrect results

277

Chapter: Trouble shooting

The variable name must me entered exactly as it is used in the PLC code Selecting the text before opening the tool will place the selected text in the Name box. Get References will start the search After selecting an item in the POU column Go To will open the POU to the line of code where the variable is used. Double clicking the POU name will also go to where the variable is used Cancel will close the search window To message window will send all of the search results to the message window. The format will be done the same as a Global Search

278

Chapter: Trouble shooting

The List of References shows the following The POU and line where the variable was found The name of the variable The address of the variable (if it has one) The scope of the variable Global or Local The Variable access (Read or Write)

279

Chapter: Trouble shooting

When searching by address the full address must be entered Only the address entered will be searched, overlapping memory addresses will not be found

280

Chapter: Trouble shooting

The POU search is limited, but when multiple tasks are used this will tell you which task to set as the Debug Task for displaying the Flow Control

281

Chapter: Trouble shooting

When looking for where a POU is in the POU list, click somewhere in the POU list and start typing the name of the POU This will bring up a dialog box that will narrow down the results as you type Select the POU name from the list and then select open This will open the POU and also highlight it in the POU list

282

Chapter: Trouble shooting

30. Scope View


Scope View is a software oscilloscope for monitoring variables in the PLC Scope View is an optional component that can be installed when TwinCAT is installed From the Windows Start menu select Programs, TwinCAT System, TwinCAT Scope View

Right click on Scope and select Add Scope View

283

Chapter: Trouble shooting

Leave the defaults and select OK

Right click on Scope View 1 and select Add Channel

284

Chapter: Trouble shooting

Give the Channel a descriptive name and press OK

On the Acquisition Tab of the Channel press the Change button

285

Chapter: Trouble shooting

In the Edit Acquisition window select the correct Server Port and press the Reload Symbols button

286

Chapter: Trouble shooting

Select MAIN.BSWITCH and press OK

287

Chapter: Trouble shooting

Press the Start button

288

Chapter: Trouble shooting

When the PLC variable changes state the change can be seen in the Scope

289

Chapter: Trouble shooting

VII.

Labs
31. Languages
Assignment: Write a program that will monitor an Analog Value and energize an output if the value is within a specific range. Thoughts: We have 1 output to control. The output will be energized if the value is within range. A range is defined as having an upper value and a lower value. Therefore we have 2 conditions that determine if the output is energized. The first condition is that the value is greater than the low end of the range, and the second condition is that the value is less than the upper end of the range. If both conditions are TRUE then the output will be energized. Condition1 is that the value of the analog input is greater than the lower end of the Range. We will assume the lower end of the range is defined as 0. Therefore Condition will be TRUE is the value is greater than 0. Condition2 is that the value of the analog input is less than the upper end of the Range. We will assume the upper end of the range is defined as 10,000. Therefore Condition will be TRUE is the value is less than 10,000.

290

Chapter: Labs

Here is the Ladder Diagram (LD) Code to solve the problem

291

Chapter: Labs

Here is the Function Block Diagram (FBD) Code

It could also be written this way

292

Chapter: Labs

In Continuous Function Chart (CFC) it will look very similar to the second FBD example. Notice that iPot is only used once, and then connected to both inputs. Also notice the order of operation in the gray box. If this order of operations is incorrect, it will require multiple PLC scans to fully execute the code.

293

Chapter: Labs

For Instruction List (IL) the same ideas still apply, but we now work with 1 simple instruction at a time, and we work with a Holding Register The below code works like this: The LD command will load the value of the following variable into the holding register. The AND command will perform the AND function on the value of the following variable and the value stored in the holding register. It will then store that result in the holding register. The ST command will read the value from the holding register and store it in the following variable.

Load the value of Condition1 AND it with Condition2 Store the result in xLight1 For the comparison we do the following

Load the value of iPot If it is Greater Than 0 then store a TRUE, else store a False Store the result in Condition1

If it is Less Than 10,000 the store a TRUE, else store a FALSE Store the result in Condition2

294

Chapter: Labs

Load the value of iPot

In some of the previous example I started with the output first. This was only done for planning and explanation. It should be noted that you should always set your Conditions before you evaluate them. However, when writing code it is a common practice to work backwards to find a solution. Starting with the Output and then working back towards the input conditions that control the state of that output. We started with the xLight1, and the 2 conditions required to energize it. We then looked at the values of iPot that were needed to set the conditions. Although we wrote that conditions last, they should be analyzed first. Below are the full solutions: Ladder Diagram (LD)

295

Chapter: Labs

Function Block Diagram (FBD)

Or

Continuous Function Chart (CFC)

296

Chapter: Labs

Instruction List (IL)

The last language option is Structured Text (ST) In the previous examples I started with the output first, and wrote the code that would control that output. In ST we will do the same; however, we will apply this literally. In ST the line of code will always start with the variable that we would like to assign a value to.

The above line of code reads as xLight1 is assigned a value of Condition1 and Condition2 The := is an assignment statement. Anytime you would like to assign a value to a variable this symbol will be used. In Structured Text the semi-colon is a separator. It indicates that a given statement is separate from the one that follows. It actually has little to do with being at the end of each line of code other than we humans like to put it there. As long as it appears somewhere before the next statement, it will be fine. The semi-colon is for the compiler, not the human.

297

Chapter: Labs

These two lines of code: xMyOutput:=true ;xMyOtherOutput:=false;

Are equally valid as these two lines of code: xMyOutput:=true; xMyOtherOutput:=false;

In the case of a block statement like IF-THEN, CASE-OF or WHILE-DO, the compiler already knows how to parse it via predefined delimiters such as END_CASE, ELSE, ELSIF, END_WHILE, et cetera. Therefore a semicolon becomes unnecessary in a block statement except to parse the separation of the individual lines inside the block statement.

IF myValue > 9 THEN xMyOutput:=true; xMyOtherOutput:=false; END_IF

298

Chapter: Labs

Now we add the code to control the Conditions.

Parentheses aid in understanding and controlling the order of operation. Condition1 is assigned a value of: (iPot > 0) end of line Greater Than > is a function. Pass in 2 values and it will return either TRUE or FALSE. If iPot is greater than 0 then the function will return a TRUE, and Condition1 will be set to TRUE. If iPot is not greater than 0 then the function will return a FALSE, and Condition1 will be set to FALSE.

If the value of iPot is less than 10,000 then the function will return TRUE, and Condition2 will be set to TRUE, else the function will return FALSE, and Condition2 will be set to FALSE.

When looking at these three lines of code together, notice that each of them ends with a ; this tells us that each of them are their own lines of code. Each line of code has an assignment instruction, and there is either an evaluation or instruction that must happen to determine the value that will be assigned to the output. Similar to the other languages, there are many ways to write the code and obtain the same result.

This line of code simply compresses the above into one line. IF iPot is greater than 0 and iPot is less than 10,000 then xLight1 will be TRUE, else xLight1 will be FALSE. Chapter: Labs

299

The IF instruction will selectively call parts of the code. It is similar to a jump instruction. Between IF and THEN the code must simplify down to either TRUE or FALSE IF iPot is greater than 0 and iPot is less than 10,000 then xLight1 will be TRUE, ELSE xLight1 will be FALSE. The code of the ELSE condition will only be executed if the IF statement returns a FALSE. IF TRUE THEN Run This Code ELSE Run This Code END_IF Every IF instruction requires an END_IF

300

Chapter: Labs

32. Linear scaling using a Ratio


Assignment: Create a function the will scale a value between 0 and 32767 to a value between 0 and 100. Thoughts: Because both scales start at 0 we can simply divide the maximum scale-to value by the maximum scaled-from value. This will give us a ratio that we can multiply by the input and it will give us the scaled value. The formula will be Ratio := MaxOutput / MaxInput; ScaledValue := InputValue * Ratio;

301

Chapter: Labs

33. Linear scaling using an equation


Assignment: Create a function that will scale a value between any two numbers to a value between any two other numbers. Thoughts: This is similar to converting temperature from one scale to another. The numbers can go both positive and negative. For any given value on 1 scale there is exactly 1 possible value on the other scale. 32 degrees F = 0 degrees C and 212 degrees F = 100 C

Think of the Celsius scale as the X-axis and the Fahrenheit scale as the Y-axis. The Formula to convert from Celsius to Fahrenheit is: TempF = 9/5 * TempC + 32 The +32 is the offset of the line, because it does not cross the Y-axis at 0. The 9/5 comes from the step required to get from one position on the line to the next. For each increase of 9 degrees in Fahrenheit, you must increase 5 degrees in Celsius. An increase on the Y-axis is referred to as Rise, an increase on the X-axis is called a Run. So we have a Rise of 9 and a Run of 5. This can be calculated using the two known positions 100,212 and 0,32. The difference in the values will give us the change in Step. 212-32 / 100-0 = 180 / 100 = dividing both numerator and denominator by 20 will reduce the fraction to 9/5 Step = Y2 Y1 / X2 X1 = 212-32/100-0 = 9/5 Chapter: Labs

302

Because the step is actually a ratio it is referred to as the slope of the Line, in the formula we will use the letter m. The formula needed to do our conversion is y=mx+b m = Y2 Y1 / X2 X1 = 212-32/100-0 = 9/5 x = Temp in Celsius b = 32 the Y-Intercept, the location where the line crosses the Y-axis y = 9/5 * TempC + 32 TempF = 9/5 * TempC +32 Using this formula we can now convert from any scale to any other scale y = mx + b m = Y2 - Y1 / X2 - X1 b = How do you calculate b if you dont have a graph? b = y1 ( x1 * m ) If we know two points on the graph 0,32 and 100,212 we can calculate everything else in the PLC

303

Chapter: Labs

304

Chapter: Labs

VIII.

Camming
34. Preface

Creation of Cam Tables with or without TC Cam Design Tool, with the new MC2 PLC Open Standard

This document is mostly compiled with information and screen shots directly from the Beckhoff Information System version 01/2010. The current version can be downloaded from here. If you prefer not to download and install the Beckhoff Information System you can also access it on the web. However please keep in mind that the links in the document only work if you have the Information System installed locally in the default location. The links in the document will open a web page showing the Information System article on the specific topic and not the entire Information System. Additionally the documentation for the specific topics covered and referenced in the article can be downloaded using the following: TwinCAT Cam Design Tool TcMC2 Camming.lib Note: these are .chm files and you must UnBlock them before they can be opened. This document covers a brief introduction to the new TcMC2 library; as defined by PLCopen, and its differences from the previous TcMC library. TcMC2.lib has been included with TwinCAT NC PTP and higher since version 2.10 build 1340. To download the TwinCAT development software please go here. The registration form must have a valid email address and the requested version can be selected at the bottom of the form. After submitting the information a link to download the requested version will be emailed to the email address provided. The document then covers the creation of cam tables from either the PLC or the TwinCAT Cam Design Tool. When using the PLC to create a cam table the TcMC2_Camming.lib is required. This library is provided as a supplement to TwinCAT and must be purchased. This library is required for all camming functionality, even if the TwinCAT Cam Design Tool is used. The TwinCAT Cam Design Tool is provided as a supplement to TwinCAT to assist in the development of cam tables by giving a graphical representation to the cam table and its elements. The TwinCAT Cam Design Tool must be purchased, but can also be evaluated for 30 days by entering DEMO when asked for a product key. The use of Motion Functions as defined by the VDI 2143 Guidelines is covered in the document; however the functions themselves are not covered. The current publication from the VDI is geared toward mechanical cams and is only published in Deustch. The VDI does have plans to publish a new document in English that will focus more on software camming; however no indication of when this might occur has been given.

305

Chapter: Camming

35. Intro to TcMC2.Lib a. Overview


The TcMC2 TwinCAT motion control PLC library includes function blocks for programming machine applications and represents a further development of the TcMC library. TcMC2 is based on the revised PLCopen specification for motion control function blocks V2.0 (www.PLCopen.org).

Compatibility
The TcMC2 motion control library contains enhanced and new functions. The function blocks are better adapted to the requirements of the PLCopen specification and are not compatible with the first version (TCMC). Users maintaining existing projects are advised to continue using the original TcMC library for these projects, although TcMC2 should be used for new projects or revision of existing projects.

Main new features


A key feature of TcMC2 compared with TcMC is the so-called buffer mode. Buffer mode enables Move commands to be queued in order to achieve a continuous positioning without intermediate stops. It enables transition of two travel commands with a defined velocity at a certain position. Move commands can be followed by further Move commands during execution. This makes adaptation of target position or travel speed during the movement much easier.

TwinCAT Version
The TcMC2 library is available from TwinCAT version 2.10 build 1340. On remote programmable controls, both systems, the programming PC and the control PC, must have installed an appropriate version. Windows CE systems must have installed an image from version Windows CE 3.08.

306

Chapter: Camming

General rules for MC function blocks


For all MC function blocks the following rules apply, which ensure defined processing through the PLC program.

Exclusivity of the outputs


The outputs Busy, Done, Error and CommandAborted are mutually exclusive, i.e. only one of these outputs can be TRUE at a function block at any one time. When the Execute input becomes TRUE, one of the outputs must become TRUE. Similarly, only one of the outputs Active, Error, Done and CommandAborted can be TRUE at any one time. An exception of this rule is, MC_Stop. MC_Stop sets Done to TRUE as soon as the axis is in standstill. Busy and Active stay TRUE, since the axis is locked. After Execute is reset to FALSE, the axis is released and Busy as well as Active are reset to FALSE.

Initial state
The outputs Done, InGear, InSync, InVelocity, Error, ErrorID and CommandAborted are reset with a falling edge at input Execute, if the function block is not active (Busy=FALSE). However, a falling edge at Execute has no influence on the command execution. Resetting Execute during command execution ensures that one of the outputs is set at the end of the command for a single PLC cycle. Only then are the outputs reset. If Execute is triggered more than once while a command is executing, the function block will not execute further commands and will not provide any feedback.

Input parameters
The input parameters are read with rising edge at Execute. To change the parameters the command has to be triggered again once it is completed or a second instance of the function block must be triggered with new parameters during command execution. If an input parameter is not transferred to the function block, the last value transferred to this block remains valid. A meaningful default value is used for the first call.

Position and Distance


The Position input denotes a defined value within a coordinate system, while Distance is a relative measure for the distance between two positions. Position and Distance are specified in technical units, e.g. [mm] or [], according to the axis scaling.

Dynamic parameters
The dynamic parameters for Move functions are specified in technical units with second as time base. If an axis is scaled in millimeters, for example, the following units are used: Velocity [mm/s], Acceleration [mm/s2], deceleration [mm/s2], jerk [mm/s3]. Chapter: Camming

307

Error handling
All function blocks have two error outputs for indicating errors during command execution. Error indicates the error; ErrorID contains a supplementary error number. The outputs Done, InVelocity, InGear and InSync indicate successful command execution and are not set if Error becomes TRUE. Errors of different type are signaled at the function block output. The error type is not specified explicitly. It depends on the unique, system-wide error number. Error types Function block errors only related to the function block, not the axis (e.g. incorrect parameterization). Function block errors do not have to be reset explicitly. They are reset automatically when the Execute input is reset. Communication errors (the function block cannot address the axis, for example). Communication errors usually indicate incorrect configuration or parameterization. A reset is not possible. The function block can only be triggered again after the configuration was corrected. Axis errors (logical NC axis) usually occur during the motion (e.g. following error). They cause the axis to switch to error status. An axis error must be reset through MC_Reset. Drive errors (control device) may result in an axis error, i.e. an error in the logical NC axis. In many cases axis errors and drive errors can be reset together through MC_Reset. Depending on the drive controller, a separate reset mechanism may be required (e.g. connection of a reset line to the control device).

Behavior of the Done output


The Done output (or alternatively InVelocity, InGear, InSync, etc.) is set when a command was executed successfully. If several function blocks are used for an axis and the running command is interrupted through a further block, the Done output for the first block is not set.

Behavior of the CommandAborted output


CommandAborted is set if a command is interrupted through another block.

Behavior of the Busy output


The Busy output indicates that the function block is active. The block can only be triggered with a rising edge at Execute, if Busy is FALSE. Busy is immediately set with a rising edge at Execute and is only reset when the command was completed successful or unsuccessfully. As long as Busy is TRUE, the function block must be called cyclically for the command to be executed.

Behavior of the Active output


If the axis movement is controlled by several functions, the Active output of each block indicates that the axis executes the command. The status Busy=TRUE and Active=FALSE means that the command is not or no longer executed.

Enable input and Valid output


Chapter: Camming In contrast to Execute, the Enable input results in an action being executed permanently and repeatedly, as long as Enable is TRUE. MC_ReadStatus cyclically updates the status of an axis, for example, as long as Enable is TRUE. A function block with an Enable input indicates through the Valid output that the output data is good. The data is updated continuously while Valid is TRUE.

308

BufferMode
Some function blocks have a BufferMode input for controlling the command flow with several function blocks. For example, BufferMode can specify that a command interrupts another command (nonqueued mode) or that the following command is only executed after the previous command (queued mode). In queued mode BufferMode can be used to specify the movement transition from one command to the next. This is referred to as Blending, which specifies the velocity at the transition point. In non-queued mode a subsequent command leads to termination of a running command. In this case the previous command sets the CommandAborted output. In queued mode a subsequent command waits until a running command is completed. Only one command is queued while another command is executed. If more than one command is triggered while a command is running, the command started last for queuing is rejected with an error. If the last command is started in non-queued mode (Aborting), it becomes active and interrupts the running and an already queued command. BufferModes Aborting : Default mode without buffering. The command is executed immediately and interrupts any other command that may be running. Buffered : The command is executed after no other command is running on the axis. The previous movement continues until it has stopped. The following command is started from standstill. BlendingLow : The command is executed after no other command is running on the axis. In contrast to Buffered the axis does not stop at the previous target, but passes through this position with the lower velocity of two commands. BlendingHigh : The command is executed after no other command is running on the axis. In contrast to Buffered the axis does not stop at the previous target, but passes through this position with the higher velocity of two commands. BlendingNext : The command is executed after no other command is running on the axis. In contrast to Buffered the axis does not stop at the previous target, but passes through this position with the velocity of the last command. BlendingPrevious: The command is executed after no other command is running on the axis. In contrast to Buffered the axis does not stop at the previous target, but passes through this position with the velocity of the first command.

Options input
Many function blocks have an Options input with a data structure containing additional, infrequently required options. For the basic block function these options are often not required, so that the input can remain open. The user only has to populate the Options data structure in cases where the documentation explicitly refers to certain options. Chapter: Camming

Slave Axes
Motion commands like MC_MoveAbsolute can be passed to slave axes if they are explicitly enabled in the axis parameters. A motion command will then decouple the axis and move it afterwards. In this case just Buffer-Mode Aborting can be used.

309

b. Migration from TcMC to TcMC2


The main differences and modifications between the TcMC motion control library and the extended TcMC2 library are listed here, so that the effort for converting an existing project can be estimated.

Axis data structure


In the past an axis required two data structures for cyclic data exchange with the NC. NcToPlc_Axis1 AT %I* : NCTOPLC_AXLESTRUCT; PlcToNc_Axis1 AT %Q* : PLCTONC_AXLESTRUCT; In most function blocks, including MC_MoveAbsolute, the NCTOPLC_AXLESTRUCT data structure was transferred at the Axis input. Certain function blocks, including MC_Power, expected an additional PLCTONC_AXLESTRUCT structure. In the TcMC2 environment the axis structure was extended so that all required data are included in a single structure, which is transferred to each MC function block. Axis1: AXIS_REF; The structure contains the cyclic input and output data for the NC plus additional status information. An existing project generally accesses the content of the NcToPlc structure. The data are also available in the Axis1 structure and can be used to adapt the application program. Example: TcMC : NcToPlc_Axis1.fPosSoll

TcMC2 : Axis1.NcToPlc.SetPos Please note that the sub elements for the NcToPlc and PlcToNc structures now have English names in view of the international market. For example, the current set position for an axis is no longer referred to as fPosSoll, but as SetPos.

310

Chapter: Camming

Function blocks
The input and output configuration of the function blocks has changed slightly compared with TcMC. The main new feature is support for MC_BufferMode in Move blocks. In addition, the blocks now also support a Busy and Active output. These modifications generally only require little migration effort. The following table contains a list of blocks with more extensive modifications.

TcMC MC_GearInFloat

TcMC2 MC_GearIn

Remark MC_GearIn now accepts the gear ratio as a floating point value The new BufferMode enables each Move block to be used to assign a new target for the axis or change the velocity. The NewPos function blocks are therefore no longer required. MoveAbsoluteOrRestart can be replaced with two instances of a Move block (see BufferMode). The new MC_CamIn function block deals with the function of the extended MC_CamInExt block. The input configuration was adapted accordingly. Setting and resetting of the reference flag (axis is referenced) can be achieved with the MC_Home block. To set an axis position on the fly, MC_SetPosition can be used in relative mode (Mode=TRUE). MC_SetActualPosition can be replaced with MC_SetPosition. The new function block sets both, actual and set position. Motion commands like MC_MoveAbsolute can be passed to slave axes if they are explicitly enabled in the axis parameters (from TwinCAT 2.11). A motion command will then decouple the axis and move it afterwards. In this case just Buffer-Mode Aborting can be used.

MC_NewPos MC_NewPosAndVelo

MC_Move...

MC_MoveAbsoluteOrRestart MC_Move...

MC_CamIn MC_CamInExt

MC_CamIn

MC_SetReferenceFlag

MC_Home

MC_SetPositionOnTheFly

MC_SetPosition

MC_SetActualPosition

MC_SetPosition

MC_GearOutExt

MC_Move...

MC_OrientedStop

MC_MoveModulo MC_MoveModulo can be executed from standstill or in motion. If started in motion, the block will behave like

311

Chapter: Camming

MC_OrientedStop

MC_Stop

MC_Halt, MC_Stop

MC_Halt stops the axis in a normal operation cycle. MC_Stop is only used in a particular condition when the axis must be locked against further motion.

TcNC library
The previous TcMC library required declarations and functions from the TcNC library, so that this was always integrated in a project. The new TcMC2 library no longer has this dependency. All required declarations and functions are now included in TcMC2 library itself, so that the TcNC library is no longer required. Nevertheless, the TcNC library can still be used for compatibility reasons.

312

Chapter: Camming

c. Status information
In existing motion applications axis status information was often determined via a function call (AxisHasJob(), AxisIsMoving() etc.). While these functions can still be used if the TcNC library is integrated, we now recommended a different approach: The complete status information for an axis is included in the above-mentioned axis data structure Axis1:AXIS_REF. However, this data must be updated cyclically by calling the function block MC_ReadStatus or an Axis1.ReadStatus action at the start of the PLC cycle. Current status information is then available at any point in the program during the PLC cycle.

313

Chapter: Camming

36. When to use a Cam Table a. Overview


In many applications it is necessary to synchronize two or more axes. Axes can be coupled together in the TwinCAT NC PTP. A master axis is then actively controlled, and the position of one or more coupled slave axes is synchronously controlled by the NC. The simplest type of coupling is linear coupling with a fixed ratio of transmission (an electronic gearbox). Some applications require a more complex coupling of master and slave, one which cannot be described by a simple mathematical formula. Such a dependency can be described by means of a table that specifies an associated slave position for every master position. The TwinCAT NC PTP offers the possibility of coupling a slave axis to a master axis by means of a table (electronic cam plate). Here the table contains a certain number of prescribed reference points, and the NC interpolates position and speed between them. The TcMC2_Camming library contains function blocks for handling cam plates. Two types of cam plates are supported. One option is a cam plate in the form of a 2-column table containing master and slave positions (standard table). The master column defines interpolation points via the travel path of the master, ascending from a minimum position value to a maximum value. The associated slave position is determined from the second column using the interpolation points of the table. Values between these points are interpolated. Another option is to define a cam plate as a so-called motion function. A motion function is a singlecolumn table of interpolation points. Each interpolation point not only contains a position, but a complete description of the shape of the curve within a section (segment) of the cam plate. In addition to the master and slave position at the start of the segment, the shape of the function; for example, is specified up to the next interpolation point in the form of a mathematical function. Using this procedure, a motion function requires only very few interpolation points. Despite this, each point between the interpolation points are precisely defined through the mathematical function, and there are no uncertainties due to interpolation. Unlike a standard table, the points of a motion function can be manipulated at run time. The system ensures that a manipulation only becomes effective once an alteration has no direct influence on the slave. Position jumps are thus avoided.

314

Chapter: Camming

b. Gearing
With a 1:1 gear Ratio the two axes will move the tooling at a 45 degree angle.

With a 3.6:1 gear ratio the axes will move the tooling in a diagonal line as seen below.

315

Chapter: Camming

c. Linearly Increasing Gear Ratio (Dynamic)


Dynamically changing the gear ratio by a fixed increment each PLC cycle will create a curve. The math for any other curve is long and complicated.

The key behind the cam table is that it is used when the slave position relative to the master position is critical. For example if at 360 degrees both slave and master must be at 360 degrees, but when the master reaches 720 the slave must be at 1080. This can be accomplished by having the gear ratio doubled, but it is Time dependant and if the gear ratio is not changed at exactly the right time for correct length of time the proper position cannot be reached. So gearing works well for linear changes but not arbitrary changes. The cam table allows you to specify any point for the slave to be at any position of the master, the mathematics of the cam table allow you to make the transition from one point to the next as smooth as possible while guaranteeing that the slave will be at the specified point when the master reaches its predefined position. Linear and fixed gear ratios are no problem but determining a position based on adjusting the gear ratio is time dependant and time is not necessarily under the control of the programmer, if the ratio is changed too early or too late the target position will not be reached.

316

Chapter: Camming

d. Cam Table
With a Cam Table, Slave positions can be defined in the forward direction of the Master and TwinCAT will do the math for you. Cam tables can be made cyclical so that they repeat, typically a rotary axis will be the master and after every 360 degrees of the Master the Cam Table will repeat. In the below graph the Master is moving along the X-Axis from left to right. The Slave is moving along the Y-Axis from bottom to top. As the Master position increases from 0 to 100 the Slave axis moves from 0 to 100, and then as the Master continues towards 360 the slave will return to 0 and hold that position until the next revolution of the Master. If only the points are defined on the table then TwinCAT will calculate a straight line from one point to the next. If Motion Functions are used then TwinCAT will use the VDI 2143 Motion Function standard to calculate a curve between the points. Typically Polynomial 5 will be used. If a different curve is desired then the Cam Table can be setup to use a different motion function to calculate the path from one point to another. Additionally the type of points can be selected; these include Rest, Velocity, Return, and Movement.

317

Chapter: Camming

37. Creating a Cam Table with Function Blocks


Prerequisites: TwinCAT NC PTP 2.10 Build 1340 or Higher TcMC2_Camming.lib (From the TwinCAT NC Camming Supplement)

a. Overview
By the use of the TcMC2_Camming library a cam table can be created, implemented, adjusted, and used directly from the PLC. Motion Function Points define the points on the table and the associated Motion Function to be used with that point. The reference to the Cam Table by use of a pointer is created to define the starting memory location and size of the Cam Table. Additionally the table type must be defined. Each Cam Table will have a unique TableID from 1 to 255. This table ID will be used by the programmer to reference the Cam Table when creating and/or selecting it for use. The use of the CamIn procedure will couple the slave axis to the master axis with the given TableID as a reference. In order to provide more flexibility, the individual points; and the properties of those points, on the Cam Table can be adjusted after the coupling has been performed. The mode in which the Cam Table is to be activated is also selectable.

b. Defining the Points on the Cam Table i. Motion Function Point


A motion function point describes a start point of a motion function. The description includes the point itself, a definition of the function type and a relative pointer to the end point of the motion function segment. The data structure MC_MotionFunctionPoint describes an interpolation point of a motion function. A motion function is a one-dimensional list (array) of type MC_MotionFunctionPoint. TYPE MC_MotionFunctionPoint : STRUCT PointIndex : MC_MotionFunctionPoint_ID; FunctionType : MC_MotionFunctionType; PointType : MC_MotionPointType; RelIndexNextPoint : MC_MotionFunctionPoint_ID; MasterPos : LREAL; (* X *) SlavePos : LREAL; (* Y *) SlaveVelo : LREAL; (* Y' *) SlaveAcc : LREAL; (* Y'' *) SlaveJerk : LREAL; (* Y''' *) END_STRUCT END_TYPE

318

Chapter: Camming

PointIndex: Absolute index of this interpolation point within the motion function. The point index of all interpolation points must increase strictly monotonously and must have no gaps and be greater than 0. Notes: The first point in a list must start AT any index > 0. All following points in the list add 1 to the PointIndex. MC_MotionFunctionPoint_ID is of type UDINT. FunctionType: Type definition for motion functions. Type MC_MotionFunctionType of the mathematical function between this and the subsequent interpolation point. Notes: The type Automatic motion function type used in the TwinCAT Cam Design Editor corresponds to MOTIONFUNCTYPE_POLYNOM5_MM. TYPE MC_MotionFunctionType : ( MOTIONFUNCTYPE_NOTDEF, MOTIONFUNCTYPE_POLYNOM1 := 1, MOTIONFUNCTYPE_POLYNOM3 := 3, MOTIONFUNCTYPE_POLYNOM5 := 5, MOTIONFUNCTYPE_POLYNOM5_MM := 15, MOTIONFUNCTYPE_BESCHLTRAPEZ_RT := 22, END_TYPE

(* 1: polynom with order 1 *) (* 3: polynom with order 3 (rest <-> rest) *) (* 5: polynom with order 5 (rest <-> rest) *) (* 15: polynom with order 5 (motion <-> motion) *) (* 22: acceleration trapezoid (rest <-> turn) *));

PointType: Type MC_MotionPointType of this interpolation point. TYPE MC_MotionFunctionPoint: ( MOTIONPOINTTYPE_IGNORE, (* Ignore point *) MOTIONPOINTTYPE_REST := 16#0001, (* Rest point *) MOTIONPOINTTYPE_VELOCITY := 16#0002, (* Velocity point *) MOTIONPOINTTYPE_TURN := 16#0004, (* Turn point *) MOTIONPOINTTYPE_MOTION := 16#0008, (* Motion point *) MOTIONPOINTTYPE_ADD := 16#0F00, (* Adding of segments *) MOTIONPOINTTYPE_ACTIVATION := 16#2000 (* 1: activation point *)); END_TYPE RelIndexNextPoint: Relative reference to the subsequent interpolation point (usually 1).

319

Chapter: Camming

ii. Sample Code:


Below is a really bad graphical representation of the Points on the Cam Table below. Point3 Point4 X--------X / \ / \ / \ / \ ------X--------X Point1 Point2 X-------------X Point5 Point6

(*Point 1*) VM_MotionFunctionPoints[1].PointIndex := 1; VM_MotionFunctionPoints[1].FunctionType := 15; (*MOTIONFUNCTYPE_POLYNOM5_MM*) VM_MotionFunctionPoints[1].PointType := 1; (*MOTIONPOINTTYPE_REST*) VM_MotionFunctionPoints[1].RelIndexNextPoint := 1; (*1 = Increment PointIndex by 1 to get to Next Point, must be 0 for the last point on the table*) VM_MotionFunctionPoints[1].MasterPos := 0; VM_MotionFunctionPoints[1].SlavePos := 0; (*Point 2*) VM_MotionFunctionPoints[2].PointIndex VM_MotionFunctionPoints[2].FunctionType VM_MotionFunctionPoints[2].PointType VM_MotionFunctionPoints[2].RelIndexNextPoint VM_MotionFunctionPoints[2].MasterPos VM_MotionFunctionPoints[2].SlavePos (*Point 3*) VM_MotionFunctionPoints[3].PointIndex VM_MotionFunctionPoints[3].FunctionType VM_MotionFunctionPoints[3].PointType VM_MotionFunctionPoints[3].RelIndexNextPoint VM_MotionFunctionPoints[3].MasterPos VM_MotionFunctionPoints[3].SlavePos (*Point 4*) VM_MotionFunctionPoints[4].PointIndex VM_MotionFunctionPoints[4].FunctionType VM_MotionFunctionPoints[4].PointType VM_MotionFunctionPoints[4].RelIndexNextPoint VM_MotionFunctionPoints[4].MasterPos VM_MotionFunctionPoints[4].SlavePos

:= := := := := :=

2; 15; 1; 1; 30; 0;

:= := := := := :=

3; 15; 1; 1; 45; 150;

320

Chapter: Camming

:= := := := := :=

4; 15; 1; 1; 60; 150;

(*Point 5*) VM_MotionFunctionPoints[5].PointIndex VM_MotionFunctionPoints[5].FunctionType VM_MotionFunctionPoints[5].PointType VM_MotionFunctionPoints[5].RelIndexNextPoint VM_MotionFunctionPoints[5].MasterPos VM_MotionFunctionPoints[5].SlavePos (*Point 6*) VM_MotionFunctionPoints[6].PointIndex VM_MotionFunctionPoints[6].FunctionType VM_MotionFunctionPoints[6].PointType VM_MotionFunctionPoints[6].RelIndexNextPoint VM_MotionFunctionPoints[6].MasterPos VM_MotionFunctionPoints[6].SlavePos

:= := := := := :=

5; 15; 1; 1; 75; 0;

:= := := := := :=

6; 15; 1; 0; 360; 0;

321

Chapter: Camming

38. Defining the Cam Table in the PLC a. Overview


Within the PLC a Cam Table can be defined by providing a starting memory location, size, and table type.

b. MC_CAM_REF
TYPE MC_CAM_REF : STRUCT pArray ArraySize TableType NoOfRows NoOfColumns END_STRUCT END_TYPE

: : : : :

UDINT; UDINT; MC_TableType; UDINT; UDINT;

The data structure MC_CAM_REF describes the data memory of a cam plate in a further PLC variable (array). The first parameter pArray is a pointer to a data structure containing the cam plate data. The data structure depends on the table type TableType. The number of rows is entered in the component NoOfRows, the number of columns in NoOfCols (usually 1 or 2).

i. Example 1: Position table structure description


pArray: Address of a two-dimensional array. The first column contains an ascending list of master positions. The second column contains the associated slave positions. The address can be assigned with the ADR function. Example: Table1 : ARRAY[0..360, 0..1] OF LREAL; pArray := ADR( Table1 ); ArraySize : Storage capacity of the two-dimensional array, which can be determined with the SIZEOF function. Example: ArraySize := SIZEOF( Table1 ); TableType: The table type is MC_TABLETYPE_EQUIDISTANT, if the master positions have the same distance, or MC_TABLETYPE_NONEQUIDISTANT it the distance is variable. NoOfRows: The number or rows corresponds to the number of table points. NoOfColumns: The number of columns is 2. Chapter: Camming

322

ii. Example 2: Structure description of a motion function


pArray: Address of a two-dimensional array. The first column contains an ascending list of master positions. The second column contains the associated slave positions. The address can be assigned with the ADR function. Example: Table1 : ARRAY[0..360, 0..1] OF LREAL; pArray := ADR( Table1 ); ArraySize : Storage capacity of the one-dimensional array, which can be determined with the SIZEOF function. Example: ArraySize := SIZEOF( MotionFunction ); TableType: The table type is MC_TABLETYPE_MOTIONFUNCTION. NoOfRows: The number or rows corresponds to the number of table points. NoOfColumns: The number of columns is 1.

323

Chapter: Camming

c. MC_TableType
TYPE MC_TableType : ((* n*m tabular with equidistant ascending master values *) MC_TABLETYPE_EQUIDISTANT := 10, (* n*m tabular with strictly monotone ascending master values (not imperative equidistant) *) MC_TABLETYPE_NONEQUIDISTANT := 11,

motion function calculated in runtime *) MC_TABLETYPE_MOTIONFUNCTION := 22 ); END_TYPE

(*

i. Sample Code:
(*Cam Table Data*) VM_MotionFunctionPoints : ARRAY [1..6] OF MC_MotionFunctionPoint; (*The size of the Array determines the number of points in the Cam Table*) CamTable_Slave : MC_Cam_Ref; (*MC_Cam_Ref contains the location, size, and type of the Cam Table*) (*Provide MC_Cam_Ref with the data of the CAM Table*) CamTable_Slave.pArray := ADR(VM_MotionFunctionPoints); CamTable_Slave.ArraySize := SIZEOF(VM_MotionFunctionPoints); CamTable_Slave.TableType := MC_TABLETYPE_MOTIONFUNCTION; CamTable_Slave.NoOfRows := 6; CamTable_Slave.NoOfColumns := 1;

324

Chapter: Camming

39. Creating the Cam Table a. Overview


The Cam Table Select block enables the programmer to create a Cam Table by providing the Master and Slave axes along with the ID of the Cam Table to be used, and the reference to the Cam Table.

b. MC_CamTableSelect

With the function block MC_CamTableSelect, a table can be specified and loaded into the NC. The block creates a new table and simultaneously fills it with data provided by the PLC. MC_CamTableSelect does not have to be used, if a table created with the TwinCAT cam plate editor is to be used. In this case, simple coupling with MC_CamIn is sufficient.

Inputs
Execute: The command is executed with a rising edge at input Execute. Periodic: Periodic is TRUE if the cam plate is repeatedly cyclically. MasterAbsolute: Absolute interpretation of master positions. SlaveAbsolute: Absolute interpretation of slave positions. CamTableID: ID of the cam plate used for coupling.

Outputs
Done: becomes TRUE, if the cam plate was created successfully. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done or Error, is set. Error: Becomes TRUE, as soon as an error occurs. ErrorID: If the error output is set, this parameter supplies the error number.

Input/Outputs
Chapter: Camming Master: Axis data structure of the master Slave: Axis data structure of the slave CamTable: The data structure of type MC_CAM_REF describes the data storage for the cam plate in the PLC.

325

i. Sample Code:
(*Axes*) VM Slave (*Triggers*) bCamTableSel1 (*FB Error Info*) bErrorCamCreate iErrorIDCamCreate : : Axis_Ref; Axis_Ref;

BOOL; (*MC_CamTableSelect*)

: :

BOOL; UDINT;

fbMC_CamTableSelect1

MC_CamTableSelect;

(*Create the Cam Table*) fbMC_CamTableSelect1( Execute:= bCamTableSel1, Periodic:= TRUE, MasterAbsolute:=TRUE , SlaveAbsolute:=TRUE , CamTableID:=1 , Master:=VM , Slave:=Slave , CamTable:=CamTable_Slave , Done=> , Busy=> , Error=>bErrorCamCreate , ErrorID=>iErrorIDCamCreate );

326

Chapter: Camming

40. Importing a Cam Table for Verification a. Overview


Without a license for the TwinCAT Cam Design Tool, the Cam Table created by the PLC can be viewed but changes will not be saved. Once the Cam Table has been uploaded changes can be made to tweak the table, and then corresponding changes can be made to the PLC code.

b. Creating a Blank Table


Under the NC-Configuration, right click on Tables and select Append Table

Leave the defaults and select OK.

327

Chapter: Camming

If you do not have a license for the Cam Design Tool you will receive the following message. Select OK.

Right click on Master 1 and select Append Slave

Leave the defaults and select OK.

328

Chapter: Camming

You should now see an empty Cam Table.

329

Chapter: Camming

c. Importing the Cam Table


On the Slave Tab verify that the Table ID matches the Table ID used in the PLC program.

If it does not match then right click on the Slave and select Change ID.

330

Chapter: Camming

Change the ID: and select OK.

After verifying the Table ID, select Upload.

Leave the defaults and select OK.

331

Chapter: Camming

Your Cam Table should now look like the following.

332

Chapter: Camming

41. Camming the two Axes together a. Overview


Once the Cam Table has been defined, verified, and created; the two axes are now ready to be cammed together.

b. MC_CamIn

The function block MC_CamIn activates master-slave coupling with a certain cam plate. In addition it is possible to switch to a new cam plate in coupled state. The switching rules, in particular the time or position, can be specified. The status flag Axis.Status.CamTableQueued can be used to check whether a cam plate is queued for switchover. Inputs VAR_INPUT Execute : BOOL; MasterOffset : LREAL; SlaveOffset : LREAL; MasterScaling : LREAL := 1.0; SlaveScaling : LREAL := 1.0; StartMode : MC_StartMode; CamTableID : MC_CAM_ID; BufferMode : MC_BufferMode; Options : ST_CamInOptions; END_VAR Chapter: Camming Execute: The command is executed with a rising edge at input Execute MasterOffset: Offset to the master position of the cam plate SlaveOffset: Offset to the slave position of the cam plate MasterScaling: Scaling of the master position of the cam plate StartMode: StartMode determines whether the cam plate position is interpreted absolute or relative to the coupling position. StartMode can be relative or absolute for master (X coordinate) and slave (Y coordinate).

333

CamTableID: ID of the cam plate used for coupling BufferMode: currently not implemented

Options: Data structure with further coupling and switching options: ActivationMode: ActivationMode specifies the switching time or position at which cam plate coupling or switchover takes place. ActivationMode can also be specified when a slave is coupled for the first time. ActivationPosition: Optional master position at which a cam plate is switched, depending on the ActivationMode. (not required for first coupling.) If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used, the position refers to the non-scaled cam plate. If the position in the application refers to the scaled cam plate, it can be divided by the MasterScaling before the function block is called. MasterScalingMode: Optional Scaling mode for the master position of the cam plate SlaveScalingMode: Optional Scaling mode for the Slave position of the cam plate InterpolationType: Interpolation type for position tables. Not required for motion functions Outputs VAR_OUTPUT InSync : Busy : Active : CommandAborted : Error : ErrorID : UDINT; END_VAR

BOOL; BOOL; BOOL; BOOL; BOOL;

InSync: Becomes TRUE, if the coupling was successful and the cam plate is active. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, InSync, CommandAborted or Error, is set. Active: Active indicates that the command is executed. For cam plate switching Active becomes TRUE, if the coupling command was executed successfully but the cam plate is still queued. If the cam plate is activated depending on the ActivationMode, Active becomes FALSE and InSync is set. CommandAborted: Becomes TRUE, if the command could not be fully executed. The axis may have become decoupled during the coupling process (simultaneous command execution). Error: Becomes TRUE, as soon as an error occurs. ErrorID: If the error output is set, this parameter supplies the error number. Inputs/outputs VAR_IN_OUT Master Slave END_VAR

: :

AXIS_REF; AXIS_REF;

334

Chapter: Camming

i. Sample Code:
(*Couple the Axes using the Cam Table*) fbMC_CamInSlave( Execute:=bExectueCamInSlave , MasterOffset:= , SlaveOffset:= , MasterScaling:= , SlaveScaling:= , StartMode:=MC_STARTMODE_ABSOLUTE , CamTableID:=1 , BufferMode:= , Options:= , Master:=VM , Slave:= Slave, InSync=> , Busy=> , Active=> , CommandAborted=> , Error=>bErrorCamIn , ErrorID=>iErrorIDCamIn );

335

Chapter: Camming

42. Changing a table point via the PLC a. Overview


While the Cam Table is in operation it may be necessary to adjust the location and/or properties of the points. Although the point before and after the current Slave position cannot be adjusted every other point can be. The way the change is to be implemented can also be defined.

b. MC_WriteMotionFunctionPoint

The function block MC_WriteMotionFunctionPoint can be used to write the data of a motion function interpolation point. Inputs VAR_INPUT Execute CamTableID PointID END_VAR

: BOOL; : MC_CAM_ID; : MC_MotionFunctionPoint_ID;

Execute: The command is executed with rising edge. CamTableID: ID of the loaded table. PointID: Point ID of the first point of the motion function to be read. Outputs VAR_OUTPUT Done Busy Error ErrorID END_VAR

: BOOL; : BOOL; : BOOL; : UDINT;

Inputs/Outputs VAR_IN_OUT Point : MC_MotionFunctionPoint; END_VAR

336

Chapter: Camming

Done: Becomes TRUE, if the data were written successfully. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done or Error, is set. Error: Becomes TRUE, as soon as an error occurs. ErrorID: If the error output is set, this parameter supplies the error number

Point: Data structure containing the data of a motion function interpolation point Motion Function Point: Refer to Creating a Cam Table with Function Blocks

c. MC_SetCamOnlineChangeMode

The function block MC_SetCamOnlineChangeMode specifies the mode for write access to cam plate data. The function block can also be used to specify when the data is read into the cam plate. If activation of the data is to be delayed until the master reaches a certain position, the system will initially queue the written data and activate them at the master position. The status flag Axis.Status.CamDataQueued can be used to check whether data has been queued (i.e. written but not yet activated). Cam plate can be modified at run time via the PLC (see MC_WriteMotionFunction, MC_WriteMotionFunctionPoint). The function block MC_SetCamOnlineChangeMode is used to specify when and how these changes take effect. The set mode affects all subsequent write operations. It is therefore not necessary to call the block before each write access. This function specifies the activation mode for modifications but does not affect a change or changeover of cam plates. Inputs VAR_INPUT Execute ActivationMode ActivationPosition MasterScalingMode SlaveScalingMode CamTableID END_VAR

: BOOL; : MC_CamActivationMode; : LREAL; : MC_CamScalingMode; : MC_CamScalingMode; : MC_CAM_ID;

337

Chapter: Camming

Execute: The command is executed with rising edge. ActivationMode: Defines when and how scaling takes place. (MC_CamActivationMode) ActivationPosition: Optional master position at which scaling is carried out (depending on ActivationMode). If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used, the position refers to the non-scaled cam plate. If the position in the application refers to the scaled cam plate, it can be divided by the MasterScaling before the function block is called.

MasterScalingMode: Type of master scaling. (MC_CamScalingMode) SlaveScalingMode: Type of slave scaling. (MC_CamScalingMode) CamTableID: Table ID.

Outputs VAR_OUTPUT Done Busy Error ErrorID END_VAR

: BOOL; : BOOL; : BOOL; : UDINT;

Done: Becomes TRUE, if the data were written successfully. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done or Error, is set. Error: Becomes TRUE, as soon as an error occurs. ErrorID: If the error output is set, this parameter supplies the error number

338

Chapter: Camming

d. MC_CamActivationMode
TYPE MC_CamActivationMode : ( MC_CAMACTIVATION_INSTANTANEOUS, (* instantaneous change *) MC_CAMACTIVATION_ATMASTERCAMPOS, (* modify the data at a defined master position referring to the cam tables master position *) MC_CAMACTIVATION_ATMASTERAXISPOS, (* modify the data at a defined master position referring to the absolute master axis position *) MC_CAMACTIVATION_NEXTCYCLE, (* modify the data at the beginning of the next cam table cycle *) MC_CAMACTIVATION_NEXTCYCLEONCE, (* Not Yet Implemented! Modify the data at the beginning of the next cam table cycle, activation is valid for one cycle only *) MC_CAMACTIVATION_ASSOONASPOSSIBLE, (* modify the data as soon as the cam table is in a safe state to change its data *) MC_CAMACTIVATION_OFF, (* don't accept any modification *) MC_CAMACTIVATION_DELETEQUEUEDDATA (* delete all data which was written to modify the cam table but is still not activated *) ); END_TYPE MC_CamActivationMode specifies the timing and type of change for a cam plate. Changes can be affected through scaling, modification of the cam plate data, or switching of cam plates. The following modes are possible: MC_SetCamOnlineChangeMode is used to specify when modified cam plate data become active (see also MC_WriteMotionFunction and MC_WriteMotionFunctionPoint). In both cases the following modes are possible: MC_CAMACTIVATION_INSTANTANEOUS: The change takes effect immediately. MC_CAMACTIVATION_ATMASTERCAMPOS: The change takes effect at a certain cam plate position (master position within the cam plate). The command must be issued ahead of this position. The position refers to the non-scaled cam plate. If the position in the application refers to the scaled cam plate, it can be divided by the MasterScaling before the function block is called. MC_CAMACTIVATION_ATMASTERAXISPOS: The change takes effect at a certain absolute position of the master axis. The command must be issued ahead of this position. MC_CAMACTIVATION_NEXTCYCLE: For a cyclic cam plate, the change takes effect at the transition to the next period. MC_CAMACTIVATION_ASSOONASPOSSIBLE: Modified cam plate data take effect as soon as system dynamics allow. MC_CAMACTIVATION_OFF: Changes in cam plate data are ignored. MC_CAMACTIVATION_DELETEQUEUEDDATA : Queued cam plate data are deleted. Data are queued if the change was requested at a certain master position or at the end of the cycle, for example.

339

Chapter: Camming

i. Sample Code:
(*New data for point 5 of the Cam Table*) VM_MotionFunctionPoints[5].PointIndex VM_MotionFunctionPoints[5].FunctionType VM_MotionFunctionPoints[5].PointType VM_MotionFunctionPoints[5].RelIndexNextPoint VM_MotionFunctionPoints[5].MasterPos VM_MotionFunctionPoints[5].SlavePos (*Buffer the Data for Point 5*) fbMC_WriteMotionFunctionPoint5_1st( Execute:=TRUE , CamTableID:=1 , PointID:=5 , Point:=VM_MotionFunctionPoints[5] , Done=> , Busy=> , Error=>bErrorWritePoint_1st , ErrorID=>iErrorIDWritePoint_1st ); (*Use new Data for Point 5*) fbMC_SetCamOnlineChangeModeTable1_1st( Execute:= TRUE , ActivationMode:=MC_CAMACTIVATION_ATMASTERAXISPOS , ActivationPosition:=370 , MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET , SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET , CamTableID:=1 , Done=> , Busy=> , Error=> bErrorChangeMode_1st, ErrorID=>iErrorIDChangeMode_1st ); := := := := := := 5; 15; 1; 1; 75; 75;

340

Chapter: Camming

(*New data for point 5 of the Cam Table*) VM_MotionFunctionPoints[5].PointIndex VM_MotionFunctionPoints[5].FunctionType VM_MotionFunctionPoints[5].PointType VM_MotionFunctionPoints[5].RelIndexNextPoint VM_MotionFunctionPoints[5].MasterPos VM_MotionFunctionPoints[5].SlavePos (*Buffer the Data for Point 5*) fbMC_WriteMotionFunctionPoint5_2nd( Execute:=TRUE , CamTableID:=1 , PointID:=5 , Point:=VM_MotionFunctionPoints[5] , Done=> , Busy=> , Error=>bErrorWritePoint_2nd , ErrorID=>iErrorIDWritePoint_2nd );

:= := := := := :=

5; 15; 1; 1; 75; 0;

(*Use new Data for Point 5*) fbMC_SetCamOnlineChangeModeTable1_2nd( Execute:= TRUE , ActivationMode:=MC_CAMACTIVATION_ATMASTERAXISPOS , ActivationPosition:=730 , MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET , SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET , CamTableID:=1 , Done=> , Busy=> , Error=> bErrorChangeMode_2nd, ErrorID=>iErrorIDChangeMode_2nd );

341

Chapter: Camming

43. Motion Functions vs. Position Tables a. Position Tables


General Table Conventions Tables only contain binary data. Table can be read from an ASCII file but you have to parse the file. A table consists of a header (the first line) and the table data (the remaining lines). The header contains two numbers of type unsigned short. The first column contains the number of lines (without header), while the second column contains the number of columns (for table-slave tables this is always 2). There are no separating characters between the data. Apart from the header, the table only contains data of type double. The first column (with the exception of the header line) contains the master positions, while the second column contains the associated slave positions (both in mm). There are no separating characters between the data. The quantity of data is restricted to 64 KB (TwinCAT Version 2.6). (This might be greater in newer versions) A position table is a 2D array that provides a slave position relative to the master position. The downside of a position table is that the segments between defined points are calculated in a straight line between the points. Therefore the more points on the table the shorter the segments and the better the motion. Most 2D tables contain at least 1000 points and are commonly generated by 3rd party software using a mathematical formula (similar to a motion function) to create a table of 1000+ points.

342

Chapter: Camming

Below are the points generated by using Motion Functions from our above sample code. The values highlighted in yellow are the master. The values highlighted in red are the defined points. If this was a table of points the Slave axis values would increase linearly.

343

Chapter: Camming

b. Motion Functions
A motion function (MF) describes a cam disc via mathematical functions. It sub-divides the curve into appropriate segments (sections), for which different motion laws, i.e. special mathematical functions, can be used (for cam examples see: Cam design tool examples). The motion laws for mechanical cams are defined in VDI guideline 2143 and other documents. The electronic cams in TwinCAT use these functions, among others. The motion functions realize these motion functions directly in the real-time driver of the NC. Unlike classic table couplings that only transfer discrete steps (scatter plots) in the form of larger data quantities to the NC, the complete information is stored in the NC in very compact form. Problems originating from data granularity (position reference points) in the table are thus eliminated. The realization of motion laws in the NC has a further crucial advantage: A motion diagram, i.e. the complete description of the motion of a slave axis, can now simply and clearly be defined and modified from the PLC. Associated PLC function blocks make the application of this functionality very convenient. Users can influence not only the complete motion description, but also individual segments or subsections. In order to ensure that the drive system can actually implement a cam in practice, the system calculates characteristic values (such as maximum and minimum position values, velocity and acceleration etc.), which the user has to analyze. The resulting dynamic limit values ultimately depend on the motion of the master and relate to constant master velocity. The characteristic values are thus calculated with the idealized assumption of constant master velocity. In addition, the mean velocity and the effective acceleration are calculated. These values may be used, for example, for calculating the effective torque or the operating point PA (nm ; Meff) in the torque/speed diagram of the motor. The PLC can access the current characteristic values of the NC via function blocks. In the cam design tool (TwinCAT Cam Design Editor) the decision whether to use classic table couplings (scatter plot) or motion functions can be configured via an associated selection. Subsequently, either the position tables or the motion function points are generated when the configuration is activated. If motion functions are used, these points can subsequently be modified individually by the PLC. It is possible to modify individual values or complete sections of the motion functions online according to associated rules, i.e. while the cam is active. Very flexible cams can thus be realized.

344

Chapter: Camming

c. Definition of a Point

The information contained in the cam design tool table is sufficient for defining the motion in the NC. However, closer inspection of this MF table reveals the presence of redundant data. Because the motion is described in segments (sections), for motion diagrams with simple interrelationships the end point of a section is identical to the starting point of the next segment. The more complex point types offered by the cam design tool, such as slide point, are not yet implemented. In addition, users want to be able to deactivate individual points in a particular motion diagram (MOTIONPOINTTYPE_IGNORE, referred to as IGNORE below) at a later stage. These requirements lead a description that in addition to the starting point of a segment, including the point information (velocity, acceleration, point type), also contains the segment information (function type, symmetry value).

d. Point structure
PointIndex FunctionType PointType RelIndexNextPoint MasterPos SlavePos SlaveVelo SlaveAcc SlaveJerk/Symmetry UINT32 Point index UINT16 Function type UINT16 Point type Relative index of the end point (default: 0, subsequently corresponds INT32 to 1) REAL64 Master position REAL64 Slave position at this reference point REAL64 Slave velocity at this reference point REAL64 Slave acceleration at this reference point Slave jerk at this reference point or symmetry value of the segments REAL64 for rest in rest motion laws

In this structure, a relative index is used to refer to the point index of the end point of this segment. In order to keep the definition simple for motion diagrams with simple interrelationships, the IGNORE points are indeed ignored completely. The relative point index is therefore automatically adjusted internally. The default value of the relative point index may therefore be zero, although for a standard list with simple link the value should be 1. The user therefore does not have to update this information. The possible point types of the cam design tool therefore includes the IGNORE point. Chapter: Camming

345

e. Point types
MOTIONPOINTTYPE_IGNORE MOTIONPOINTTYPE_REST MOTIONPOINTTYPE_VELOCITY MOTIONPOINTTYPE_TURN MOTIONPOINTTYPE_MOTION MOTIONPOINTTYPE_REST MOTIONPOINTTYPE_VELOCITY MOTIONPOINTTYPE_TURN MOTIONPOINTTYPE_MOTION 0x0000 0x0001 0x0002 0x0004 0x0008 Ignore point Restpoint Velocitypoint Turnpoint Motionpoint Ignored point Rest point Velocity point Reversal point Movement point

v=0, a=0 v=?, a=0 v=0, a=? v=?, a=?

At Rest the velocity and acceleration will be 0. A Velocity point will have 0 acceleration and the velocity will be defined by the Cam Table or the user. A Turn point will have a velocity of 0, and the acceleration will be calculated by the Cam Table or the user. A Motion point is the default type in which the velocity and acceleration will be calculated by the Cam Table. Since no points can be added while the MF is active, the IGNORE point type enables associated points to be included. These can be activated online at a later stage by specifying the associated values (point type not equal IGNORE). Warning: The master position has to be either strictly monotonic rising or falling. Otherwise it is rejected with an associated error message.

346

Chapter: Camming

44. Cam Design Tool a. Overview


A cam design editor is used to design the movements for a cam plate. A cam design editor is integrated into TwinCAT, and it can be found in the System Manager under the NC Configuration, under the Tables item. The cam design editor is a flexible tool that provides the user with optimum support and only the minimum of restrictions. Therefore, responsibility for the choice of parameters lies with the user. The user, for instance, should carefully check whether the starting and end points correspond exactly to requirements. On the other hand, the user is offered the best possible assistance for checking velocity, acceleration and jerk through the graphic display facilities. With all these options, however, the user must remember that it is physics that sets the limits to the possible movement.

347

Chapter: Camming

b. Creating a Cam Table


Right click on Tables and select Append Table

Leave the defaults and select OK.

348

Chapter: Camming

Right click on the Master and select Append Slave

Leave the defaults and select OK.

It is possible here to insert additional masters, and to enter corresponding slaves under. If you then click the master in the structure tree, the property pages can be used to set the properties not only of the master, but also of the associated slaves.

349

Chapter: Camming

350

Chapter: Camming

The general procedure for developing a design of a cam is based on VDI (Verein Deutscher Ingenieure) Guideline 2143. The rough design of the movement - the movement plan - defines the starting and end points of the movement section. The editor, however, does not make a distinction between the movement sketch and the movement diagram containing the detailed description of the movement, they will show the same data.

The user's interface to the cam design editor is graphic. Following interactive graphic entry of the points in the graphic window, the co-ordinates of the points are displayed in the table window above it. New points can only be inserted in the graph, and it is only possible to delete existing points via the graph. The properties of the points - the co-ordinate values or their derivatives - can also be interactively manipulated in the table window.

351

Chapter: Camming

Not just the position, but also the velocity, acceleration and jerk can be displayed in the graphic area.

The mode of the display can be changed by a right mouse click in the graphic window, which opens the following menu:

Thus a separate Graphic Window is opened for each derivative.

352

Chapter: Camming

i. Master Tab
The minimum and maximum master positions can be specified. The Normed switch allows you to choose between a normalized display and a physically oriented display in which the velocity, acceleration and jerk of the slave are shown against time. The normalized display refers these displays to the master position. The velocity of the master is needed for the physically oriented display; it is necessary, first of all, to distinguish here between a linear and a rotary axis (angular values quoted in degrees). When the data is transferred to the NC, the choice between a linear and a rotary axis specifies whether the table type is linear or cyclic. For a rotary Master, the first and second derivatives at the end are set equal to the corresponding values at the start of the movement cycle, if the starting and end positions of the slave correspond to the minimum and maximum positions of the master. The increment specifies the increment of the master position used for output of the table into a file. If an equidistant table is to be generated, the total length (the actual maximum minus the minimum) should be divisible by the increment. When the project is saved in the registry, the information required to generate and transfer the tables with this increment is created in the NC. The Rounding Value rounds the master position in the graphic input with the given value. Fixed Table / Motion Function: When exporting the cam table to a .csv file this option will either generate a straight line (Fixed Table) or calculate the points using the Motion Function.

353

Chapter: Camming

ii. Slave Tab


Maximum and minimum values can be specified for position, velocity, acceleration and jerk. These values can be used as initial specifications when the graphic window is first displayed. Adjustment to the current values in the diagram can be performed in the relevant graphic window with the Adjust to Extreme Values command. The Rounding Value rounds the slave position in the graphic input with the given value. Export allows the slave's values to be stored in an ASCII file in the form of master position, slave position, on one line each. The master position increment is specified in the master's property page. Import allows files in the format just described to be read in. The values can then be displayed as cubic splines. The type of the spline still needs to be adjusted in the table, according to the values. The Table Id provides a unique identifying number (1..255) for the table, with the aid of which the table data is stored in the NC. It can be changed to using a right mouse click in the menu with the Change Id... command.

354

Chapter: Camming

c. Graphic Window
The slave's position and derivatives are each shown in separate graphic windows.

The associated toolbar includes both buttons that are only related to the graph as well as the special commands for the cam plate editor.

When the Overview Window is switched on, it is not only possible to see which section the graph window is looking at, but this section can be moved, or it is possible to zoom to a new section. The horizontal and vertical Scrollbars can be used to shift the Graphic Section; the horizontal scrollbar acts on all the graphic windows at the same time. If you're using an IntelliMouse with a ScrollWheel you can zoom with the ScrollWheel.

355

Chapter: Camming

The toolbar and its commands can be displayed or hidden via the menu that is opened by a right mouse click (in the graphic window).

This window also has a Horizontal Scrollbar if the Horizontal Scrollbar option is activated. All the horizontal scrollbars are synchronized. The Cross on Point option causes the starting and end points of a movement section to be indicated by a cross. The Show Online Data displays the table data that is currently in the NC, with the associated table ID as a cubic spline. Currently this can result in a distorted display; because the linear tables are displayed as natural splines (second derivative at the edges equals 0). The data is displayed in the same color, but somewhat darker. The data is automatically transferred by ADS, as soon as Online Mode is switched on. The current data can be read by switching the mode on and off. When the project is saved in the registry (Activate Configuration), the information required to generate and transfer the tables is created in the NC.

356

Chapter: Camming

d. Tables Window
The values for the movement section are displayed in the table window:

The values can be altered via the keyboard, remember that restrictions are applied arising from the choice of function type or other boundary conditions for the points. Since movement sections are normally continuous; except for Slide Points, the end point and its derivatives at the end of the section are equal to the corresponding values at the start of the following movement section. For this reason it is normally always the initial values that should be manipulated. In addition to this, if any inconsistencies are seen in the graph of a completed movement diagram, the agreement of the initial and end points should be checked. If certain values in the table cannot be changed, consideration should be given to the boundary conditions applying to the points. It may be appropriate to change them. The boundary conditions limit the scope of the functions in sections in accordance with their type. The symmetry of the functions can only be changed for the following types: Polynom3, Polynom5, Polynom8, Sinusline, ModSinusline, Bestehorn, and AccTrapezoid. Normally the inflection on the curve (acceleration = 0) at 50 % = 0.5. This value can be changed in the table or in the diagram of the acceleration (Example 6).

357

Chapter: Camming

i. Function Types
In addition to the standard types (synchronous/automatic), which can be changed by command on the graph, the function type can also be modified in the combo box. When the combo box; or a field in the first column, is first clicked, a rectangle is temporarily shown in the position window, with the initial and end points of the section at its corners. As soon as another field in the table window is activated, either the rectangle for this one is shown, or no rectangle is displayed at all.

The types correspond to those of VDI Guideline 2143; additionally, there are the cubic splines, with the boundary conditions of natural, tangential and periodical.

Changing the type of spline at the first point implies that the spline type as a whole is changed, including that of the end point. If Spline Tangential is chosen as the spline type, the boundary conditions (first derivative at the starting and end point) should be modified. At the Motion functions with fit to boundary values the R is for Rest, V for Velocity, T for Turn, and M for Motion. Chapter: Camming

358

ii. Commands
The cam design editor offers the following commands, and these may be called up through the toolbars on the relevant graphic window:

All these commands are only applicable to the associated window.

Adjustment to the Extreme Values The window's coordinates are adjusted to the extreme values of the movement. Measurement of Distance The horizontal and vertical distance to the current point from the point first clicked with the left mouse button is displayed at the top right hand corner of the window (please hold the mouse button down for this). Current Position The absolute horizontal and vertical position of the point currently clicked with the left mouse button is displayed at the top right hand corner of the window (please hold the mouse button down for this). Horizontal Shift Moves the selected point horizontally In the velocity window for synchronous functions: shift along a straight line in the position window. The left-hand edge of the graphic area can be temporarily moved in this way, so that the scale can be more easily read. Vertical Shift Moves the selected point vertically In the velocity window for synchronous functions: adjustment of the position in the position window to the velocity. In the acceleration window for automatic function: adjustment of the acceleration. Shift Moves the selected point. Chapter: Camming

359

The following commands only apply in the graphic window for position: Insert Point Inserts a point at the cursor position. Synchronous Function The chosen section is passed through with a synchronous function. Automatic Function An optimum function is selected automatically for the chosen section including adjustment to the boundary values. Delete Point The selected point is deleted, as is the corresponding section.

The following four items define specific boundary conditions for the points: The point type is correspondingly displayed in front of the point in the table window. This restriction can mean that the end value of a section does not agree with the initial value for the following section. Rest Point The selected point is defined as a rest point (boundary condition: v=0, a=0). Velocity Point The selected point is defined as a velocity point (boundary condition: a=0). Reversal Point The selected point is defined as a reversal point (boundary condition: v=0). Movement Point The selected point is defined as a movement point (no boundary conditions).

Delete Slide Point The slide point is deleted and the sections are joined together as they were previously.

360

Chapter: Camming

Slide Point The starting position of the following section or the end position of the previous section is set at the cursor position, without changing the selected section. The point can then be moved on to the section using horizontal shift.

45. Cam Table Scaling a. Overview


As required by the application the scale of the Cam Table can be adjusted. Master and Slave offsets can also be given to provide more flexibility to the programmer.

b. MC_CamScaling

A cam plate coupling can be scaled with the function block MC_CamScaling. The raw table data of the cam plate are not affected, the scaling refers to an existing master/slave coupling. The following parameters can be modified, scaling factors for master and slave, and offsets for the cam plate within the coordinate system. Optionally, the modification will only take effect from a certain master position, enabling precise scaling during the motion. Caution when scaling during motion! The slave position at the time of scaling should only be affected slightly by the change. The status flag Axis.Status.CamcalingPending can be used to check whether a scaling procedure is queued. Inputs VAR_INPUT Execute : BOOL; ActivationMode : MC_CamActivationMode; ActivationPosition : LREAL; MasterScalingMode : MC_CamScalingMode; SlaveScalingMode : MC_CamScalingMode; MasterOffset : LREAL; SlaveOffset : LREAL; MasterScaling : LREAL := 1.0; SlaveScaling : LREAL := 1.0; END_VAR Execute: The command is executed with a rising edge at input Execute

361

Chapter: Camming

ActivationMode: ActivationMode specifies the scaling time and position.

ActivationPosition: Master position at which a cam plate is scaled, depending on the ActivationMode If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used; the position refers to the nonscaled cam plate. If the position in the application refers to the scaled cam plate, it can be divided by the MasterScaling value before the function block is called. MasterScalingMode: Optional scaling mode for the master position of the cam plate SlaveScalingMode: Optional scaling mode for the slave position of the cam plate MasterOffset: Offset to the master position of the cam plate SlaveOffset: Offset to the slave position of the cam plate MasterScaling: Scaling of the master position of the cam plate SlaveScaling: Scaling of the slave position of the cam plate Outputs VAR_OUTPUT Done : Busy : Error : ErrorID : UDINT; END_VAR

BOOL; BOOL; BOOL;

Done: becomes TRUE, if the cam plate was created successfully. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done or Error, is set. Error: Becomes TRUE, as soon as an error occurs. ErrorID: If the error output is set, this parameter supplies the error number. Inputs/outputs VAR_IN_OUT Master : AXIS_REF; Slave : AXIS_REF; END_VAR

362

Chapter: Camming

c. MC_CamScalingMode
TYPE MC_CamScalingMode : ( MC_CAMSCALING_USERDEFINED, (* user defines scaling parameters - scaling and offset *) MC_CAMSCALING_AUTOOFFSET, (* offset is calculated automatically for best result *) MC_CAMSCALING_OFF (* no modification accepted *) ); END_TYPE Type and scope of the scaling of a cam plate coupling via function block MC_CamScaling. MC_CAMSCALING_USERDEFINED: The scaling and offset are retained unchanged. The user has to calculate the scaling and offset such that a jump in the position is avoided. MC_CAMSCALING_AUTOOFFSET: The scaling takes effect and the system adjusts the offset such that a jump in the position is avoided. Scaling should nevertheless occur during a phase with slave velocity 0, since otherwise a jump in velocity cannot be avoided. MC_CAMSCALING_OFF: The scaling and offset are ignored. This mode is used when only slave scaling (i.e. without master scaling) is to be implemented. Autooffset Autooffset mode ensures automatic adaptation of a cam plate offset. Autooffset can be used independently for the master or slave axis of a cam plate and affects both switchover and scaling of cam plates. The function operates based on the rules described below. Master-Autooffset Master-Autooffset Prevents discontinuity of the master position of the cam plate in the axis coordinate system during switching of cam plates with different master cycle or scaling of cam plates (master scaling). This function is required because the relative position of a cam plate in the axis coordinate system depends on the master cycle. If the master cycle is changed, e.g. through scaling, the position would change. Master-Autooffset determines the master offset of the cam plate such that the master position within the cam plate is maintained. For scaling or switchover to a cam plate with a different master cycle this means that the relative (percentage) position before and after the switchover is identical.

363

Chapter: Camming

i. Example:
A cam plate has master cycle of 360 and is scaled by a factor of 2 to 720. Scaling takes place at the 90 position within the cam plate, i.e. at 25% of the start of a cycle. After the scaling the relative master position in the cam plate at 180 is therefore also 25% of the start of a cycle.

During a switchover at the edges of a cam plate (see MC_CamActivationMode MC_CAMACTIVATION_NEXTCYCLE), Master-Autooffset ensures a seamless sequence of cam plates, both for cyclic and linear cam plates.

364

Chapter: Camming

Master-Autooffset cannot be used for a cam plate with relative coupling or switching, since these functions are mutually exclusive. Further restrictions apply to initial coupling. These are shown in the following table.

Slave-Autooffset Slave-Autooffset calculates a slave offset such that discontinuities in the slave position are avoided during cam plate switching or scaling. The slave offset is adjusted to ensure that the slave position is identical before and after the action. If both Master Autooffset and Slave-Autooffset are used for cam plate switching or scaling, the master offset is calculated first, followed by the slave offset. Slave-Autooffset can be used with any MC_StartMode and will always adjust the cam plate such that the slave position doesn't jump.

365

Chapter: Camming

ii. Sample Code:


IF VM.NcToPlc.ActPos > 540 THEN fbMC_CamScaling( Execute:=TRUE , ActivationMode:=MC_CAMACTIVATION_NEXTCYCLE , ActivationPosition:=721 , MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET , SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET , MasterOffset:=0 , SlaveOffset:=0 , MasterScaling:= 0.5, SlaveScaling:=1 , Slave:=Slave); END_IF

366

Chapter: Camming

46. Cyclic Cam Plates with Lift


Please refer to MC_CamIn Appendix in the Information System or at the end of this document. This document makes use of the Cam Design Tool to create the following cam table where the Slave axis travels 100 for each 360 degree revolution of the Master axis.

Calculations for the Lift are handled internally. Only the configuration needs to be correct to implement this type of Cam Table.

367

Chapter: Camming

The Master Axis must be set for Rotation.

The StartMode of the MC_CamIn FB must be set properly. In this example we are using MC_STARTMODE_MASTERABS_SLAVEREL Where the Master axis is calculated to an Absolute position and the Slave axis is calculated Relative to its current position.

368

Chapter: Camming

a. MC_StartMode
TYPE MC_StartMode : ( MC_STARTMODE_ABSOLUTE := 1, (* cam table is absolute for master and slave *) MC_STARTMODE_RELATIVE, (* cam table is relative for master and slave *) MC_STARTMODE_MASTERABS_SLAVEREL, (* cam table is absolute for master and relative for slave *) MC_STARTMODE_MASTERREL_SLAVEABS (* cam table is relative for master and absolute for slave *) ); END_TYPE StartMode is used for coupling with cam plates through MC_CamIn and defines whether a cam plate is interpreted absolute (based on the origin of the axis coordinate system) or relative to the coupling position. The mode can be specified as absolute or relative separately for both coordinate axes. With StartMode absolute the cam plate coordinate system is congruent with the axis coordinate system and can be moved through an offset, if required (master or slave offset). With StartMode relative the origin of the cam plate coordinate system is at the axis position of the respective axis (master or slave) at the time of coupling or cam plate switching. The cam plate can additionally be moved through an offset. Note: The modes MC_STARTMODE_RELATIVE and MC_STARTMODE_MASTERREL_SLAVEABS cannot be used in conjunction with automatic master offset calculation (MC_CamScalingMode), since this would cause a conflict.

369

Chapter: Camming

As can be seen below, when running the Cam Table cyclically the Slave axis will increase from its current position by 100 for each 360 degrees of travel by the Master Axis.

The Red line is the Modulo position of the Master Axis. The Green line is the Absolute position of the Slave Axis.

370

Chapter: Camming

47. Cam Out and Restarting a. Overview


MC_CamOut is used to decouple the Slave axis from the Master axis. The slave axis must be stopped after it is decoupled. To couple the axis back to the Master via the Cam Table simply call the MC_CamIn FB again. If the Slave axis has not changed positions then the default values will suffice for Camming the Slave axis to the Master axis on the next cycle of the Cam Table. In the below Scope the Green horizontal line shows the Slave axis not moving because it was decoupled from the Master for 3 revolutions, and then coupled again.

371

Chapter: Camming

b. MC_CamOut

The function block MC_CamOut deactivates a master-slave coupling.

Note: If a slave axis is uncoupled during the movement, it is not automatically stopped, but reaches a continuous velocity with which it will continue to travel endlessly. The axis can be
stopped with a Stop command. Inputs VAR_INPUT Execute Options END_VAR

: BOOL; : ST_CamOutOptions; (*Not Yet Implemented*)

Execute: The command is executed with a rising edge at input Execute. Options: Currently not implemented Outputs VAR_OUTPUT Done : Busy : Error : ErrorID : UDINT; END_VAR

BOOL; BOOL; BOOL;

Done: Becomes TRUE, if the axis was successfully uncoupled. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done or Error, is set. Error: Becomes TRUE, as soon as an error occurs. ErrorID: If the error output is set, this parameter supplies the error number. Inputs/Outputs VAR_IN_OUT Slave END_VAR

AXIS_REF; Chapter: Camming

Slave: Slave axis data structure. The axis data structure of type AXIS_REF addresses an axis uniquely within the system. Among other parameters it contains the current axis status, including position, velocity or error status.

372

c. MC_Halt

MC_Halt stops an axis with a defined braking ramp. In contrast to MC_Stop, the axis is not locked against further motion commands. The axis can therefore be restarted through a further command during the braking ramp or after it has come to a halt. Note: Motion commands can be passed to slave axes if they are explicitly enabled in the axis parameters. A motion command will then decouple the axis and move it afterwards. In this case just Buffer-Mode Aborting can be used. Inputs VAR_INPUT Execute : BOOL; Deceleration : LREAL; Jerk : LREAL; BufferMode : MC_BufferMode; Options : ST_MoveOptions; END_VAR Execute: The command is executed with a rising edge at input Execute. Deceleration: Deceleration (0). If the value is 0, the deceleration parameterised with the last Move command is used. MC_Halt and MC_Stop as well cannot be executed with lower dynamical parameters than the currently active motion command. Parameters will be adapted automatically. Jerk: Jerk (0). If the value is 0, the jerk parameterised with the last Move command is used. MC_Halt and MC_Stop as well cannot be executed with lower dynamical parameters than the currently active motion command. Parameters will be adapted automatically. BufferMode: BufferMode is currently not supported by MC_Halt. Halt takes effect immediately with a rising edge at Execute, similar to BufferMode=MC_Aborting Options: Currently not implemented - The data structure option includes additional, rarely required parameters. The input can normally remain open.

373

Chapter: Camming

Outputs VAR_OUTPUT Done Busy Active CommandAborted Error ErrorID END_VAR

: BOOL; : BOOL; : BOOL; : BOOL; : BOOL; : UDINT;

Done: The Done output becomes TRUE, if the axis was stopped and has come to a standstill. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done, CommandAborted or Error, is set. Active: Active indicates that the command is executed If the command was queued, it becomes active once a running command is completed. CommandAborted: Becomes TRUE, if the command could not be fully executed. The running command may have been followed by a Move command. Error: Becomes TRUE if an error occurs. ErrorID: If the error output is set, this parameter supplies the error number. Inputs/outputs VAR_IN_OUT Axis END_VAR

: AXIS_REF;

Axis: Axis data structure The axis data structure of type AXIS_REF addresses an axis uniquely within the system. Among other parameters it contains the current axis status, including position, velocity or error status.

374

Chapter: Camming

48. MC_CamIn Appendix


TwinCAT PLC Library: MC (Version 2)

a. Axis coupling with cam plates


The function block MC_CamIn can be used to establish a cam plate coupling (or table coupling) between a master axis and a slave axis. Note that prior to the coupling the slave axis has to be at a position defined by the cam plate. After the coupling and once the master has been started, the slave position is calculated directly from the cam plate. The slave axis is therefore not slowly synchronized with the cam plate, but it will jump if it is not already at the table position. In practice the question arises; what position the slave should be in prior to the coupling, and how this is calculated. The following figures illustrate the procedure. Notes: For all subsequent calculations only axis set positions are used. The actual positions are not used in the calculations, since they would lead to calculation errors, particularly with cyclic cam plates. Only absolute table couplings are considered. For relative couplings, the coupling position of the master or slave axis is considered in the calculations as an additional offset.

b. Linear cam plates


A linear cam plate is only defined via a limited master position range. Outside this range the slave position is defined by the first or last table position. The slave therefore stops at the table edges as soon as the master leaves the defined range.

The diagram shows that the absolute axis coordinate system (blue) does not have to be identical to the cam plate coordinate system (red). The cam plate coordinate system may be offset by a master offset or a slave offset. Scaling is also possible.

375

Chapter: Camming

The slave position relating to a certain master position can be determined via the function block MC_ReadCamTableSlaveDynamics . The block refers to the raw table data, which means that offsets and scaling factors have to be considered via the PLC program itself. Initially, the master offset is added to the current master position. If the cam plate is to be scaled, it is divided by this scaling factor. MasterCamTablePosition := (MasterPosition + MasterOffset) / MasterScaling; The master table position is used as an input parameter for the function block MC_ReadCamTableSlaveDynamics. The result is converted to an absolute slave position with slave offset and scaling, if necessary. SlaveCamTablePosition := ReadSlaveDynamics.SlavePosition; SlavePosition := (SlaveCamTablePosition * SlaveScaling) + SlaveOffset; The slave is moved to this position prior to the coupling. Alternatively, the master may be moved to a position that corresponds to the current slave position. However, generally this position cannot be determined from the cam plate, since the cam plate may be ambiguous. Note: Since the master offset is added in the first formula, a positive offset leads to the cam plate coordinate system being shifted to the left in negative direction. Accordingly, the master offset in the diagram is negative. A positive slave offset leads to the cam plate coordinate system being shifted upwards in positive direction.

376

Chapter: Camming

c. Cyclic cam plates without lift


A cyclic cam plate without lift is characterized by the fact that the slave start and end positions in the table are identical. The slave therefore moves cyclically within a defined range, without changing its position permanently in a particular direction.

For these cam plate types, master/slave coupling requires the same preparation as for a linear cam plate. The starting position of the slave can therefore be calculated as described above. It is not necessary to use the modulo position of the master for the calculation, since the absolute position is already correctly taken into account via the coupling command.

377

Chapter: Camming

d. Cyclic cam plates with lift


The lift of a cyclic cam plate is the difference between the last and the first table position of the slave.

Such a cam plate is continued cyclically at the end of the table. The slave position does not jump back to the initial table value. Instead, the motion continues steadily. With each new cycle, the lift is therefore added as an additional internal slave offset or subtracted if the motion is reversed.

378

Chapter: Camming

e. Uncoupling and re-coupling for cyclic cam plates with lift


If a slave is coupled to a cam plate with lift, the coupling is always done in the basic cycle (red coordinate system), i.e. without added lifting distances. If the slave is uncoupled after a few cycles and then recoupled, the slave position returns to the basic cycle. If necessary, this behavior has to be taken into account and compensated by re-calculating the slave offset.

MasterCamTablePos := (MasterPosition + MasterOffset) / MasterScaling; The master table position is used as input parameter for the function block MC_ReadCamTableSlaveDynamics. The result is converted to an absolute slave position with slave offset and scaling, if necessary. In addition, the number of pending lifts must be calculated and added to the slave position. SlaveCamTablePosition := ReadSlaveDynamics.SlavePosition; Lift number := MODTURNS( (SlavePosition - SlaveOffset), SlaveHub ); NewSlaveOffset := SlaveOffset + (SlaveHub * lift number); SlavePosition := (SlaveCamTablePosition * SlaveScaling) + NewSlaveOffset; The Autooffset function can simplify the calculation of offsets, particularly for switching of cam plates.

379

Chapter: Camming

49. Diagnostics a. Overview


The following covers the error codes as provided by either the function blocks or the TwinCAT System Manager. The error codes provided by the system; although complete, are sometimes not easily understood by new users. The explanations of the error codes provided are based solely on the experience of myself and others. The added descriptions are only relevant for helping to find a problem within TwinCAT, this document will not suffice if your problem is within your .NET or other 3rd party application.

b. Error Format
The error codes within TwinCAT are given in accordance with the following structure. All errors are generated in hexadecimal. The errors range from 0x0000 to 0xFFFF. The most significant byte 0xn000 can be considered as the grouping for the errors. When needed a sub subgroup will be identified by the second byte 0x0n00. The remaining bytes are used to give the exact error code. The errors between 0x0000 and 0x0FFF refer to the TwinCAT System itself. These errors indicate that something is fundamentally wrong with your system. The cause of the errors can vary greatly; it can be anything from a corrupted file to forgetting to start the PLC, or an incorrect linking in the system manager. Remember that just because TwinCAT allows you to do something, that doesnt mean that thats what you wanted to do.

380

Chapter: Camming

Error Groups Offset 0x0000 0x0500 0x0600 0x0700 0x0800 0x1000 0x1900 0x2000 0x3000 0x4000 0x6000 0x7000 0x7800 Description ERR_GLOBAL ERR_ROUTERERRS ERR_TASKERRS ERR_ADSERRS ERR_SYSSMPLERRS ERR_RTIMEERRS ERR_TRACEERRS ERR_IOERRS ERR_SPSERRS ERR_NCERRS ERR_PLCERRS ERR_STRKERRS ERR_PRJSPECIFIC

Global Error Codes 0x0000 0x6 0x7 target port not found target machine not found

These errors commonly occur when setting up a system for the first time, and the frequency increases when switching between development, simulation, and machine. This error is trying to tell you that there is a communication problem, and is commonly an ADS communication problem. If all communication is local, then make sure TwinCAT is running the correct System Manager file, and that the correct PLC program is loading and running. If you are unsure of what system manager file is running, the red folder in the system manager will Open from Target. If communication is remote then check the AMS router on both PCs to make sure the info is valid. Ping the IP of address of one PC from the other to make sure cabling and network configuration is correct. General ADS Error Codes 0x0700 The common errors in this group are fairly self-explanatory. These normally occur because of something not being configured correctly. It could be an incorrect or missing link in the system manager or the PLC code that is calling the ADS service has an invalid parameter.

381

Chapter: Camming

NC Errors 0x4000 The NC error group is comprised of 9 sub-groups. These sub groups cover all things motion, from Overtemp errors to syntax errors in G-Code to bad PLC commands. NC Error Sub Groups 0x40nn 0x41nn 0x42nn 0x43nn 0x44nn 0x45nn 0x46nn 0x4Ann 0x4Bnn General NC Errors Channel Errors Group Errors Axis Errors Encoder Errors Controller Errors Drive Errors Table Errors NC-PLC Errors

General NC Errors 0x40nn 0x4016 used, "Table identifier not allowed" Either an unacceptable value (not 1...255) has been or a table that does not exist in the system has been named. Check your value of your TableID

0x4052 for

"Axis not ready for operation" The axis is not complete, and is therefore not ready operation. This is usually a consequence of problems at system start-up. If the Ready Status of the Axis is not TRUE and the axis receives a command then this error will be given. This value is held in the NCDRIVESTRUCT_IN2 of the Axis 1_Drive and is linked to the Drive Status Word of the drive under the I/O Configuration.

from

For an AX5000 the first place to check is on the Configuration Tab of the axis. Look at the ErrorID, it must be at D013: Axis Op. A value less than 13 or an F value will prevent the axis being ready. The R button on the right side of the ErrorID display will issue an IDN99 reset command to the drive.

382

Chapter: Camming

Channel Errors 0x41nn These errors are for NC-I and are not within the scope of this document. Group Errors 0x42nn These errors are for NC-I also. However there is one here that should be covered. 0x4208 "Single step mode not allowed" The flag for the activation or deactivation of single step mode is not allowed. Value 0: Passive (buffered operation) Value 1: Active (single-block operation). Prior to MC2 if an axis was given a command while the Status bit Has Job was TRUE this error would be given. This error does not stop the axis; it just appears in the Log window of the System Manager. With the new Buffered Moves in MC2 this shouldnt be an issue any more. However keep in mind that if you issue a second move before the first one is complete, where it previously would ignore the command, it will now Abort the previous command and Execute the new one. Axis Errors 0x43nn These Errors relate to the parameterization and monitoring of an axis. The majority of these errors are for incorrect (out of range) parameters or monitoring the control of the axes. Encoder Errors 0x44nn These Errors relate to the parameterization and monitoring of an encoder. The majority of these errors are for incorrect (out of range) parameters or monitoring the encoder of the axes.

Controller Errors 0x45nn These Errors relate to the parameterization and monitoring of the axis controller. The majority of these errors are for incorrect (out of range) parameters or monitoring the control of the axis position. Drive Errors 0x46nn These Errors relate to the parameterization and monitoring of the drive and motor. The majority of these errors are for incorrect (out of range) parameters or monitoring the state of the drive and motor.

383

Chapter: Camming

Table Errors 0x4Ann These Errors relate to the parameterization and initialization of a cam table. The majority of these errors are for incorrect (out of range) parameters or invalid cam table data. The Flying Saw function blocks will generate these errors as well as Cam Table function blocks. 0x4A06 "Table is not monotonic" The value for the step size is not allowed, because, for example, it is less than or equal to zero. When generating a Cam Table from the PLC or from the Flying Saw this error can happen. The most common cause from the Flying Saw is the Master SetPos is within 1E-12 of the Master Sync position when the Execute turns TRUE. This can also happen for a Cam Table generated by the PLC when the position would require the Master Axis to move backwards.

PLC Errors 0x4Bnn The majority of these errors are well described within the Information System. NC-PLC Errors TwinCAT NC I TcMcCam TcNc TcRemoteSync TcMC2 0x4B00..0x4B0F 0x4B10..0x4B2F 0x4B30..0x4B3F 0x4B40..0x4B4F 0x4B50..0x4B5F 0x4B60..0x4B6F

TcPlcInterpolation 0x4B70..0x4B7F

384

Chapter: Camming

IX.

Remote Connections
50. Embedded Controllers
The TwinCAT AMS Router allows for TwinCAT to communicate between computers

Configuring your local IP address Establishing a Route to the Target Opening the active system manager of the Target

385

Chapter: Remote Connections

Click Start Expand Connect To Click Show all connections

The network card you are going to use should be the only one with a Status of Connected. If the other cards are connected TwinCAT may try to one of scan these networks for devices and not scan the correct network.

Right-Click on the Network Card and select Properties

386

Chapter: Remote Connections

Scroll to the bottom of the list. Select Internet Protocol (TCP/IP) Click on Properties

387

Chapter: Remote Connections

Select Use the following IP address Enter the following IP address. 192.168.0.2 Enter your Subnet mask Click OK

388

Chapter: Remote Connections

Click OK

389

Chapter: Remote Connections

If the below window appears click on STOP Installation. If you click on Continue Anyway windows will install the Real-Time Ethernet driver for your network card. You can do this if you like, but it is not needed for connecting to remote devices.

Click on the TwinCAT icon in the Windows System Tray, and select System Manager.

390

Chapter: Remote Connections

Open a new System Manger file. Select File, then New

Set/Reset TwinCAT to Config mode.

Click Ok

391

Chapter: Remote Connections

Select SYSTEM Configuration, then Choose Target

Click Search (Ethernet)

392

Chapter: Remote Connections

If you know the IP address of the remote device it can be entered. Click Enter Host Name / IP: It is also possible to use the Broadcast Search button to look for computers on the local network that are running TwinCAT, however a broadcast search will not go through a network router.

If the computer you are connecting to is using DHCP then the Address info should be set to Host Name, if a static IP address is being used then set Address Info to IP Address Select the computer form the list and select Add Route Chapter: Remote Connections

393

Enter User name and password of an Administrator account on the Target PC Not required for Windows CE Click OK

Verify the X appears in the Connected column. Click on Close.

394

Chapter: Remote Connections

Select BasePLC Click OK

395

Chapter: Remote Connections

Verify connection to BasePLC the red background indicates you are connected to a remote device. Verify the device status. A green background indicates that TwinCAT is running on the remote device. A blue background indicates the remote device is in config mode. A yellow background indicates a Timeout. Click on the red folder to Open from Target

If the below window appears click on Yes

396

Chapter: Remote Connections

File name of the System Manager *.tsm file Name of remote device List of hardware connected to the device

397

Chapter: Remote Connections

X.

Appendix I Variable Naming Convention


51. Scope
The following programming guidelines support the creation and maintenance of consistent programs with the following goals:

Improve readability Speed development Facilitate the incorporation of third-party software components

These guidelines are based on a history of experience in software development by Beckhoff and our customers. The programming guidelines must be used for the development of new programs, unless the customer has specified other guidelines for the project. The programmer can judge the extent to which the guidelines can be applied to existing programs.

398

Chapter: Appendix I Variable Naming Convention

52. Programming System Settings


The TwinCat project options must be defined uniformly to achieve identical notation for individual editors and for documentation. This is especially true in multi-user projects.

a. Font
A non-proportional font is recommended with the following settings: This can be adjusted under "Project -> Options -> Editor -> Font".

Font: Tahoma Font style: Regular Size: 12 Character set: Western

b. Tab Width
A tab width of 4 is recommended. This can be adjusted under "Project -> Options -> Editor".

399

Chapter: Appendix I Variable Naming Convention

53. Naming a. General


This naming convention applies to variables, constants, and program organization units (POU). Choose a relevant, short, description for each designator name and the designator should be self-explanatory. The first letter of each word in the designator is capitalized (example: FileSize). Please limit the name to 20 characters, the fewer the better.

Prefixes are included with the designator name to indicate scope, property, and type as will be explained below.

b. Case Sensitivity
Pay close attention to case sensitivity, especially for prefixes, to improve readability.

NOTE: The TwinCat IEC compiler is not case sensitive.

c. Valid Characters
Names should contain the following letters, numbers, and special characters only: Chapter: Appendix I Variable Naming Convention

0...9, A...Z, a...z Underscore Designators always begin with a letter.

The underscore is used to display prefixes more clearly. The syntax is explained in the respective prefix section. Because data type designators are usually formed from capital letters, the individual words are put together with an underscore as a separator to increase readability. The underscore should not be used otherwise.

400

d. Prefix Types
Prefixes are used to quickly identify a designators function. The prefix types are as follows:

Type designator type such as Boolean or integer Scope designator scope as either local or global Property designator property such as retained or VAR_IN_OUT POU POU type such as function or function block

The general syntax for variables and constants is as follows:

[Scope][Property] _ [Type][Name]

g_diFirstUserFault xEnable c_iNumberOfAxes gc_sMyGlobalStringConstant

The general syntax for POUs is as follows:

[POU] _ [Name] Chapter: Appendix I Variable Naming Convention

FB_AxisController FB_HeatGun P_Main F_GetLeftString

401

e. Scope Prefix
Scope prefix indicates the scope of variables and constants. You can see if it is a local or a global variable or a constant from the scope prefix.

Global variables are indicated by a lower case "g". A lower case "c" is added to global constants.

VAR_GLOBAL CONSTANT gc_diMaxFaults gc_diMaxEvents END_VAR : DINT := 100; : DINT := 100; (* Maximum Quantity of Active Faults *) (* Maximum Quantity of Events *)

VAR_GLOBAL g_stMasterFaultList g_stMasterEventList g_xReset END_VAR : ST_FAULTLIST; : ST_EVENTLIST; : BOOL;

Scope Prefix No prefix g_ gc_

Type VAR VAR_GLOBAL VAR_GLOBAL CONSTANT

Use Local variable Global variable Global constant

Example xEnable g_xRunning gc_iCurrentRecipe

Table 3.5 Scope Prefix

402

Chapter: Appendix I Variable Naming Convention

f. Type Prefix
Type prefixes identify the data type of variables and constants. The IEC 61131-3 standard data type prefixes are listed in the following table.

Type Prefix x b w dw si i di usi ui udi r lr date tod dt t s p a e

Type BOOL BYTE WORD DWORD SINT INT DINT USINT UINT UDINT REAL LREAL DATE TOD DT TIME STRING POINTER ARRAY ENUM

Use (Bytes) Boolean (1) Byte (8) Word (16) Double Word (32) Short Integer (8) Integer (16) Double Integer (32) Unsigned Short Integer (8) Unsigned Integer (8) Unsigned Double Integer (32) Floating Point Value (32) Long Floating Point Value (64) Date (32) Time of Day (32) Time and Date (32) Time Duration (32) Character String (x Chars + 1) Pointer Array List Type

Example xName bName wName dwName siName iName diName usiName uiName udiName rName Chapter: Appendix I Variable Naming Convention lrName dateName todName dtName tName sName pxName adiName eMotorType

403

Type Prefix st fb

Type STRUCT FUNCTION BLOCK

Use (Bytes) Structure Function Block

Example stRecipe fbTrigger

Table 3.6 Standard Date Type Prefixes

The type prefix can also be composites, for example, for pointers and arrays. The pointer or array is listed first, followed by the prefix of the pointer type or array type as the following examples show:
piCounter aiCounter paiRefCount astList : POINTER TO INT; : ARRAY [0..10] OF INT; : POINTER TO ARRAY [1..10] OF INT; : ARRAY[0..gc_diMaxFaults] OF ST_FAULT;

404

Chapter: Appendix I Variable Naming Convention

g. Property Prefix
Property prefixes are used for identifying the properties of variables and constants as shown in the following table:

Property Prefix c_ r_

Type VAR CONSTANT VAR RETAIN

Use Local constant Remnant variable type retain Remnant variable type persistent Input variable of POU Output variable of POU In/out variable of POU

Example c_xName r_xName

p_ i_ q_ iq_

VAR PERSISTENT VAR_INPUT VAR_OUTPUT VAR_IN_OUT AT %IX AT %IB

p_diName i_xEnable q_xError iq_stParameters

ati_ AT %IW AT %ID

Direct access to input memory

ati_bName

AT %QB atq_ AT %QW AT %QD AT %MX AT %MB atm_ AT %MW AT %MD

Direct access to output memory

atq_bName

Direct access to memory location

atm_bName

405

Chapter: Appendix I Variable Naming Convention

AT %QX

Table 3.7 Property Prefix

NOTE: Do not declare constants as RETAIN or PERSISTENT.

The name of the AT-declared variable also contains the type of the target variable. It is used like the type prefix:

atm_rMyVar1 atm_rMyVar2

AT %MW0 : REAL; AT %MW4 : REAL;

406

Chapter: Appendix I Variable Naming Convention

h. POU Prefix
The program organization units defined in IEC 61131-3 are:

Function Function block Program Action

The designator is composed of a POU prefix and as short a name as possible (e.g. FB_GetResult). Just like a variable, the first letter of each word in the POU name is capitalized. We recommend that you form a composite POU name from a verb and a noun. The prefix comes with an underscore before the name and identifies the type of POU on the basis of the following table:

POU Prefix P_ FB_ F_ A_

Type PROGRAM FUNCTION_BLOCK FUNCTION ACTION

Use Program Function block declaration Functions Action

Example P_RecipeManagement FB_AxisController F_GetLrealString A_GetCommand Chapter: Appendix I Variable Naming Convention

Table 3.8 POU Prefix

407

i. Structures
The name of each structure data type consists of a prefix ST_ and a short, meaningful description in upper case (e.g. ST_STATION_NUMBER). If several words have been put together, they are separated by an underscore. Each component of the structure must be identified with a type prefix.

TYPE ST_FEED_PARAMETERS : (* Parameters for MC_MoveVelocity FB *) STRUCT lrVel lrAcc lrDecel lrJerk eDirection lrStopPos END_STRUCT END_TYPE : LREAL := 100.0; : LREAL := 2000.0; : LREAL := 2000.0; : LREAL := 10000.0; : MC_Direction := MC_Positive_Direction; : LREAL := 0.0;

stAxis1Feed

: ST_FEED_PARAMETERS;

408

Chapter: Appendix I Variable Naming Convention

Declaration example:

j. List Types
The name of a list type consists of a prefix ET_ and a short, meaningful description in upper case (e.g. ET_WORKING_DAY). If several words have been put together, they are separated by an underscore. The individual elements of list types are identified with the prefix E_.

TYPE ET_EVENT_TYPES : ( E_EVENT_NO_EVENT := 0, E_EVENT_FAULT_ACTIVE := 1, E_EVENT_FAULT_RESET := 2, E_EVENT_FAULT_ACK := 3, E_EVENT_USER_1 := 10 ); END_TYPE (* Fault Just Occurred *) (* Fault Is Gone and Acknowledged By AutoReset *) (* Fault Is Are Gone and Ack By Reset Input *) (* User Event *)

Variables and constants declared as a list type are prefixed with a lower case:

NOTE: 2 bytes of memory are reserved for each list variable.

409

Chapter: Appendix I Variable Naming Convention

eMyEvent

: ET_EVENT_TYPES;

k. Libraries
Designators contained within a library and the library name itself is prefixed with a code to quickly identify the source and to match the designator with the library.

MyLib_gc_diMaxConvCount MyLib_ConveyorControl.lib

410

Chapter: Appendix I Variable Naming Convention

54. Good Programming Practices a. Comments


Comments are essential for understanding source code; however, each individual line of code does not need to be commented. Limit your comments to the necessary minimum. It is more important to keep code clear and understandable. This minimizes the amount of comments required. If all POUs and variables have meaningful names, comments can be shorter. However, if the code is difficult to understand and there are no comments, even the programmer will have trouble understanding it after a short time. If variables have been given unusual values, for example, it is extremely important to explain the reason for this to prevent future misunderstandings. Write your comments so that they are not only notes for the programmer but can also be understood by third parties.

b. Array Indexing
Array should always be index starting at zero to prevent range errors. This typically occurs when the variable used to index an array is not initialized properly as shown below.
iCurrentRecipe astRecipes : INT; : ARRAY[1..10] OF ST_RECIPE;

The problem is corrected as follows:


astRecipes : ARRAY[0..10] OF ST_RECIPE;

The first element of the array, 0, is either not used or used as a default.

c. Program Calls
Parenthesis should be used when calling programs and actions as shown below:
P_SearchData();

411

Chapter:

Index

A
Actions .................................................................. 28, 96, 97 AMS ...................................... 20, 21, 22, 178, 179, 375, 379 Array ....................................... 103, 104, 106, 317, 398, 406

POU .8, 67, 68, 69, 75, 84, 97, 135, 153, 163, 164, 165, 166, 170, 171, 186, 187, 196, 200, 205, 206, 210, 214, 240, 265, 270, 284, 285, 286, 288, 289, 394, 396, 400, 401, 402 Priorities ........................................................................... 34

F
FBD.......................................................... 12, 77, 79, 83, 170

R
Registration ......................................... 23, 24, 50, 58, 63, 64 Remote .............................................. 21, 22, 37, 58, 59, 379

I
IL 12, 13, 77 Instruction List ...........................................................405

S
SFC ........................................................... 12, 77, 80, 81, 135 ST 12, 13, 77, 81, 82, 135, 164, 187, 326, 366, 367, 397, 399, 403, 406

L
LD 12, 77, 78

T P
TwinCAT 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 25, 26, 29, 30, 31, 32, 37, 38, 46, 47, 48, 49, 50, 57, 58, 59, 60, 61, 62, 63, 64, 65, 69, 70, 77, 82, 86, 88, 107, 110, 112, 132, 133, 134, 139, 168, 170, 171, 172, 175, 177, 178, 263, 268, 290, 298, 299, 304, 306, 307, 310, 311, 312, 318, 320, 335, 337, 340, 369, 374, 375, 378, 379, 380, 384, 385, 387, 391

PLC 10, 11, 12, 13, 14, 15, 16, 22, 23, 25, 26, 29, 41, 42, 43, 45, 57, 59, 65, 66, 67, 68, 69, 72, 73, 74, 75, 76, 77, 84, 87, 107, 108, 109, 110, 112, 132, 133, 139, 140, 144, 153, 155, 156, 165, 168, 199, 200, 202, 204, 208, 215, 216, 217, 218, 220, 221, 222, 225, 228, 230, 263, 266, 267, 268, 269, 270, 271, 273, 275, 281, 284, 285, 290, 297, 298, 299, 300, 305, 309, 311, 315, 318, 320, 323, 329, 330, 337, 369, 370, 374, 375, 376, 378

412

Chapter:

You might also like