You are on page 1of 304

Multilizer PDF Translator Free version - translation is limited to ~ 3 pages per translation.

Teknologi otomatisasi baru Beckhoff

TwinCAT 2

Direvisi: 28 Mei 2012 Brian McClure b.McClure@beckhoff.com

Multilizer PDF Translator Free version - translation is limited to ~ 3 pages per translation.

Multilizer PDF Translator Free version - translation is limited to ~ 3 pages per translation.
TwinCAT 2

Daftar isi
SAYA. TwinCAT Overview............................................................................................................................................................ 7 #Pages [7] 1. 2. 3. 4. Overview ............................................................................................................................................................. 7 #Pages [7] System Service .................................................................................................................................................. 13 #Pages [13] System Manager ............................................................................................................................................... 21 #Pages [21] PLC Control ........................................................................................................................................................ 38 #Pages [38] TwinCAT Versions .............................................................................................................................................. 39 #Pages [39] Software, Download & Installation ................................................................................................................... 41 #Pages [41] Licensing and Registration ................................................................................................................................ 54 #Pages [54]

II. TwinCAT Software Installation ....................................................................................................................................... 39 #Pages [39] 5. 6. 7.

III. PLC Ikhtisar.... 56 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

#Pages [56]

IDE ..................................................................................................................................................................... 56 #Pages [56] Programs ........................................................................................................................................................... 60 #Pages [60] Data Types and Conversions ......................................................................................................................... 61 #Pages [61] Variables ........................................................................................................................................................ 64 #Pages [64] Languages ...................................................................................................................................................... 68 #Pages [68] Functions ....................................................................................................................................................... 73 #Pages [73] Function Blocks ............................................................................................................................................. 76 #Pages [76] Actions ........................................................................................................................................................... 83 #Pages [83] Structures ...................................................................................................................................................... 84 #Pages [84] Enumerations ................................................................................................................................................ 86 #Pages [86] Arrays ............................................................................................................................................................ 89 #Pages [89] Boot Project .................................................................................................................................................. 92 #Pages [92] Source code Download ................................................................................................................................. 94 #Pages [94]

IV. PLC Programming "Inspeksi Conveyor".... 98 21.

#Pages [98]

Kontrol mesin dengan pemrograman... Top-Down. #Pages 98 [98] Code Sequencing ......................................................................................................................................... 171 #Pages [171] Break Points ................................................................................................................................................ 175 #Pages [175] Flow Control ................................................................................................................................................ 180 #Pages [180] Global Search .............................................................................................................................................. 184 #Pages [184] Cross Reference .......................................................................................................................................... 190 #Pages [190] Scope View .................................................................................................................................................. 196 #Pages [196]

V. Trouble shooting .......................................................................................................................................................... 171 #Pages [171] 22. 23. 24. 25. 26. 27.

Multilizer PDF Translator Free version - translation is limited to ~ 3 pages per translation.

Multilizer PDF Translator Free version - translation is limited to ~ 3 pages per translation.
TwinCAT 2

VI. Camming ....................................................................................................................................................................... 203 #Pages [203] 28. 29. a. b. c. 30. a. b. c. d. 31. a. b. Preface ........................................................................................................................................................ 203 #Pages [203] Intro to TcMC2.Lib....................................................................................................................................... 204 #Pages [204] Overview ......................................................................................................................................................... 204 #Pages [204] Migration from TcMC to TcMC2 ..................................................................................................................... 208 #Pages [208] Status information .......................................................................................................................................... 210 #Pages [210] When to use a Cam Table ........................................................................................................................... 211 #Pages [211] Overview ......................................................................................................................................................... 211 #Pages [211] Gearing ............................................................................................................................................................ 212 #Pages [212] Linier meningkatkan rasio Gear (dinamis).... 213 #Pages [213] Cam Table ........................................................................................................................................................ 214 #Pages [214] Membuat tabel Cam dengan fungsi blok....#Pages 215 [215] Overview ......................................................................................................................................................... 215 #Pages [215]

Mendefinisikan poin pada tabel Cam.... 215 #Pages [215] saya. Motion Function Point .................................................................................................................................... 215 #Pages [215] II. 32. a. b. Sample Code: .................................................................................................................................................. 217 #Pages [217] Defining the Cam Table in the PLC .............................................................................................................. 219 #Pages [219] Overview ......................................................................................................................................................... 219 #Pages [219] MC_CAM_REF ................................................................................................................................................. 219 #Pages [219] Contoh 2: Struktur Deskripsi fungsi gerak.... 220 #Pages [220] MC_TableType ................................................................................................................................................ 221 #Pages [221] Creating the Cam Table ............................................................................................................................... 222 #Pages [222] Overview ......................................................................................................................................................... 222 #Pages [222] MC_CamTableSelect ....................................................................................................................................... 222 #Pages [222] Mengimpor tabel Cam untuk verifikasi.... 224 #Pages [224] Overview ......................................................................................................................................................... 224 #Pages [224] Creating a Blank Table ..................................................................................................................................... 224 #Pages [224] Importing the Cam Table ................................................................................................................................ 227 #Pages [227] Camming the two Axes together ................................................................................................................ 230 #Pages [230] Overview ......................................................................................................................................................... 230 #Pages [230]

saya. Contoh 1: Posisi keterangan struktur tabel....#Pages 219 [219] II. c.

saya. Sample Code: .................................................................................................................................................. 221 #Pages [221] 33. a. b.

saya. Sample Code: .................................................................................................................................................. 223 #Pages [223] 34. a. b. c. 35. a.

Multilizer PDF Translator Free version - translation is limited to ~ 3 pages per translation.

TwinCAT 2

Once the Cam Table has been defined, verified, and created; the two axes are now ready to be cammed together. ................................................................................................................................................................................. 230 b. i. 36. a. b. c. d. i. 37. a. b. c. d. e. 38. a. b. i. ii. c. d. i. ii. 39. a. b. c. i. ii. 40. a. 41. MC_CamIn....................................................................................................................................................... 230 Sample Code: .................................................................................................................................................. 232 Changing a table point via the PLC .............................................................................................................. 233 Overview ......................................................................................................................................................... 233 MC_WriteMotionFunctionPoint ..................................................................................................................... 233 MC_SetCamOnlineChangeMode .................................................................................................................... 234 MC_CamActivationMode ................................................................................................................................ 236 Sample Code: .................................................................................................................................................. 237 Motion Functions vs. Position Tables ......................................................................................................... 239 Position Tables ................................................................................................................................................ 239 Motion Functions ............................................................................................................................................ 241 Definition of a Point ........................................................................................................................................ 242 Point structure ................................................................................................................................................ 242 Point types ...................................................................................................................................................... 243 Cam Design Tool .......................................................................................................................................... 244 Overview ......................................................................................................................................................... 244 Creating a Cam Table ...................................................................................................................................... 245 Master Tab ...................................................................................................................................................... 250 Slave Tab ......................................................................................................................................................... 251 Graphic Window ............................................................................................................................................. 252 Tables Window ................................................................................................................................................ 254 Function Types ................................................................................................................................................ 255 Commands ...................................................................................................................................................... 256 Cam Table Scaling ....................................................................................................................................... 258 Overview ......................................................................................................................................................... 258 MC_CamScaling............................................................................................................................................... 258 MC_CamScalingMode ..................................................................................................................................... 260 Example: .......................................................................................................................................................... 261 Sample Code: .................................................................................................................................................. 263 Cyclic Cam Plates with Lift........................................................................................................................... 264 MC_StartMode ................................................................................................................................................ 266 Cam Out and Restarting .............................................................................................................................. 268

TwinCAT 2

a. b. c. 42. a. b. c. d. e. 43. a. b.

Overview ......................................................................................................................................................... 268 MC_CamOut.................................................................................................................................................... 269 MC_Halt .......................................................................................................................................................... 270 MC_CamIn Appendix................................................................................................................................... 272 Axis coupling with cam plates ......................................................................................................................... 272 Linear cam plates ............................................................................................................................................ 273 Cyclic cam plates without lift .......................................................................................................................... 274 Cyclic cam plates with lift ................................................................................................................................ 275 Uncoupling and re-coupling for cyclic cam plates with lift ............................................................................. 276 Diagnostics .................................................................................................................................................. 277 Overview ......................................................................................................................................................... 277 Error Format .................................................................................................................................................... 277

Error Groups ............................................................................................................................................................ 278 c. d. e. f. Global Error Codes 0x0000.............................................................................................................................. 278 General ADS Error Codes 0x0700 .................................................................................................................... 278 NC Errors 0x4000 ............................................................................................................................................ 279 General NC Errors 0x40nn ............................................................................................................................... 279

Group Errors 0x42nn............................................................................................................................................... 280 g. Table Errors 0x4Ann ........................................................................................................................................ 281

VII. Remote Connections .................................................................................................................................................... 282 44. Embedded Controllers ................................................................................................................................ 282

VIII.Appendix I Variable Naming Convention ................................................................................................................... 294 45. 46. a. b. 47. a. b. c. d. e. f. g. Scope ........................................................................................................................................................... 294 Programming System Settings .................................................................................................................... 294 Font ................................................................................................................................................................. 294 Tab Width........................................................................................................................................................ 294 Naming ........................................................................................................................................................ 295 General............................................................................................................................................................ 295 Case Sensitivity ................................................................................................................................................ 295 Valid Characters .............................................................................................................................................. 295 Prefix Types ..................................................................................................................................................... 295 Scope Prefix ..................................................................................................................................................... 297 Type Prefix ....................................................................................................................................................... 298 Property Prefix ................................................................................................................................................ 299

TwinCAT 2

h. i. j. k. 48. a. b. c.

POU Prefix ....................................................................................................................................................... 300 Structures ........................................................................................................................................................ 301 List Types ......................................................................................................................................................... 302 Libraries ........................................................................................................................................................... 303 Good Programming Practices ..................................................................................................................... 304 Comments ....................................................................................................................................................... 304 Array Indexing ................................................................................................................................................. 304 Program Calls .................................................................................................................................................. 304

TwinCAT 2

I.

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. 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.

TwinCAT 2

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. 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 2

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. ander the CE operating system and the embedded operating systems for the series BX and BC controllers, only TwinCAT runtime 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).

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 2

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. 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 2

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. 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. 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, PLCopen-certified 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.

TwinCAT 2

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. 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.

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

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.

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

The System Manager and PLC Control can be 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 Trial) All services are enabled and running if configured to do so (i.e. Boot Project)

TwinCAT 2

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

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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 RightClicking 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 Right-Clicking 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.

TwinCAT 2

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

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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

Additional Tasks

TwinCAT 2

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

When used for simulation the Auto start must be checked

TwinCAT 2

Route Settings

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

TwinCAT 2

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.

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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 PLC-Configuration 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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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)

TwinCAT 2

II.

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 Required for CX5000

TwinCAT 2.11 R3

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

TwinCAT 2

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

TwinCAT 2

6. Software, Download & Installation


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

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

TwinCAT 2

Select TwinCAT

TwinCAT 2

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

TwinCAT 2

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

If you receive the following warning select Run

TwinCAT 2

Select your preferred language and then select next

The InstallShield Wizard will begin the install process

TwinCAT 2

When prompted select next

Accept the license agreement and select next

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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 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.

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

7. Licensing and Registration


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

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.

TwinCAT 2

TwinCAT 2

III.

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.

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

TwinCAT 2

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.

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

TwinCAT 2

A POU is opened by double-clicking on it.

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.

TwinCAT 2

Additionally there is a Message Window at the bottom.

The Message Window can be hidden or shown, from the Window menu select Messages or the keyboard shortcut Ctrl + K The Message window will show Errors, Warnings, and compile information.

TwinCAT 2

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 thereby values of the program are changed, then these changes are retained the next time the program is called, even if the program has been called from within 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 ., for example is 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. Where as a variable defined globally will only show the name of the variable.

TwinCAT 2

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.

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 ;

TwinCAT 2

Use the {BYTE, WORD, DWORD, SINT, USINT, INT, UINT, REAL, LREAL} data set is 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. 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.

TwinCAT 2

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) ;

TwinCAT 2

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

TwinCAT 2

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*)

Variable Scope Global Variables can be read and written to from anywhere in the PLC program 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

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*)

TwinCAT 2

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.

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.

TwinCAT 2

TwinCAT 2

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

TwinCAT 2

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

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

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.)

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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

TwinCAT 2

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

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

TwinCAT 2

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

TwinCAT 2

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

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

TwinCAT 2

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;

TwinCAT 2

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.

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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 intelli-sense window will appear, showing what elements exist inside of the structure

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

Initializing each index of an array

TwinCAT 2

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

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

TwinCAT 2

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

Creation

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

TwinCAT 2

TwinCAT 2

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

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.

TwinCAT 2

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

On the Open file dialog select the PLC button

Select the correct Target System Type

TwinCAT 2

Select the Run-Time on the Target

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

TwinCAT 2

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

TwinCAT 2

IV.

PLC Programming The Inspection Conveyor


21. 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 Input 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 mode 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.

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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.

TwinCAT 2

You should now have the following

Place a semicolon on Line 1 of MAIN.

TwinCAT 2

From the Project Menu, select Rebuild All

TwinCAT 2

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.

TwinCAT 2

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.

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.

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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.

TwinCAT 2

Between the key words VAR_GLOBAL and END_VAR is where we will declare our variables. Note: Please refer to the Appendix 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 (*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 Auto, 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 in Auto, 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 Auto, thereby applying 24 Volts DC to the output and turning on the light.

TwinCAT 2

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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 ,.

TwinCAT 2

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

TwinCAT 2

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.

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.

TwinCAT 2

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.

TwinCAT 2

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

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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

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

TwinCAT 2

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.

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.

TwinCAT 2

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

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.

TwinCAT 2

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

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

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.

TwinCAT 2

You will also need to do this after E_Auto and ELSE

If you have any other errors, please address them before moving on. 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.

TwinCAT 2

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.

TwinCAT 2

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

TwinCAT 2

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.

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.

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

Select TcUtilities in the list of libraries.

Notice that libraries can contain POUs, Data Types, Visualizations, and Global Variables. In the POU coloumn 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.

TwinCAT 2

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.

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

TwinCAT 2

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

TwinCAT 2

Select Tc_CpuUsage and click OK.

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

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

TwinCAT 2

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.

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

TwinCAT 2

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.

TwinCAT 2

The Input Assistant 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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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. Place the cursor on line 11 and press F2.

TwinCAT 2

Select Standard Function Blocks from the left column, expand the NT, W2K, XP, XPe, CE Operating System folder.

TwinCAT 2

Select the NT_GetTime Function Block and press OK

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

TwinCAT 2

Change the name to fbNT_GetTime.

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

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.

TwinCAT 2

Set the TMOUT to 500ms. Set the output variables and declare them as they are below.

The local declaration section should have the following

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

TwinCAT 2

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.

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. From the POU column right-click and select Add Object

TwinCAT 2

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 inly used internally within the Function Block.

In the VAR_INPUT section declare the following variables

TwinCAT 2

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

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

TwinCAT 2

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

TwinCAT 2

Now change the name of the TON and TOF to match the declaration section.

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 ,

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

TwinCAT 2

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. 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 ( , )

TwinCAT 2

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.

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

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. With i_tTimeOn highlighted, press the Enter key.

TwinCAT 2

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.

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

TwinCAT 2

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. It is also possible to select Monitoring Options from the Extras menu, then set the Distance of two variables value.

TwinCAT 2

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.

TwinCAT 2

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

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

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

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

TwinCAT 2

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. Start by adding a new Function and name it FB_LogStateMachine

TwinCAT 2

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

TwinCAT 2

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). 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 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. 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

TwinCAT 2

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 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; msgCtrlMask is used to define the parameters of the logged event

TwinCAT 2

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

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 The message in the log will be Machine State Changed to: Auto if sStateLog has a value of Auto

TwinCAT 2

Note: The ADSLOGSTR should always be called conditionally using a Rising Trigger Function Block; otherwise it will create a log message every PLC scan. 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.

TwinCAT 2

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

TwinCAT 2

Define the Function as below.

In the declaration section add the Input Variable

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. 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.

TwinCAT 2

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. 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.

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 4thPLC scan that iStep would have a value of 3.

TwinCAT 2

This code would never work inside of a Function. However if the variable to be evaluated is the variable that is passed into the Funciton 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 Funciton eState is then evaluated by the CASE statement to determine which part of the CASE statement to run

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

TwinCAT 2

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

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

TwinCAT 2

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.

TwinCAT 2

V.

Trouble shooting
22.

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

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

TwinCAT 2

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

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

23.

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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.

TwinCAT 2

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

TwinCAT 2

24.

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

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

TwinCAT 2

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

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

TwinCAT 2

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

TwinCAT 2

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

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

TwinCAT 2

25.

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

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.

TwinCAT 2

Once the sections have been selected press the OK button

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

The Global Search tool can be used to search for an element within a structure, the instance of the structure or both

TwinCAT 2

26.

Cross Reference
Variable Address POU

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

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

The variable name must me entered exactly as it is used in the PLC code

TwinCAT 2

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

TwinCAT 2

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)

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

27.

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

Leave the defaults and select OK

TwinCAT 2

Right click on Scope View 1 and select Add Channel

Give the Channel a descriptive name and press OK

TwinCAT 2

On the Acquisition Tab of the Channel press the Change button

TwinCAT 2

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

TwinCAT 2

Select MAIN.BSWITCH and press OK

TwinCAT 2

Press the Start button

TwinCAT 2

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

TwinCAT 2

VI.

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

28.

Preface

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.

TwinCAT 2

29.

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.

TwinCAT 2

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].

TwinCAT 2

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.

TwinCAT 2

Enable input and Valid output


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.

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 (non-queued 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 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 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 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 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 position with the velocity of the first command.

from

this

this

this

this

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.

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.

TwinCAT 2

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.

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.

TwinCAT 2

TcMC MC_GearInFloat

TcMC2 MC_GearIn

Remark MC_GearIn now accepts the gear ratio as a floating point value

MC_NewPos MC_NewPosAndVelo

MC_Move...

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.

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...

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_OrientedStop

MC_MoveModulo

MC_MoveModulo can be executed from standstill or in motion. If started in motion, the block will behave like MC_OrientedStop 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.

MC_Stop

MC_Halt, MC_Stop

TwinCAT 2

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.

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, these data have to 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.

TwinCAT 2

30.

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 single-column 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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

31.

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 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.

TwinCAT 2

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).

TwinCAT 2

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 (*Point 5*) VM_MotionFunctionPoints[5].PointIndex VM_MotionFunctionPoints[5].FunctionType VM_MotionFunctionPoints[5].PointType VM_MotionFunctionPoints[5].RelIndexNextPoint

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

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

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

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

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

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

:= := := :=

5; 15; 1; 1;

TwinCAT 2

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

:= :=

75; 0;

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

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

TwinCAT 2

32.

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.

TwinCAT 2

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.

TwinCAT 2

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;

TwinCAT 2

33.

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
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.

TwinCAT 2

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 );

TwinCAT 2

34.

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.

TwinCAT 2

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.

TwinCAT 2

You should now see an empty Cam Table.

TwinCAT 2

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.

TwinCAT 2

Change the ID: and select OK.

After verifying the Table ID, select Upload.

Leave the defaults and select OK.

TwinCAT 2

Your Cam Table should now look like the following.

TwinCAT 2

35.

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 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). CamTableID: ID of the cam plate used for coupling BufferMode: currently not implemented

TwinCAT 2

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 : BOOL; Busy : BOOL; Active : BOOL; CommandAborted : BOOL; Error : BOOL; ErrorID : UDINT; END_VAR 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;

TwinCAT 2

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 );

TwinCAT 2

36.

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;

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 Inputs/Outputs VAR_IN_OUT Point : MC_MotionFunctionPoint; END_VAR Point: Data structure containing the data of a motion function interpolation point Motion Function Point: Refer to Creating a Cam Table with Function Blocks

TwinCAT 2

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 change-over 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;

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.

TwinCAT 2

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

TwinCAT 2

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.

TwinCAT 2

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 ); := := 1; 1; := := 5; 15;

:= :=

75; 75;

TwinCAT 2

(*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 );

:= := :=

:= := 1; 1; := 0;

5; 15;

75;

(*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 );

TwinCAT 2

37.

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 3rdparty software using a mathematical formula (similar to a motion function) to create a table of 1000+ points.

TwinCAT 2

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.

TwinCAT 2

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 sub-sections. 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(n m ; M ) eff 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.

TwinCAT 2

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 INT32 Relative index of the end point (default: 0, subsequently corresponds 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 for rest in rest REAL64 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.

TwinCAT 2

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.

TwinCAT 2

38.

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.

TwinCAT 2

b. Creating a Cam Table


Right click on Tables and select Append Table

Leave the defaults and select OK.

TwinCAT 2

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.

TwinCAT 2

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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).

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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).

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.

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

TwinCAT 2

39.

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 ActivationMode: ActivationMode specifies the scaling time and position.

TwinCAT 2

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 non-scaled 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

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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

TwinCAT 2

40.

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

41.

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.

TwinCAT 2

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;

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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

42.

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.

TwinCAT 2

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. 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.

TwinCAT 2

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.

TwinCAT 2

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.

TwinCAT 2

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 re-coupled, 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.

TwinCAT 2

43.

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 3rdparty 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.

TwinCAT 2

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

c. 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.

d. 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.

TwinCAT 2

e. 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

f. General NC Errors 0x40nn


0x4016 "Table identifier not allowed" Either an unacceptable value (not 1...255) has been used, Check your value of your TableID

or a ta

0x4052

"Axis not ready for operation" The axis is not complete, and is therefore not ready for

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.

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 from being ready. The R button on the right side of the ErrorID display will issue an IDN99 reset command to the drive.

TwinCAT 2

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.

TwinCAT 2

g. 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

TwinCAT 2

VII.

Remote Connections
44.

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

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

TwinCAT 2

Click OK

TwinCAT 2

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.

TwinCAT 2

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

Set/Reset TwinCAT to Config mode.

Click Ok

TwinCAT 2

Select SYSTEM Configuration, then Choose Target

Click Search (Ethernet)

TwinCAT 2

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 Enter User name and password of an Administrator account on the Target PC Not required for Windows CE Click OK

TwinCAT 2

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

TwinCAT 2

Select BasePLC Click OK

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

TwinCAT 2

If the below window appears click on Yes

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

TwinCAT 2

VIII.

Appendix I Variable Naming Convention


45. 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.

46.

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".

TwinCAT 2

47.

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:

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.

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

TwinCAT 2

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]

FB_AxisController FB_HeatGun P_Main F_GetLeftString

TwinCAT 2

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 : DINT := 100; (* Maximum Quantity of Active Faults *)

gc_diMaxEvents : DINT := 100; END_VAR

(* 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

TwinCAT 2

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 st fb

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

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 Structure Function Block

Example xName bName wName dwName siName iName diName usiName uiName udiName rName lrName dateName todName dtName tName sName pxName adiName eMotorType 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;

TwinCAT 2

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_ p_ i_ q_ iq_ ati_

Type VAR CONSTANT VAR RETAIN VAR PERSISTENT VAR_INPUT VAR_OUTPUT VAR_IN_OUT AT %IX AT %IB AT %IW AT %ID AT %QX AT %QB AT %QW AT %QD AT %MX AT %MB AT %MW AT %MD

Use Local constant Remnant variable type retain Remnant variable type persistent Input variable of POU Output variable of POU In/out variable of POU Direct access to input memory Direct access to output memory Direct access to memory location

Example c_xName r_xName p_diName i_xEnable q_xError iq_stParameters ati_bName

atq_

atq_bName

atm_

atm_bName

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;

TwinCAT 2

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_BLOC K FUNCTION ACTION

Use Program Function block declaration Functions Action

Example P_RecipeManageme nt FB_AxisController F_GetLrealString A_GetCommand

Table 3.8 POU Prefix

TwinCAT 2

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;

Declaration example:

stAxis1Feed

: ST_FEED_PARAMETERS;

TwinCAT 2

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:

eMyEvent

: ET_EVENT_TYPES;

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

TwinCAT 2

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

TwinCAT 2

48.

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();

You might also like