TwinCAT 2 Manual v3.0.1



Comments



Description

Beckhoff New Automation TechnologyTwinCAT 2 Revised: November 8, 2013 Brian McClure [email protected] 2 Preface This Manual is intended for anyone who is interested in the TwinCAT software. From electricians, to electrical engineers, and even computer scientists; all levels of experience can benefit from the material covered in this manual. The material is a result of the combined efforts of many engineers within Beckhoff Automation. We have reviewed and revised the information in an effort to make it as precise and correct as possible; however, nothing is perfect. But, we would like for it to be. If you find any issues, or items that you think need more explanation, please let us know by contacting the author at [email protected]. 3 Revision Notes V3.0.0 Added – Chapter Digital I/O This chapter covers the first section of “The Inspection Conveyor” utilizing Digital Inputs and Outputs to control the conveyor. Index Added Table of Contents and Page numbering modified V3.0.1 Added – Code Changes to PLC Overview Added – Lamp Test to Trouble shooting Index Updated Page Number Wrapping Fixed Added - Labs 4 I. Contents II. TWINCAT OVERVIEW 11 11 18 26 44 45 45 47 62 64 64 68 69 72 77 83 87 96 97 99 102 106 108 112 130 1. 2. 3. 4. OVERVIEW SYSTEM SERVICE SYSTEM MANAGER PLC CONTROL III. TWINCAT SOFTWARE INSTALLATION 5. TWINCAT VERSIONS 6. SOFTWARE, DOWNLOAD & INSTALLATION 7. LICENSING AND REGISTRATION IV. PLC OVERVIEW 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. IDE PROGRAMS DATA TYPES AND CONVERSIONS VARIABLES LANGUAGES FUNCTIONS FUNCTION BLOCKS ACTIONS STRUCTURES ENUMERATIONS ARRAYS BOOT PROJECT SOURCE CODE DOWNLOAD CODE CHANGES V. PLC PROGRAMMING “THE INSPECTION CONVEYOR” 5 22. MACHINE CONTROL WITH TOP-DOWN PROGRAMMING 23. DIGITAL I/O VI. TROUBLE SHOOTING 24. 25. 26. 27. 28. 29. 30. LAMP TEST CODE SEQUENCING BREAK POINTS FLOW CONTROL GLOBAL SEARCH CROSS REFERENCE SCOPE VIEW 130 206 241 241 256 260 265 271 277 283 290 290 301 302 305 305 306 306 310 313 314 314 315 316 317 318 318 318 318 320 322 322 322 322 323 VII. LABS 31. LANGUAGES 32. LINEAR SCALING USING A RATIO 33. LINEAR SCALING USING AN EQUATION VIII. CAMMING 34. PREFACE 35. INTRO TO TCMC2.LIB A. OVERVIEW B. MIGRATION FROM TCMC TO TCMC2 C. STATUS INFORMATION 36. WHEN TO USE A CAM TABLE A. OVERVIEW B. GEARING C. LINEARLY INCREASING GEAR RATIO (DYNAMIC) D. CAM TABLE 37. CREATING A CAM TABLE WITH FUNCTION BLOCKS A. OVERVIEW B. DEFINING THE POINTS ON THE CAM TABLE I. MOTION FUNCTION POINT II. SAMPLE CODE: 38. DEFINING THE CAM TABLE IN THE PLC A. OVERVIEW B. MC_CAM_REF I. EXAMPLE 1: POSITION TABLE STRUCTURE DESCRIPTION II. EXAMPLE 2: STRUCTURE DESCRIPTION OF A MOTION FUNCTION 6 C. MC_TABLETYPE I. SAMPLE CODE: 39. CREATING THE CAM TABLE A. OVERVIEW B. MC_CAMTABLESELECT I. SAMPLE CODE: 40. IMPORTING A CAM TABLE FOR VERIFICATION A. OVERVIEW B. CREATING A BLANK TABLE C. IMPORTING THE CAM TABLE 41. CAMMING THE TWO AXES TOGETHER A. OVERVIEW ONCE THE CAM TABLE HAS BEEN DEFINED, VERIFIED, AND CREATED; THE TWO AXES ARE NOW READY TO BE CAMMED TOGETHER. B. MC_CAMIN I. SAMPLE CODE: 42. CHANGING A TABLE POINT VIA THE PLC A. OVERVIEW B. MC_WRITEMOTIONFUNCTIONPOINT C. MC_SETCAMONLINECHANGEMODE D. MC_CAMACTIVATIONMODE I. SAMPLE CODE: 43. MOTION FUNCTIONS VS. POSITION TABLES A. POSITION TABLES B. MOTION FUNCTIONS C. DEFINITION OF A POINT D. POINT STRUCTURE E. POINT TYPES 44. CAM DESIGN TOOL A. OVERVIEW B. CREATING A CAM TABLE I. MASTER TAB II. SLAVE TAB C. GRAPHIC WINDOW D. TABLES WINDOW I. FUNCTION TYPES II. COMMANDS 45. CAM TABLE SCALING A. OVERVIEW B. MC_CAMSCALING C. MC_CAMSCALINGMODE I. EXAMPLE: 324 324 325 325 325 326 327 327 327 330 333 333 333 333 335 336 336 336 337 339 340 342 342 344 345 345 346 347 347 348 353 354 355 357 358 359 361 361 361 363 364 7 II. 46. A. 47. A. B. C. 48. A. B. C. D. E. 49. A. B. SAMPLE CODE: CYCLIC CAM PLATES WITH LIFT MC_STARTMODE CAM OUT AND RESTARTING OVERVIEW MC_CAMOUT MC_HALT MC_CAMIN APPENDIX AXIS COUPLING WITH CAM PLATES LINEAR CAM PLATES CYCLIC CAM PLATES WITHOUT LIFT CYCLIC CAM PLATES WITH LIFT UNCOUPLING AND RE-COUPLING FOR CYCLIC CAM PLATES WITH LIFT DIAGNOSTICS OVERVIEW ERROR FORMAT 366 367 369 371 371 372 373 375 375 375 377 378 379 380 380 380 385 385 398 398 399 399 399 400 400 400 400 401 402 403 405 407 408 409 410 411 411 IX. REMOTE CONNECTIONS 50. EMBEDDED CONTROLLERS X. APPENDIX I – VARIABLE NAMING CONVENTION 51. SCOPE 52. PROGRAMMING SYSTEM SETTINGS A. FONT B. TAB WIDTH 53. NAMING A. GENERAL B. CASE SENSITIVITY C. VALID CHARACTERS D. PREFIX TYPES E. SCOPE PREFIX F. TYPE PREFIX G. PROPERTY PREFIX H. POU PREFIX I. STRUCTURES J. LIST TYPES K. LIBRARIES 54. GOOD PROGRAMMING PRACTICES A. COMMENTS 8 PROGRAM CALLS 411 411 9 .B. ARRAY INDEXING C. 1 0 . compatible PC hardware embedded IEC 61131-3 software PLC. TwinCAT indicates the system load for programs that are running. etc. 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. diagnostics and configuration. A practical oriented software solution  TwinCAT offers a precise time base in which programs are executed with the highest deterministic features. a system message is generated. Windows 7. software NC and software CNC in Windows NT/2000/XP/Vista. NT/XP Embedded.)     Architecture  TwinCAT consists of run-time systems that execute control programs in real-time and the development environments for programming. TwinCAT Overview 1. TwinCAT replaces conventional PLC and NC/CNC controllers as well as operating devices with:   open. or can execute commands. visualization programs or MS Office programs. independently of other processor tasks. for instance. 11 Chapter: TwinCAT Overview . programming environment and operating station. The real-time load on a PC is set with TwinCAT. can access TwinCAT data via Microsoft interfaces. defined operating behavior is achieved in this way. NC axis control. 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.II. DLL. Any Windows programs. 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. If this threshold is exceeded. OCX. TwinCAT loads programs and remnant data. Start/Stop behavior  Depending on the setting. CANopen.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. Since TwinCAT is integrated into Windows NT/2000/XP/Vista and Windows 7as a service. The system offers scalable communication capacity and timeout periods for the supervision of communications. 12 Chapter: TwinCAT Overview . PC systems can be connected with each other via TCP/IP. Lightbus. PROFIBUS DP. giving administrators an easy way to evaluate the hardware and software. both in the system and via TCP/IP connections. World-wide access  Since standard TCP/IP services of NT/2000/XP/Vista/CE and Windows 7 can be used. Beckhoff has integrated a practical indicator of the real-time jitter. the TwinCAT software devices can be distributed: TwinCAT PLC programs can run on the PCs or on Beckhoff Bus Terminal Controllers. TwinCAT is started and stopped manually or automatically. RS485. RS232. A system message during operation can draw attention to incorrect states. To back up data and to shut down Windows NT/2000/XP/Vista and Windows 7 correctly. OPC provides a standardized means for accessing many different SCADA/MES/ERP packets. Ethernet TCP/IP). Restarting and data backup  When a program is started or restarted. A “message router” manages and distributes all the messages. World-wide connection through message routing – “remote” connection is inherent to the system  According to the requirement for operating resources. an operator is not needed to start the system: switching on is enough. Bus Terminal Controllers are integrated via serial interfaces and fieldbuses (EtherCAT. a UPS (uninterruptible power supply) is of great value. this data can be exchanged across the world. 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. Master and slave functionality is supported. so that an additional programming device is not required.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. TwinCAT PLC allows up to four virtual “PLC CPUs”. via TCP/IP or via the fieldbus (BXxxxx and BCxxxx). TwinCAT PLC – the central pillar of automation software  Conceived as a pure software PLC. LD (Ladder Diagram). Chapter: TwinCAT Overview 13 . FBD/CFC (Function Block Diagram). The fieldbus cards can be configured and diagnosed conveniently via the TwinCAT System Manager. Under the CE operating system and the embedded operating systems for the series BX and BC controllers. Program modifications are implemented via network-capable powerful communication with the run-time system. only TwinCAT run-time is available. each running up to four user tasks. on one PC. depending on the selected fieldbus card. Programming can be done    locally. It is possible to operate more than one fieldbus card per 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). TwinCAT I/O includes the TwinCAT real-time system for operating the fieldbuses and a DLL interface to application programs. the project comparison function facilitates differences to be identified and accepted if appropriate. If a project (comments. TwinCAT PLC is certified for the languages IL and ST (base level). etc. system libraries for message outputs. the PLC project can also be loaded into the BC and BX series fieldbus controllers from Beckhoff. libraries for controlling electrical and hydraulic axes via TwinCAT NC. write/read files. For all programming languages. regardless of which unit is executing the program. Incremental compilation prevents long turnaroand times. such as “autoformat”. data types. Chapter: TwinCAT Overview    14 . providing maximum data retention. Many target platforms – one tool  The PLC programs created with TwinCAT PLC can be executed on a number of target platforms. Source code can be stored in the target system (except for BCxxxx series controllers).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. effective compiler. etc. translated and re-imported. This enables changes to be traced back and differences between individual versions to be displayed. all terms can be exported into a table. Multi-dimensional fields and structures are possible. multi-stage password protection can be applied to programs and libraries. Beckhoff offers a wide range of supplementary libraries for the execution of tasks typical in automation technology: e.g. in which each instance is associated with its own data. serial communication libraries. The online change function can be used for code and/or data modifications while the PLC is running. TwinCAT supports all the IEC 61131-3 programming languages with convenient editors and a fast. Powerful editor features. For know-how protection. Code can very easily be reused via the convenient library manager. as are enumeration and subrange types. all objects (blocks. directories.) is to be translated into a language other than the original language. If a team is dealing with the development. lists) can be managed within a source code management tool via the TwinCAT Engineering Interface. All common data types specified in IEC 61131-3 are supported. The concept of the “instantiation” of function blocks. The criteria analysis function is very helpful for the detection of process errors. control technology blocks. Only genuinely new sections are compiled. so that the development cycle for the creation even of large PLC programs of several megabytes can be short. “autodeclare” or “find” and “replace” enable fast programming. Program development and debugging proceed in the same working environment. leads naturally to object-oriented and structured programming styles. Apart from Industrial PCs and the Embedded PCs. Extensive supplementary libraries  As an extension to the blocks defined by the IEC language standard. whereby the position controller is usually calculated on the PC: The computing capacity of a PC enables many axes to be positioned simultaneously. the PLC and the NC at the same time. the position controller is calculated on the PC processor as standard.Helpful practice tools  Extensive fault finding functions in TwinCAT PLC facilitate the solution of problems either on site or via remote maintenance. The division of the system load is supported by TwinCAT with appropriate functions. TwinCAT enables a PC to process the operating programs. In addition. It exchanges data cyclically with drives and measurement systems via the fieldbus. 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. the TwinCAT ScopeView (a software oscilloscope) can be used to record one or several variables simultaneously. Chapter: TwinCAT Overview Central NC positioning on the PC  The computing capacity of a PC enables axis motion simultaneously with the PLC. For this purpose.           15 . 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. A convenient dialog enables the dynamic parameters of an axis to be determined. acceleration and jerk. TwinCAT ScopeView is helpful for commissioning and maintenance. Chapter: TwinCAT Overview 16 . moving from its starting point to its destination (point-to-point positioning). For each axis. acceleration and jerk. cam plates or distance compensation can be triggered and observed via the System Manager. It records all axis variables such as position. PLCopencertified function blocks. TwinCAT NC also allows the coordinated movement of a number of axes in multi-stage master-slave operation (e. The communication between the two packages is a pure software/software channel with minimum delay times. Software PLC included  TwinCAT combines software NC and software PLC to form a powerful controller. and the complete machine flow is checked. Individual or joint  Based on the normal methods for positioning an individual electrical axis. gearing functions or cam plates) to be executed. In this way. The axes can be moved via function keys. all main data are displayed at a glance. the axes are moved at any time within the limits of what is dynamically possible. speed. The NC functionalities are called from the PLC program via standardized. Special functions such as couplings.g. and are precisely analytically coordinated.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. A range of different regulation algorithms are available in order to reduce the deviations from the ideal trajectory that will occur in practice. the actual value is instructed to ideally track the set value.  Convenient commissioning  Commissioning is simplified significantly by the configuration and diagnostic dialogs offered in the TwinCAT System Manager. TwinCAT NC I further allows the interpolated path sequencing described in accordance with DIN 66025 to be carried out involving up to three axes. Axis movements can be simulated without hardware. PLC functionality is integrated.  17 Chapter: TwinCAT Overview . Parts programming is carried out according to DIN 66025 using high-level language extensions. as is the connection of the axes with the fieldbus. The interpreter interprets the code described in DIN 66025. In a CNC channel. 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. enabling even the most difficult motion tasks to be solved. up to 32 axes can be interpolated simultaneously.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. set value generation and position controller. for example. 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. can be loaded directly from the PLC program into the interpreter. The system includes interpreter. NC programs. Comprehensive PLC libraries enable interaction between NC and PLC.  The TwinCAT System Service can be accessed through the TwinCAT icon in the windows system tray (Right-Click and Left-Click provides the same menu)  From this menu the other parts of the TwinCAT system can be accessed and the TwinCAT System Properties can be changed 18 Chapter: TwinCAT Overview .2. System Service  The TwinCAT System Service is represented by the TwinCAT icon in the Windows system tray. Key is empty  19 Chapter: TwinCAT Overview . The General tab of the system properties provides the version number and registration information of TwinCAT Note that the 30 day counter has started and the Reg. remote communication is possible Chapter: TwinCAT Overview  Auto Logon:  Enabling this option and providing a User Name and Password will allow for the Windows Logon screen to be bypassed. Note: See the security section for protecting the windows registry.  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. 20 . 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. xxx.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.xxx. 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.1 added to the end The first four octets of the address can be changed to any number between 0 and 255.xxx.1.1.1 represents the external address and other values are used internally Chapter: TwinCAT Overview   21 . They do not have to match the IP address The last two octets should not be changed as .  Remote Computers  The lower section provides a list of remote computers than have been previously configured for AMS communication Remote Computers can be manually added or removed from here The list of computers is loaded when TwinCAT enters either Config or Run mode. therefore if a computer is added or removed from here. TwinCAT must be restarted to update the list of Target Computers in the System Manager   22 Chapter: TwinCAT Overview .  PLC    Up to 4 PLC Run-Times can be configured The path of the Boot Project can be changed The selection to enable the Boot Project and Retain Data can be made 23 Chapter: TwinCAT Overview . In the event of a Hard Disk failure these two numbers and the new System ID can be used to generate a new Registration Key Otherwise the original PO is needed to generate a new Registration Key 24 Chapter: TwinCAT Overview . 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.  The System Manager and PLC Control can also be accessed through this menu or the Windows Start menu Additionally the local TwinCAT System can be placed into its different modes  Stop Mode   The system is not capable of communication and no services are running  Config Mode    The ADS Router is running and communication is possible Scanning of hardware is done is this mode only I/O values are updated at the hardware level  Run Mode (Requires License beyond 30 day Trial)  All services are enabled and running if configured to do so (i. Boot Project) 25 Chapter: TwinCAT Overview .e. 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.3. Interpolation Channels System Configuration – Properties of the Target System and Real-Time Usage 26 Chapter: TwinCAT Overview . 27 Chapter: TwinCAT Overview . by using ‘Open from Target’ also referred to as ‘The Red Folder’.tsm file from the Boot folder.  Additionally provides a way to open the CurrentConfig.Menus and Controls  File Menu – Allows for creating a new file or opening a saved file.  Actions – Any time a change is made to the System Manager. Note: The first 6 commands in the ‘Actions’ menu will be sent to the Target system either local or remote. the ‘Activate Configuration’ must be done to implement this change into the running system. 28 Chapter: TwinCAT Overview . almost every item you wish to add in both the system manager and the PLC will be done by ‘RightClicking’ and select ‘Add.. 29 Chapter: TwinCAT Overview .’ 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. When an item on the left is selected its information will be displayed on the right. Become familiar with this..The tree view on the left provides access to the configurations of the system manager. Items can be added to the System Manager be ‘Right-Clicking’ on an existing item. General – The TwinCAT version is provided here in bold The ‘Choose Target…’ button can be used to access a remote TwinCAT system. 30 Chapter: TwinCAT Overview .   Boot Settings – can be used to set the TwinCAT Mode on startup and the Auto Logon When pointed to a remote system these setting will be applied to the remote system. and an Administrator level user name and password must be provided. The ‘Apply’ button must be used. 31 Chapter: TwinCAT Overview .  Real-Time Settings   Settings – Here the Base Time is set. The CPU limit of 80% means that TwinCAT will consume no more than 80% to run all of its tasks. 32 Chapter: TwinCAT Overview . no task can be set to a faster interval than the base time.  Online – The ‘Real Time Usage’ is graphed and the limit from the ‘Settings’ tab is indicated by the thick green line System Latency should be no more than 5 micro seconds   Note: Image taken from a laptop with power save features and CPU throttling enabled. both of these create latency problems. 33 Chapter: TwinCAT Overview .  Priorities – The list of tasks and their priorities can be seen here 34 Chapter: TwinCAT Overview .  Additional Tasks    Task 1 (added by ‘Right-Clicking’ on ‘Additional Tasks’) These additional tasks are used by C++ code to talk to variables that are linked to hardware I/O They can also be used for simulation 35 Chapter: TwinCAT Overview . When used for simulation the ‘Auto start’ must be checked 36 Chapter: TwinCAT Overview . 37 Chapter: TwinCAT Overview . Route Settings  Current Routes – The Remote Computers shown in this list are the same as in the ‘Properties’ of the TwinCAT icon. Axes – The software limits the total number of axes to 255. NC Configuration (Numerical Control) – This is the software based motion controller of TwinCAT. The software side of all axes are configured here. 38 Chapter: TwinCAT Overview . the real limit is the amount of CPU and RAM in the computer. The ‘Online’ tab provides an overview of the status of all axes 39 Chapter: TwinCAT Overview .   Axes 1 – Online The ‘Online’ tab of each axis provides a useful interface to setup and troubleshoot an axis 40 Chapter: TwinCAT Overview . tpy” file was located when it was added to the project. If addressed variables are added to the PLC program the ‘ReScan’ button can be used to update the list of variables in the System Manager  41 Chapter: TwinCAT Overview . The name of the PLC project file is shown directly below the ‘PLCConfiguration’ The ‘IEC1131’ Tab shows the path of where the “. PLC Configuration  IEC Project – The PLC editor will create a “.tpy” file that contains addressed variables that can be linked to hardware.  Standard Task – The default task in the PLC is the ‘Standard’ task and runs every 10ms  Inputs of the PLC Program – Input variables have a yellow icon. Output variables have a red icon 42 Chapter: TwinCAT Overview . Once a variable has been linked (connected) to hardware the icon changes as below 43 Chapter: TwinCAT Overview .     The IEC 61131-3 Language editors A Visualization Editor Task Configuration Utility The Beckhoff Compilers specific to the Target Hardware (BC. CX-ARM. X86) 44 Chapter: TwinCAT Overview . PLC Control  The PLC Control provides the user with a combination of tools. BX.4. 11 Build 1552 TwinCAT 2.9 TwinCAT 2. 1999 TwinCAT 2.7 TwinCAT 2.III.11 R2   Change in preparation for TwinCAT 3 Chapter: TwinCAT Software Installation Required for CX5000  TwinCAT 2. TwinCAT Software Installation 5.8      Change from wsm to tsm Use of XML for system configuration Config Mode for scanning hardware TwinCAT 2.6 Build 315 August 2.11 R3 45 .10  TcMC2. 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.lib   TwinCAT 2. the following new features were implemented in Release 3 (2. additional interfaces like EtherCAT Slave EL7201 support (NC PTP) Supports new PCIe fieldbus adapters New Phasing functionality for NC PTP 46 Chapter: TwinCAT Software Installation .11.Release Notes: Changes from 2.11 TwinCAT Base System         Integration of MDP (Modular Device Profile – a generic interface for device information) Integration of configuration tool for AX5xxx drives Optimized behavior for use with Windows Vista and Windows 7 Optimization for TwinCAT running on Quad-core and Octo-core CPUs Time synchronization with EL6692 (EtherCAT bridge) Time synchronization with EL6688 (IEEE 1588/Precision Time Protocol) New modular structure of I/O drivers Base for new supplement products like TwinCAT Kinematic Transformation In addition to the features available in 2.10 to 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. the following new features were implemented in Release 2 (2.11 R3):     CX50xx.11 R2. beckhoff.com Select ‘Download’ from the top of the page 47 Chapter: TwinCAT Software Installation .6. Software. Download & Installation   The TwinCAT software can be downloaded from www.  Scroll down to the Software section and select TwinCAT 30 days version  Select TwinCAT 48 Chapter: TwinCAT Software Installation . containing a link to download the software 49 Chapter: TwinCAT Software Installation .   The form must be filled in with a valid email address Below the form you can select the version and build of TwinCAT you would like to download After selecting the “Registration” button an email will be sent. to the address provided.  Selecting the link in the email will start the download   Double-Click the exe file to start the installation process The file name will match the version number and build that you selected during the registration process 50 Chapter: TwinCAT Software Installation .  If you receive the following warning select Run  Select your preferred language and then select next 51 Chapter: TwinCAT Software Installation .  The InstallShield Wizard will begin the install process 52 Chapter: TwinCAT Software Installation .  When prompted select next 53 Chapter: TwinCAT Software Installation .  Accept the license agreement and select next 54 Chapter: TwinCAT Software Installation .   Fill in the User Name and Company Name (This information will be viewable in the software) Use ‘DEMO’ for the serial number 55 Chapter: TwinCAT Software Installation . used for OPC Server. and other ADS communication I/O – Includes the system manager for configuring hardware. Beckhoff Control Panels. used when writing C/C++ code to control the I/O PLC – Includes the IEC 61131-3 PLC editor and the Beckhoff compilers NC PTP – Numerical Control for Point to Point motion with associated libraries NC – I Numerical Control for Interpolated motion with associated libraries     56 Chapter: TwinCAT Software Installation . Selecting the level of TwinCAT to install (All levels are inclusive of lower levels)  CP – Includes the ADS driver. after 30 days TwinCAT will no longer go into run mode. Registration Type  30 Day demo – Full functionality for 30 days. Licenses can be provided within 24 hours except weekends and holidays   57 Chapter: TwinCAT Software Installation . 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. Development and Remote connections are still possible. TwinCAT Drive Manager – Used for Configuring the AX5000 servo drives TwinCAT BACnet/IP – BACnet Server for building Automation and HVAC systems. afterwards select Next to continue  TwinCAT I/O – Allows the direct access to IO via a DLL. TwinCAT Scope View – A software Oscilloscope for monitoring variables in real time TwinCAT Cam Server – A Cam tool for setting outputs on Lightbus.       58 . Can be installed with TwinCAT PLC or TwinCAT NC PTP. replaced by newer technology Chapter: TwinCAT Software Installation TwinCAT EDS and GSD files – files for DeviceNet and Profibus hardware TwinCAT Remote Manager – For managing different versions of TwinCAT on one PC. Select the additional features to install with TwinCAT  The desired features should be selected here. has never been sold in North America. project files that the user creates can be stored in any desired location 59 Chapter: TwinCAT Software Installation . 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  The installer will now install the needed components Chapter: TwinCAT Software Installation 60 . Specify the Program Folder for the TwinCAT installation  The default path is highly recommended.  You must reboot the PC after the installer has completed   After rebooting the PC you will see the TwinCAT icon in the Windows System Tray TwinCAT is in ‘Stop Mode’ by default 61 Chapter: TwinCAT Software Installation . and select properties 62 Chapter: TwinCAT Software Installation . Licensing and Registration Single left click the TwinCAT Icon in the system tray.7. Once properties is selected the ‘TwinCAT System Properties’ window will appear. 63 Chapter: TwinCAT Software Installation . 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. 64 Chapter: PLC Overview .IV. Use of the editors and debugging functions is based upon the proven development program environments of advanced programming languages. TwinCAT PLC Control puts a simple approach to the powerful IEC languages at the disposal of the PLC programmer. IDE The Integrated Development Environment (IDE) of TwinCAT provides a complete set of development tools for the PLC. The Left column provides four tabs at the bottom. PLC Overview 8. Programs.POUs – Program Organizational Units – This will contain the code written by the programmer. 65 Chapter: PLC Overview . Function Blocks. and Functions Data Types – Here the programmer can create Structures and Enumerations to be used in the PLC code Visualizations – Interface screens for use by Maintenance personnel or Operators can be created. The Global Variable Lists.Resources – The resources tab contains several items. Library Manager. A POU is opened by double-clicking on it. and Task Configuration are all accessible from this tab. 66 Chapter: PLC Overview . PLC Configuration. The POU contains 2 parts. and the Code section. 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. 67 Chapter: PLC Overview The Message Window can be hidden or shown. and compile information. The first line of the declaration section defines the type of POU and the name of the POU. The Message window will show Errors. Additionally there is a Message Window at the bottom. Warnings. the Declaration section. from the ‘Window’ menu select ‘Messages’ or the keyboard shortcut ‘Ctrl + ESC’ . Following this is the local variable declaration. the variable bStart is defined with an address as a local variable in MAIN. even if the program has been called from within a different program. the local variables declared inside of them will referenced by first using the name of the program and then the name of the variable.9. All values are retained from the last time the program was run until the next. Function Blocks. they can call Functions. separated by a dot ‘. from MAIN all other POUs are called. If a one program calls another program. Programs are recognized globally throughout the project. In the below example. whereas a variable defined globally will only show the name of the variable.’. Programs can call all types of POUs. Programs are called from either a PLC Task or another Program. 68 Chapter: PLC Overview . a Standard Task is created that calls the Program MAIN. By default when a new Project is started.bStart. Programs A program is a POU which returns several values during operation. then these changes are retained the next time the program is called. and if the values of the program are changed. in the PLC-Configuration of the TwinCAT System Manager the variable will be MAIN. Because Programs are recognized globally. and other Programs. The elementary data types within TwinCAT Plc Control are below. 69 Chapter: PLC Overview .10. Data Types and Conversions Elementary data types form the foundation of the programmer’s tools to represent and use information. 667. INT. however.The BOOL data type is used to define a Boolean or Bit-wise variable. equally. Use the {BYTE. Example: pushButton01 : BOOL . REAL.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. Declaration syntax: VariableName : DataType { := <Initial_Value } . For example. DWORD. The conversion operator BOOL_TO_INT may be used to convert a TRUE/FALSE into ‘1/0’.bitOffset NOTE: bitOffset cannot be a variable e. Example: (*Declares a double-word sized variable named ‘MyDWord’ with the initial value of ‘12345’*) MyDWord : DWORD := 12345 . Declaration syntax: VariableName : BOOL := InitialValue .g. WORD. WORD. The Plc Control editor recognizes a number as an integer unless explicitly defined as a REAL type. the Plc Control editor evaluates such an expression in integer division resulting in the value 2. UINT. USINT. LREAL} data set. “REAL#15/REAL#9” to evaluate as a floating point calculation. an individual bit of the data type may be extracted using the following syntax: VariableName. (*Example Status Word*) END_VAR Use: IF Status. DWORD} are considered bitwise data types.0” or. it must be a constant Example: Declaration: VAR Status : WORD. The BOOL data type takes the value of either TRUE or FALSE at runtime. The data set {BYTE. One must explicitly code “15. “15/9” input into a typical calculator will result in 1. SINT.0/9. 70 Chapter: PLC Overview . respectively. Declaration with Initial Value: drainValveOpen : BOOL := TRUE . LREAL} data set to define an appropriate value range for a variable. (* Declares STRING-type variable MyString with initialized value of “This is my string” *) MyString : STRING := ‘This is my string’ . 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 code snippet converts MyWordVariable from WORD to INT (integer). Conversion Functions are integrated within Plc Control to provide explicit conversion from one elementary data type to another. TIME for. The conversion operation is defined as a function.The STRING data type is utilized to define and use ASCII character strings. the duration of a timer. say. Declaration Example: VariableName : STRING { := ‘StringValue’ } . The function returns the argument’s value as the desired. The Plc Program Compiler should be able to detect when a programmer. DATE_TIME} data set supports duration measurement and/or time stamping. 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 {TIME. As such. WORD_TO_INT(MyWordVariable) The variable. For example. A STRING always occupies a memory size equal to the string size plus one byte for a null termination character. for example. MyReturnedInt := WORD_TO_INT(MyWordVariable) . 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. MyReturnedInt. TIME_OF_DAY. The necessary data type is selected depending on scope of measurement. is assigned to this converted value. attempts to assign a WORD variable to another variable of type TIME. converted data type. DATE. DATE_TIME for a time stamp vs. 71 Chapter: PLC Overview . Must begin with a Letter or an Underscore 2. Value 4. Can followed by Letters. Memory Location 5.11. Underscores. or Numbers     No distinction is made between Uppercase and Lowercase Letters Special characters cannot be used (!@#$%^&*) Blanks or Spaces are not allowed Repeated or Sequential Underscores are not allowed Descriptive abbreviations aid in understanding the value that is held by the variable 72 Chapter: PLC Overview . PLC Address  In accordance with IEC 61131-3 a variable name must adhere to the following rules 1. Name 2. Size (Defined by the Type) 3. Variables   A Variable is a name given to a location in memory that stores a value A Variable has up to 5 properties 1. 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 .The use of abbreviated data types in the name of the variable help in the understanding of what the variable is. (*iProduct Number is of type INT*) lrPressure : LREAL . (*lrPressure is of type LREAL*) Chapter: PLC Overview Variable Scope  Global Variables can be read and written to from anywhere in the PLC program 73 . (*bStart is of type BOOL*) iProductNumber : INT. 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.   Local Variables can only be written to from within the POU where they are defined The local variable of any POU can be read by first accessing the POU instance that the variable is defined in and then using the ‘.’ to access the local variables defined within that POU Local variables cannot be written to from another POU  74 Chapter: PLC Overview . after which the code of the PLC will control the value bStart : BOOL := FALSE .3 . (*bStart is of type BOOL and has an initial value of FALSE*) iProductNumber : INT := 1 .Initial Values   All Variables have the option of assigning an initial value This value will be written to memory when the PLC starts. (*lrPressure is of type LREAL and has an initial value of 2. (*iProduct Number is of type INT and has an initial value of 1*) lrPressure : LREAL := 2. (*fbTON1 is of type TON and the PT input has an initial value of 1 second*) Constants    Variables defined as Constants cannot be written to by the PLC Constants are declared similar to initial values Use of the keyword ‘Constant’ at the beginning of the declaration section signals the compiler that the variable is a constant.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) . 75 Chapter: PLC Overview . This file contains the old values of the persistent variables and is read on a TwinCAT start. Retain-Variables are reinitialized at a new download of the program unlike persistent variables. To initialize the PERSISTENT variables choose Reset all.Remnant Variables  Remnant variables can retain their value throughout the usual program run period. Variables stored with RETAIN are initialized after a "Rebuild all" of the PLC program. 76 Chapter: PLC Overview . 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‘. With a “Reset all” RETAIN variables are initialized. Therefore symbol generation must be selected. the stored values will be processed further. On a TwinCAT shutdown the persistent variables are written in a special file. Persistent variables conserve their old values after a "Rebuild all" of the PLC program. These include Retain variables and Persistent variables.   Persistent Data  These variables are stored with the complete symbol. When the program is run again. A concrete example would be a piece-counter in a production line that recommences counting after a power failure. Languages The IEC 61131-3 specifies 5 languages for writing PLC code. For example the following will increase the variable Speed by a value of 5    77 Chapter: PLC Overview . The command is then followed by a variable or a literal value.12. In IL only 1 command can be processed per line of 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. LD – Ladder Diagram   LD was created with the intention of representing the electrical wiring diagrams of relay logic LD is a graphical language that displays a power rail on each side that represents the supply and the common of the wiring diagram The below examples shows a common latching circuit in LD  78 Chapter: PLC Overview . FBD – Function Block Diagram   FBD is a graphical language that is similar to an electronic circuit diagram The below example has the same functionality as the above latching circuit 79 Chapter: PLC Overview . is better thought of as a way to organize code and control the sequence of operation Each Step and Transition in SFC has code inside of it that can be written in any of the other languages including SFC  80 Chapter: PLC Overview . although defined as a language.SFC – Sequential Function Chart  SFC. ST – Structured Text    ST is a high level language which looks similar in syntax to PASCAL ST is the most powerful and flexible of all the languages When using ST it is important to remember that the variable being written to (the output) is on the left The below example provides the same latching circuit operation as the ones above  81 Chapter: PLC Overview . and is able to be modified by the programmer   82 Chapter: PLC Overview . 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.CFC – Continuous Function Chart (Non-IEC)  CFC is an additional language provided within TwinCAT.     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. Each function starts new each PLC scan. SIN.13. 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. the name of the Function starts with F_ The same IEC rules for naming of variables apply to the naming of Functions Following the Name of the Function is the Return Type  A Function can only Return one variable 83 Chapter: PLC Overview . OR. GT. LE are all examples of Functions The programmer can also create their own Functions that normally involve more complicated tasks. SQRT. COS. 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. Functions  A Function is a re-useable piece of code that will process the defined inputs and return a single result AND.  The Variables to be passed into the Function  In the below example iTempInCelsius is the Variable that is being passed into the function 84 Chapter: PLC Overview . 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. this does cause inaccuracy due to rounding.)   85 Chapter: PLC Overview .Code  The working code of the Function   Tf := 9/5 * Tc + 32 In the example code the integer value iTempInCelsius is converted to a real number. (Yes. Before writing the calculated value to the output the number is converted back to an integer. The result of the Function is then stored in iTempF. 86 Chapter: PLC Overview .Implementation     iTempC is declared as an INT with an initial value of 100 iTempF is declared as an INT with no initial value In the code the Function F_CtoF is called and iTempC is passed into it. FB_FileOpen. Function Blocks  A Function Block is a re-useable piece of code that can have multiple inputs and outputs. Just because you can doesn’t mean you should. all of which must be handled by the programmer. Note: It is possible to call a Program from a Function Block. Each instance receives its own space in memory and therefore will retain its values from one PLC scan to the next. TON. Function Blocks can all other Function Blocks and Functions. CTU.     87 Chapter: PLC Overview . therefore each time a Function Block is used it must be assigned a unique instance name. Function Blocks are instantiated.14. Function Blocks can be called by Programs or other Function Blocks. once you understand the inner workings of the software you will understand why doing this can cause problems. TwinCAT provides you with the flexibility to do many things (some good. ADSREAD. are just a few examples of Function Blocks The programmer can also create their own Function Blocks to perform a variety of tasks. R_Trig. some not so good). Declaration       The Declaration of a Function Block contains 4 parts The Name of the Function Block The Variables to be passed into the Function Block The Variables to be passed out of the Function Block The Variables that are internal to the Function Block The Name of the Function Block  Following the Beckhoff coding convention. the name of the Function Block starts with FB_ The same IEC rules for naming of variables apply to the naming of Function Blocks  88 Chapter: PLC Overview . and Time Off values are being passed into the Function Block 89 Chapter: PLC Overview . Time On.  The Variables to be passed into the Function Block Below the Enable.   The Variables to be passed out of the Function Block Below the Output variable has been added 90 Chapter: PLC Overview .     The Variables that are internal to the Function Block Below the two timers to be used have been instantiated fbTON is of type TON fbTOF is of type TOF 91 Chapter: PLC Overview . Code    The working Code of the Function Block Below the two timers are called with their instance name The := symbol signifies that a value of the variable is being passed into the FB and the => symbol signifies that a value of the variable is being passed out of the FB 92 Chapter: PLC Overview . Q is an output of a TOF. therefore calling the instance name fbTOF followed by ‘.’ will allow access to the variables that are declared inside of fbTOF  93 Chapter: PLC Overview .Q is FALSE What is fbTOF.Q? Anytime the ‘.   The IN of fbTON is TRUE if bEnable is TRUE and fbTOF.’ symbol is used it signifies that the variable on the right exists inside of the variable on the left. bPulse is the output of FB_Pulse This could have been done with the following  bPulse := fbTOF.Q. 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.Q is passed into fbTOF. Also notice that fbTON.   94 Chapter: PLC Overview . Implementation      fbPulse1 is of type FB_Pulse fbPulse1 is an instance of FB_Pulse bSwitch is passed into the bEnable input of fbPulse1 tTimeOn and tTimeOff are assigned literal values in the proper TIME format bPulse is passed out of fbPulse1 into bLight1 fbPulse2 is a second instance of FB_Pulse. In the above example of fbPulse2 the input variables are first assigned. 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. followed by a call of the Function Block instance on line 6. 95 Chapter: PLC Overview . It is coded differently but works exactly the same. This is extremely important to understand. if line 6 was removed from the code then the Function Block would never run. A_Enable is called from the code of MAIN. 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. To add an Action to a POU. Both Programs and Function Blocks can use Actions (They are not allowed with Functions). Actions Actions are used to organize code.15. but is declared locally in MAIN 96 Chapter: PLC Overview . The instance of fbMC_Power_Ax1 is called inside of the action A_Enable. Actions share their local declaration section with the POU they are attached to. the scaling parameters.16. and the offset are all possible elements that are directly related to the temperature sensor In order to keep these elements together and make the code more re-useable a structure of these elements can be created    Declaration    The structure is created with its element names and data types Initial values can be given A structure can also contain other structures 97 Chapter: PLC Overview . for example. is more than just the temperature value The status of the Analog input card. Structures  Structures are used to define elements of a larger item and are commonly referred to as custom data types A temperature sensor. Implementation   A structure must be instantiated just like a Function Block After typing the instance name of the structure place a ‘. showing what elements exist inside of the structure  The elements in a structure can be written to and/or read from 98 Chapter: PLC Overview .’ immediately after it and the intellisense window will appear. with or without being instantiated.17. Enumerations     Enumerations can be used to assign a variable name to a number. Enumerations can be used in two different ways. 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. If the Enumeration is not instantiated then the Enumeration works similar to a list of constants. the variables following will be assigned their values in ascending order Manual = 0 Semi_Auto = 1 Auto = 2      If a variable in the list is explicitly assigned a value then the following variables will be incremented from this value Manual = 1 Semi_Auto = 2 Auto = 3    99 Chapter: PLC Overview . As iStep1 changes in value the Case statement will change states iStep1 can be assigned a numerical value or an Enumeration variable The displayed online value of iStep1 will always be an INT value because iStep1 is declared as an INT     100 Chapter: PLC Overview .     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. ‘Semi_Auto’. or ‘Auto’  101 Chapter: PLC Overview . If an instance of the Enumeration is declared then the instance of the Enumeration holds the variable name of the value of the Enumeration If iStep2 is of type E_Mode then iStep2 holds either ‘Manual’. the data in the Array can be of any type An Array can contain more than one dimension Think of a notebook of graph paper The column on a single sheet of paper would be a 1 dimensional array The entire sheet with its rows and columns would be a 2 dimensional array The notebook with all of its sheets would be a 3 dimensional array 1 Dimensional Array   The Array is defined from 1 to 10 of type INT This Array will hold 10 integer values   The position in the Array is referred to as the index The Array name along with an index can be used just like any other variable 102 Chapter: PLC Overview .18. Arrays       An Array is a list of data. 2 Dimensional Array    The Array is defined from 1 to 10 and 1 to 3 of type String This Array will hold 30 (3*10) String values The comma ‘.’ is used to denote the multiple dimensions of the array 3 Dimensional Array 103 Chapter: PLC Overview .  Initializing each index of an array   Initializing multiple indexes with the same value 2(3) indicates that the first 2 Indexes will be given a value of 3  The above 2 examples can be mixed together 104 Chapter: PLC Overview .    Indexing through an Array with a FOR loop A FOR loop can be used to easily fill an Array or read the values in an array The following will set all values in the Array to 0 105 Chapter: PLC Overview . The Boot Project must be enabled and also created.19.  Enabling    Enabling the Boot Project is done through the TwinCAT System Service Right Click on the TwinCAT icon in the Windows system tray and select properties Click on the PLC tab and place a check mark in the Run-Time 106 Chapter: PLC Overview . Boot Project  The TwinCAT Boot Project is used on a production machine as the PLC code to be run when TwinCAT starts. Creation  To create the Boot Project: login with the PLC and select ‘Create Boot Project’ from the ‘Online’ menu 107 Chapter: PLC Overview . To create the Source Code Download file you must be logged in to the PLC From the ‘Online’ menu select ‘Sourcecode Download’   108 Chapter: PLC Overview . This copy of the code can be opened later either directly on the PC or through a remote connection.20. Source code Download   The use of the Source Code Download allows for a copy of the code to be placed on the device. wbp where x will be a number from 1 to 4 which represents the runtime number. Select Open from the File Menu  On the Open file dialog select the ‘PLC’ button 109 Chapter: PLC Overview .  The Source Code file will be created in the C:\TwinCAT\Boot folder The name of the file will be TCPLC_S_x.  To open the Source Code Download file.  Select the correct Target System Type  Select the Run-Time on the Target 110 Chapter: PLC Overview .    The files will be copied in to your local Upload folder C:\TwinCAT\PLC\Upload If any of the files already exist you will be asked if you would to overwrite these files  The code will then open  If the source code download has not been performed you will get the following error message 111 Chapter: PLC Overview . use the following steps when making changes to a PLC program to ensure the best results.     You will also see in the bottom right corner of the PLC Control the current status of the PLC 112 Chapter: PLC Overview .        Verify PLC program file matches running code Edit Code Compile Code Load Changes Save File Create Boot project Perform a Source Code Download Verify the PLC Program  To ensure the correct version of the code is being edited you should first verify the PLC Program file matches the PLC Code that is running in TwinCAT. then you can be certain that the code matches exactly.21. Code Changes To make changes on an existing system. Open the file From the ‘Online’ menu select ‘Login’ If the PLC Program goes online without prompt. If you accidentally press it.       ‘Online Change’ Notice at the end of the question you are notified that this will be an (ONLINE CHANGE) Yes – This will perform the ‘Online Change’ described in more detail on next page No – Don’t use this option. if you receive a prompt. When logging in to the PLC. simply Log Out of the PLC Cancel – Cancels the operation Load all – Stops the execution of the PLC and Loads all of the Code including the changes. and the available options. Online Change  The following is a description of the internal process for an Online Change that is only suitable for your understanding.   113 Chapter: PLC Overview . pay close attention to the question being asked. The actual process is much more intricate and complicated Imagine the below represents the RAM of the Computer and the programs that are currently using it The PLC Code runs from the first line to the last line and then repeats. The PLC must be started again. to be used by another process 114 Chapter: PLC Overview .   When an Online Change is performed The New PLC Code is loaded into a separate memory location When the current scan of the PLC Code has completed.  The New code is now repeated each PLC Scan and the memory where the old code was located is released. instead of looping back around. The PLC will start running the New PLC Code on the next scan. In both situations the first choice should be to look for another copy of the program. Online Change 3. It simply asks if you would like to ‘Download the new program?’ Yes – Will stop the PLC and load the code. An ‘Online Change’ is required for many things. The PLC logged in without prompt 2. If you accidentally press it.Don’t use this option. Anything from adding a variable to changing the value of a timer.    115 Chapter: PLC Overview .Load Changes  The other possible option when logging in to the PLC is that the code is different enough that the PLC is not able to do an ‘Online Change’ In the below prompt notice that it does not say Online Change. simply Log Out of the PLC Cancel – Cancels the operation        At this point we are still trying to verify that we have the correct version of the PLC program One of 3 possibilities have happened 1. No . Download the Program  If you are able to Login without a prompt then you can go to the next section about Editing the Code If an Online Change or a Download of the Program is required then a couple of things need to be considered. The PLC must be started after this. pro file) then a ‘Download’ of the program will be required. then an ‘Online Change’ will be required to Login. then press the ‘F3’ key In the Search Box type in *. if the auxiliary files for the PLC Project do not exist (someone emailed only the .wbp for the first PLC Run-Time To open this file. However. A ‘Download’ will be required if the computer has been restarted and the Boot Project was not updated.pro file on the hard drive. Locating the PLC Project can be done by searching for the . then select ‘Open’ from the ‘File’ menu  116 Chapter: PLC Overview . Also. but the PLC Program was closed without saving the change. If a change was made.pro and press the ‘Enter’ key       Depending on the size of the hard drive this might take a few minutes Source Code Download File   The last option is to open the Source Code Download file When created this file is saved in the C:\TwinCAT\Boot directory as TCPLC_S_1. open the PLC Control. Press the ‘Start’ button or the Windows key on the keyboard. this will be loading the older version of the code. select the ‘PLC’ button  Select the CPU type. In the Open File Dialog window. and click ‘OK’ 117 Chapter: PLC Overview . all’   If the file exists it will be opened If this file has been kept up to date and matches with the PLC Code that is running inside of TwinCAT.  118 Chapter: PLC Overview . then you should be able to Login with this Code. and click ‘OK’  Click ‘Yes. Select Run-Time1. If it does not match exactly then you will have to perform either an ‘Online Change’ or a complete ‘Download’ of the PLC Program. we can make the required changes.Edit the Code  Now the we have a program that matches with the running code. We will start with a simple Ladder program that needs a contact changed from ‘Normally Open’ to ‘Normally Closed’   Left-Click on the symbol of the Contact to select it. Notice the dotted selection box around the symbol Hold the ‘Ctrl’ key and press ‘N’ This will ‘Negate’ or invert the Contact This same command will work for changing a NC contact to NO    119 Chapter: PLC Overview . In FBD the location of the cursor is extremely important The options in the context menu will change based on the location of the cursor Chapter: PLC Overview    120 . It is also possible to Right-Click on a symbol and select one of the options from the context menu When making changes to code in FBD (Function Block Diagram) the same steps apply.   Cursor inside the box Changes here effect the box itself   Cursor on the input of the box Changes here are for the way the input interacts with the box 121 Chapter: PLC Overview . typically an Assignment to another variable or another box   Cursor on the Assignment Changes here will affect the specific output or add more outputs 122 Chapter: PLC Overview .  Cursor on the right side of the box Changes here effect what will be to the right of the box. it is time to Compile the code and check for errors. From the ‘Project’ menu select ‘Build’ This will compile the code In the message window you should see    If you have any warnings they can typically be ignored. If you have an error. your ‘Retain Data’ will be initialized. press the ‘F4’ key  The ‘F4’ key will take you to the location of the first error in the message window and also open the code to the location where the error was found. Note: If you use the ‘Rebuild All’ command. 123 Chapter: PLC Overview .Compile Code     Once the changes have been made. (End of Line) or an := (Assignment). After the variable c the compiler is expecting to find a . The reason for this is that the compiler ignores spaces. Most of the time 1 problem will cause multiple error messages. is missing from the end of the line The error message says the problem is on Line 3. The problem with the below line of code is that the . It doesn’t find it so it continues to line 2 and then line 3 Line 3 is the last line of code so this is where the compiler is at when the error is detected      The second error is caused by the first error When the first error is corrected the second error will no longer exist 124 Chapter: PLC Overview . Sometimes error messages can be misleading. select ‘Login’  Click ‘Yes’ to perform an ‘Online Change’   If additional changes need to be made First ‘Logout’ of the PLC and then repeat the process 125 Chapter: PLC Overview .Load Changes   Once all of the errors have been corrected. the changes can be loaded into the PLC From the ‘Online’ menu. select ‘Create Boot Project’ If a new Boot Project is not created.    126 Chapter: PLC Overview . From the ‘Online’ menu. the old Boot Project will be loaded. If this happens then a ‘Download’ of the program will be required before you can log in again. It is extremely important that the ‘Boot Project’ be kept up to date and match the PLC Program. select ‘Save’ This will replace the existing file on the hard drive with the current file and the changes Boot Project  Once all changes have been made.Save File    When you are done making changes the new File should be saved From the ‘File’ menu. then the next time that TwinCAT is restarted or the computer is rebooted. and before restarting TwinCAT a new ‘Boot Project’ must be created. select ‘Options’ In the left column select ‘Source download’ 127 Chapter: PLC Overview . and matches the ‘Boot Project’ then this file can also be used to ‘Login’ to the PLC This file is also useful for keeping a copy of the code on a CX device that only has the TwinCAT Run-Time and not the full development  Options   From the ‘Project’ menu.Source Code Download    From the ‘Online’ menu select ‘Sourcecode Download’ This will create a file in the C:\TwinCAT\Boot directory that can be opened later If this file is kept up to date.  Implicit at load  Create a new source code download file every time a change is loaded  Notice at load  Every time a change is loaded. ask the user if they would like to create a new source code download  Implicit on create boot project   Each time a new boot project is created. also create an new source code download Note: If this option is selected then the source code download and the boot project will always match  Only on demand  The source code download command must be manually given from the ‘Online’ menu 128 Chapter: PLC Overview .   How much data should be placed in the file All Files   This will place everything inside the file. then this is the best option  Source code only  This will only place the code and other auxiliary files needed for logging in to the PLC on the hard drive  Source code only(exclude compile info)   Only the code A download must be performed to login to the PLC 129 Chapter: PLC Overview . including all bitmaps for any visualizations If you have enough room on the hard drive. Maintenance: Used for making adjustments to the machine or for troubleshooting individual components. 130 Chapter: PLC Programming “The Inspection Conveyor” . This State will be used when the machine is first powered on and when a problem in the PLC code occurs.V. PLC Programming “The Inspection Conveyor” 22. Access to this mode will be restricted. Operations will be allowed in this State that could be harmful to the equipment. Machine Control/State Machine There are many ways to do overall machine control and to implement a state machine. Next an analog output will be added to control the conveyor speed using a Variable Frequency Drive (VFD). Manual: Used to start up the machine and prepare for operation. As the saying goes “Prior proper planning. The second module will use an analog input to measure the size of the product. With each module a new concept and/or topic will be introduced. This State is not allowed to be set by the operator. The machine will process product based on the conditions of the I/O with minimal operator intervention. both of which are outside the scope of this document. The machine will have the following States: Undefined: When no State is defined by the PLC this will be the default State. The first conveyor module will be for adding product to the system using only digital Inputs and Outputs. The overall machine control will be handled in a CASE statement. 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. prevents poor performance”. Machine Control with Top-Down Programming Intro This section is going to cover the design and programming of a modular conveyor. Automatic: Used for routine production. Requires operator intervention for all functions of the machine. 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. or to shut down the machine after Automatic operation. 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. including information about the previous and following module.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. if multiples of a module are needed they can be easily instantiated. Module data Structure: contains information about the configuration of the module. Additionally. therefore. standard data Structures for all conveyor modules will be used by each of the Function Blocks to aid in communication between modules. Creating the program Open the PLC Control by selecting the TwinCAT icon in the Windows System Tray and the select PLC Control 131 Chapter: PLC Programming “The Inspection Conveyor” . Machine data Structure: contains status information for the overall machine including the current State. From the ‘File’ menu. then click on ‘OK’ 132 Chapter: PLC Programming “The Inspection Conveyor” . select ‘PC or CX (x86). select ‘New’ For most of this project we will not be connecting to hardware. Note: The TwinCAT 2 Run-Time is only available on Windows 32-bit Operating Systems In the ‘Choose Target System Type’ window. Therefore everything will run in simulation on the computer you are using. 133 Chapter: PLC Programming “The Inspection Conveyor” . This will allow the programmer to easily call other programs and also easily comment out large parts of the program. if not impossible. it is my recommendation that when starting a new project the MAIN program should always be done in ST. 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.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. This is the smallest program you can write.You should now have the following Place a semicolon on Line 1 of MAIN. 134 Chapter: PLC Programming “The Inspection Conveyor” . From the ‘Project Menu’. select ‘Rebuild All’ 135 Chapter: PLC Programming “The Inspection Conveyor” . In the ‘Message Window’ at the bottom. The Warning is because we have not saved the file with a name. 136 Chapter: PLC Programming “The Inspection Conveyor” . you should receive 0 Errors and 1 Warning. 137 Chapter: PLC Programming “The Inspection Conveyor” . select ‘Save As’ The file can be saved anywhere you would like. I would recommend that you use the same file name that I have used.From the ‘File Menu’. 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. I would recommend against saving it on the desktop. Give your project a name and press the ‘Save’ button. Adding a version number to your project name is an easy way to have multiple versions of the program. Select the ‘Resources’ tab at the bottom of the left column 138 Chapter: PLC Programming “The Inspection Conveyor” . so that you can go back to a previous version later on. You will now see that the file name of the project is placed across the top of the PLC Control Before writing any real code we will first declare all known variables that will later be connected to hardware. select ‘Add Object’ 139 Chapter: PLC Programming “The Inspection Conveyor” . The ‘Global_Variables’ list is included by default. The ‘Global_Variables’ and the ‘Variable_Configuration’ The ‘Variable_Configuration’ list is only used for the BC line of controllers. Right Click on the ‘Global Variables’ folder. we are going to start by creating a couple of Global Variable Lists. Therefore. however. on large machines it is good practice to create multiple lists to help organize the variables into smaller more manageable lists.Expand the ‘Global Variables’ folder by clicking on the + sign In the ‘Global Variables’ folder there are two lists by default. or the name has already been used the ‘OK’ button will be grayed out. Place the cursor at the end of line 1 and press the enter key a couple of times. Double-Click on ‘Global_Variables_IO’ This will open the Global Variable list. 140 Chapter: PLC Programming “The Inspection Conveyor” . the same as variable names.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. If it does not. When the switch is in the ‘Manual’ position the input will be off. All comments will turn green. Comments can be added to the code by placing (* at the beginning of the comment.Between the key words ‘VAR_GLOBAL’ and ‘END_VAR’ is where we will declare our variables. and *) at the end of the comment. gati_xMan_Auto_SS will be a two position Selector Switch between Manual and Auto. Note: Please refer to Appendix I “Variable Naming Convention” for a better understanding of the variable names used throughout this project. when the hardware detects 0 Volts DC the PLC will represent this with FALSE. therefore when the hardware detects 24 Volts DC the PLC will represent this with TRUE. gati_xMaintenance will be a push button to request the State Machine to go into ‘Maintenance’ gati_xReset will be a push button for resetting faults 141 Chapter: PLC Programming “The Inspection Conveyor” . when the switch is in the ‘Auto’ position the input will be on. (*Machine Control*) The following will be Boolean inputs of type BOOL. thereby applying 24 Volts DC to the output and turning on the light. thereby applying 24 Volts DC to the output and turning on the light. gatq_xFaultLight will be written with a value of TRUE when the machine is Faulted. thereby applying 24 Volts DC to the output and turning on the light. gatq_xManualLight will be written with a value of TRUE when the machine is in Manual. thereby applying 24 Volts DC to the output and turning on the light.(*Stack Lights*) The use of Stack Lights allows everyone in the area of the machine to easily know the status of the machine. ‘Green’. ‘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. The definitions of what the colors represent vary between industries and countries. 142 Chapter: PLC Programming “The Inspection Conveyor” . 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’. gatq_xMaintenanceLight will be written with a value of TRUE when the machine is in Maintenance. and ‘Blue’ only one of the can be on at any given time. Select the ‘Data Types’ tab at the bottom of the left column 143 Chapter: PLC Programming “The Inspection Conveyor” .Next we will create an Enumeration that will be used to represent the possible States of the State Machine. Right-Click on the ‘Data Types’ folder and select ‘Add Object’ Type in ‘E_MachineState’ as the ‘Name of the new data type’. and click ‘OK’ You should now have the following 144 Chapter: PLC Programming “The Inspection Conveyor” . 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. The variables of the Enumeration must be placed between ( and ) and each one separated by a comma ‘.Data Types always default to a ‘STRUCT’.’. each value after that will be incremented by one. 145 Chapter: PLC Programming “The Inspection Conveyor” . The asterisk is there to indicate that changes have been made but not saved. Or simply press and hold the ‘Ctrl’ key and the press the ‘S’ key. To check the Enumeration and the Global Variables for any possible typing errors go to the ‘Project’ menu. When preforming a ‘Rebuild All’ this generates 2 errors. Notice that the asterisk * and the end of the file name disappears. and select ‘Rebuild All’ If you have any errors. they should be fixed before moving on. From the ‘File’ menu. As an example I have removed the semicolon from the end of one of the Global Variable declarations.Now would be a good time to save the changes that have been made. select ‘Save’. which can be seen in the ‘Message Window’ 146 Chapter: PLC Programming “The Inspection Conveyor” . 147 Chapter: PLC Programming “The Inspection Conveyor” .Place your mouse at the top of the ‘Message Window’ Click and Drag the bar upwards to see more of the ‘Message Window’ It is best to start with the first error in the list. many times one problem will create others for the compiler. Repeatedly pressing ‘F4’ will go to the next error in the list. The easiest way to find the first error in the list is to press the ‘F4’ key. You could also scroll through the error list and Double-Click on the error. and the line of code that has the problem will be highlighted. preform another ‘Rebuild All’ from the ‘Project’ menu. The warning simply states that the VAR_CONFIG file has not been created for these variables. ‘F4’ will scroll through the warnings. The full error message states that the complier is ‘Expecting the end of line character or an assignment before seeing a new variable name. 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. Ignore them for now and continue on. Generally speaking warnings can be ignored. 148 Chapter: PLC Programming “The Inspection Conveyor” . These 7 warnings are created by the use of %I* and %Q* variables. After fixing any errors you may have had. the location of the error will be shown. Now would be a good time to ‘Save’ your project. To the compiler the problem occurred on line 9. you will get 7 warnings. Once.When the error is selected. you have zero errors. Repeatedly pressing ‘F4’ will go to the next error in the list. it is time to write some code.Finally. 149 Chapter: PLC Programming “The Inspection Conveyor” . Click on the POUs tab at the bottom of the left column. then place a colon after it. Chapter: PLC Programming “The Inspection Conveyor” 150 . then press the F2 key which opens the Input assistant.Double-Click on the MAIN program. 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. This blue arrow simply indicates that changes have been made to this POU that have not been downloaded into the running PLC. Note: You may or may not have the small blue arrow next to the icon for MAIN. 151 Chapter: PLC Programming “The Inspection Conveyor” . place a semicolon at the end of the line. press ‘OK’ This will bring you back to the declaration section.Select ‘User defined Types’ from the left column and then E_MachineState. 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. Therefore when iStep is equal to 0 the code between 0 and the next number will be run. The value of iStep is set by conditions in the PLC code.USINT). Enumerations hold an integer value. 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. The value can be changed from within the CASE statement or from outside the CASE statement. therefore the need for skipping numbers is not necessary. The values of the condition variable are limited to integer values. For our project the Enumeration is declared as having 4 possible values. However the ELSE command should always be included. values are skipped to allow for the possibility to easily add steps in between. otherwise when a step has to be added then all following steps must be changed.The general layout of a CASE statement is as follows: The variable between CASE and OF must use an integer value (INT. In the above picture. if iStep is ever set to a value that is not defined the code in the ELSE command will be run. The numbers that follow on the next lines represent the possible values of that variable. The code following all other numbers will not be run. Chapter: PLC Programming “The Inspection Conveyor” 152 .DINT. It is generally a good practice to do this.SINT. or the first line after the END_CASE command. The ELSE case is a safeguard. double-click on the variable eStep in the declaration section of MAIN. an initial value will be placed on the variable eStep. however. This will highlight the variable name 153 Chapter: PLC Programming “The Inspection Conveyor” . By default when the PLC starts all values are 0. To ensure that our state machine starts at zero.Note: when using an Enumeration both of the above are valid. unless given an initial value. the use of the variable name from within the Enumeration makes the code easier to read. To do this. and click ‘OK’ The declaration of eStep now has an initial value of 0. The ‘Declare Variable’ window will open Place a zero in the ‘Initial Value’ box. Chapter: PLC Programming “The Inspection Conveyor” 154 . 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. The first thing we will setup is the control of the value of eStep.Press and hold the ‘Shift’ key then press ‘F2’. Remember to use ‘F2’ for the Input Assistant to select gati_xMan_Auto_ss from the Global Variables 155 Chapter: PLC Programming “The Inspection Conveyor” . The input is negated with the NOT command because the switch being in the ON position is for Auto. we should also look at the condition of the Selector Switch.However. We now are able to put the machine into Manual Operation. From Manual. Go to the ‘Project’ Menu and select ‘Rebuild All’ Chapter: PLC Programming “The Inspection Conveyor” You should get one error. 156 . Now would be a good time to ‘Save’ your project. It would also be a good time to check for errors. Press ‘F4’ to go to the error. there needs to be a way to go into either Maintenance or Auto. You will also need to do this after E_Auto and ELSE If you have any other errors. but if you forget it won’t hurt anything. When the complier sees two values for eStep with no code in between them it causes an error. It should be removed later. The easy way to avoid this is to place a semicolon after the colon. 157 Chapter: PLC Programming “The Inspection Conveyor” .Each value for the CASE statement must have some code in it. please address them before moving on. Currently it is possible to get into the Auto state but it is not possible to get out of it. This is the same code that was used to go from E_Undefined to E_Manual. 158 Chapter: PLC Programming “The Inspection Conveyor” . pressing the Maintenance push button will place the machine back into Manual. In the ELSE command eStep will be set to E_Undefined.As the programmer it is your duty to ensure that all possible conditions are accounted for. From the Maintenance mode. The selector switch will place the machine into the Manual state. The entire body of MAIN. and save your project. Each function block will be capable of controlling the conveyor module in each possible machine state. Later in the section on ‘Fault Handling’ we will add to the state machine for what needs to be done when a fault occurs. 159 Chapter: PLC Programming “The Inspection Conveyor” . now looks like the following Now would be a good time to check for errors using ‘Rebuild All’ from the ‘Project’ menu. The plan is to have a function block for each conveyor module. At this point the control for the state machine is finished. Before creating the function blocks. Therefore the machine state will be passed into the function block. we will create the code that is going to call the function blocks. Name the POU ‘P_MachineControl’. Leave the Type as a Program and set the Language to ‘ST’ for Structured Text.In the ‘POU’ column right click and select ‘Add Object’. Then click on ‘OK’ 160 Chapter: PLC Programming “The Inspection Conveyor” . 161 Chapter: PLC Programming “The Inspection Conveyor” In the ‘Input Assistant’ select ‘User defined Programs’ from the column on the left. The open and close parenthesis are not required but should be used to indicate that it is a POU call. Below the code for the CASE statement. . then press ‘OK’. This will call the new program every PLC scan. select ‘P_MachineControl’ from the window on the right. Double-click on ‘MAIN’ to open it. place the cursor and press ‘F2’.Before writing any code in the new program we should call the program from ‘MAIN’. Later we will add code to this program for calling the Function Blocks that will control the machine. 162 Chapter: PLC Programming “The Inspection Conveyor” . For now add a semicolon to prevent any build errors. to monitor things going on in the background. 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. Next.Now double-click on ‘P_MachineControl’ in the ‘POU’ column. triggers. 163 Chapter: PLC Programming “The Inspection Conveyor” . The Standard library contains timers. select ‘Library Manager’. From the ‘Window’ menu. The STANDARD. and other basic function blocks.Lib is always included in every project by default. counters.First we will add the new 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.Under the ‘STANDARD.Lib’ right click and select ‘Additional Library’. 164 Chapter: PLC Programming “The Inspection Conveyor” . After selecting ‘TcUtilities. if you choose to type in the name.lib’ by either scrolling to the right or typing the name into the ‘File name:’ box.lib’ press the ‘Open’ button. therefore these libraries are included as well.Add the ‘TcUtilities. you will notice that windows filters the results of possible options as you type. Chapter: PLC Programming “The Inspection Conveyor” 165 . TcUtilities requires the use of TcBase and TcSystem. This will display a picture of the Function Block as it would appear in the FBD language.Select TcUtilities in the list of libraries. 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. Notice that libraries can contain POUs. Visualizations. and Global Variables. it also displays part of the local variable declaration section for the Function Block. Chapter: PLC Programming “The Inspection Conveyor” 166 . In the POU column of the TcUtilities library expand the ‘TwinCAT System’ folder and select TC_CpuUsage. Data Types. In the POU column double click on ‘P_MachineMonitoring’. Chapter: PLC Programming “The Inspection Conveyor” Now place the cursor on line 0001 in the code window and press ‘F2’ to open the ‘Input Assistant’ 167 .The Tc_CpuUsage Function Block will monitor the percentage of the CPU that TwinCAT is using. Scroll down to ‘TwinCAT System’ and expand that folder 168 Chapter: PLC Programming “The Inspection Conveyor” .From the ‘Input Assistant’ select ‘Standard Function Blocks’ from the left column and then expand TcUtilities in the window on the right. Select ‘Tc_CpuUsage’ and click ‘OK’. This will add a generic version of the Function Block to the code. 169 Chapter: PLC Programming “The Inspection Conveyor” . When using large function blocks in Structured Text the variables are each placed on their own line to make them easier to view. The assignment statement := is used to indicate that the variable is of type VAR_INPUT. When you click on any line other than line 1 the ‘Declare Variable’ window will appear. leave this on VAR to declare it in the local variable declaration section. Each variable is followed by either an input or output symbol and then a comma. everything between the open and close parenthesis are variables that are defined inside of the Function Block. 170 Chapter: PLC Programming “The Inspection Conveyor” . Add ‘fb’ to the beginning of the implementation name TC_CpuUsage.The name on line 1 is the ‘Implementation’ name of the Function Block’. Each use of a Function Block will receive its own memory space. therefore. the output assignment => is used to indicate that the variable is of type VAR_OUTPUT. The ‘Class’ drop down list will allow for the selection of where the variable is to be declared. each Function Block must be given a unique instance name. Change the ‘Type’ from BOOL to TC_CpuUsage, this can be done by either typing in the type or pressing the ‘Ellipse’ button. When you press the ‘Ellipse’ button the ‘Input Assistant’ will open and allow you to select the type from the list. Select ‘Standard Function Blocks’ from the column on the left, then expand ‘TcUtilites’, then ‘TwinCAT System’, finally select TC_CpuUsage and click ‘OK’. 171 Chapter: PLC Programming “The Inspection Conveyor” The ‘Declare Variable” window should look like the following. Press ‘OK’, and notice that the instance of the Function Block has been declared in the local variable section. Next the variables to be passed into the Function Block need to be added. The ‘NETID’ is the AMSNETID of the TwinCAT Run-Time that is to be read. According to the Documentation the variable type is ‘T_AmsNetID’, which is of type string with a length of 23 bytes. 172 Chapter: PLC Programming “The Inspection Conveyor” In this example we are going to read the local CPU Usage, therefore the local AmsNetID can be provided. Click on your TwinCAT Icon in the windows system tray, the select ‘Properties’. Select the ‘AMS Router’ tab The AMS Net ID can be copied from here. 173 Chapter: PLC Programming “The Inspection Conveyor” In the code place an empty string after the assignment statement of NETID, then paste the AMS Net ID in between the quotes. When using the local AMS Net ID it is also possible to just use an empty string ‘’, internally the Function Block will read the local AMS Net ID in this case. When the ‘START’ input variable rises from False to True, internally the Function Block will execute an ADSREAD one time. Each rising edge that is seen on the ‘START’ input will cause another read of the CPU usage. For now add the variable ‘xReadCpuUsage’ to the ‘START’ input. 174 Chapter: PLC Programming “The Inspection Conveyor” When you click away from line 3 the ‘Declare Variable’ window will appear. Leave it defined as a Local variable and a BOOL. The ‘TMOUT’ variable is the amount of time to wait for a response, before throwing a TimeOut error. If the input is left empty the default time of 5 seconds will be used. Time values always start with T# and must end with time unit being used. Place a time value of 500 milliseconds in the ‘TMOUT’ variable. We will now create local variables that the Function Block will write to. 175 Chapter: PLC Programming “The Inspection Conveyor” Use the following variable names for the outputs and declare them as shown below. Now would be a good time to compile the code and check for errors, by selecting ‘Rebuild all’ from the ‘Project’ menu. When there are no errors, save your project. A commonly used Function Block is NT_GetTime. This Function Block will read the Windows Clock each time the ‘START’ input is triggered. The time value can then be added to log information. 176 Chapter: PLC Programming “The Inspection Conveyor” Place the cursor on line 11 and press ‘F2’. Select ‘Standard Function Blocks’ from the left column, expand the ‘NT, W2K, XP, XPe, CE Operating System’ folder. 177 Chapter: PLC Programming “The Inspection Conveyor” Select the NT_GetTime Function Block and press ‘OK’ The generic Function Block has now been added to the code. 178 Chapter: PLC Programming “The Inspection Conveyor” (Two single quotes. Click away from line 11 and declare the Function Block as a type NT_GetTime.Change the name to fbNT_GetTime. 179 Chapter: PLC Programming “The Inspection Conveyor” Set the NETID to local by using an empty string. with no space between them. . and contains the following information. .Set the ‘START’ variable to xGetTimeStart and declare it as ‘Type’ BOOL. Set the ‘TMOUT’ to 500ms. This structure is defined inside of the TcUtilities library. Set the output variables and declare them as they are below. The local declaration section should have the following 180 Chapter: PLC Programming “The Inspection Conveyor” Notice that ‘stGetTimeValue’ is of Type ‘TIMESTRUCT’. wDayOfWeek : Specifies the day of the week: 0 ~ 6 (Sunday = 0. 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. Monday = 1 and so on ). wHour : Specifies the hour: 0 ~ 23. wMonth : Specifies the month: 1 ~ 12 (January = 1.wYear : Specifies the year: 1970 ~ 2106. The out ‘stGetTimeValue’ will hold values similar to the following. 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’ 181 Chapter: PLC Programming “The Inspection Conveyor” The previous two Function Blocks were provided by Beckhoff. wSecond : Specifies the second: 0 ~ 59. wDay : Specifies the day of the month: 1 ~ 31. wMinute : Specifies the minute: 0 ~ 59. . wMilliseconds : Specifies the millisecond: 0 ~ 999. February = 2 and so on). 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 VAR section will declare values that are only used internally within the Function Block. name the POU ‘FB_Pulse’. the name of the Function Block is also included on this line. In the VAR_INPUT section variables will be declared that have values passed into them from the calling code.In the ‘New POU’ window. The Type of POU should be ‘Function Block’. 182 Chapter: PLC Programming “The Inspection Conveyor” . The language will be ‘ST’ for structured text. the VAR_OUPUT section will declare variables that have their values passed out to the calling code. and VAR sections. Following line 1 is the VAR_INPUT. VAR_OUTPUT. They are in the STANDARD library.In the VAR_INPUT section declare the following variables i_xEnable :BOOL. . In the VAR_OUTPUT section declare the following variable q_xPulse : BOOL. In the VAR section declare the following variables 183 Chapter: PLC Programming “The Inspection Conveyor” These are the two timers that will be used to control the output. i_tTimeOff : TIME. (*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. In the code. window use ‘F2’ to place the two timers in the Function Block. 184 Chapter: PLC Programming “The Inspection Conveyor” . Chapter: PLC Programming “The Inspection Conveyor” The TON will start when the i_xEnable input is TRUE and the TOF output is FALSE. The i_xEnable variable can be added by placing the cursor between the := and the . 185 .Now change the name of the TON and TOF to match the declaration section. and Purple icons are for VAR. in the left column of the Input Assistant select ‘Local Variables’. add the code to monitor the output of fbTOF If you type in the code. then select i_xEnable from the right window. Yellow icons are for VAR_INPUT. Red icons indicate VAR_OUTPUT. Next. ) after fbTOF a drop list will appear that contains all of the variables declared inside of the TOF. notice that once you have added the dot ( . 186 Chapter: PLC Programming “The Inspection Conveyor” .Then press ‘F2’. use ‘F2’ and select the variable from the ‘Local Variable’ list. After pressing the . press the ‘i’ key. ) key This list includes every variable in the project. instead place the cursor after the := and before thecomma ( . If you use the arrow keys.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. You code should now look like the following Next. ) Now press the dot ( . 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. 187 Chapter: PLC Programming “The Inspection Conveyor” . both the ENTER key and the space bar will select the variable and add it to the code. add the TIME variable to PT:= Note: this is the tTimeOff variable Again. The input for fbTOF will be the output of fbTON This time to add the i_tTimeOn variable do not use the ‘F2’ key. when selecting an output the .Pressing the down arrow will show the next variable in the list. . must be removed or the compiler will throw an error. is not removed as it was on the input variable. which is the one we want to use. and select the variable from the list. press the ‘Enter’ key. Next add the output q_xPulse to the Q output of the fbTOF If you use the . that the comment from the declaration section appears as a tool tip. With i_tTimeOn highlighted. the . 188 Chapter: PLC Programming “The Inspection Conveyor” Also notice that if you hover the mouse over the variable name in the list. fbTOF.Q. this allows the person viewing the code to easily see the beginning of each Function Block.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. the right side show each variable and its value. Using the above as an example i_xEnable. 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. 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 left side shows the code as it appears offline. The easiest way to do this. 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. resulting in the following Using the ‘TAB’ key to indent the lines of code that are part of the Function Block helps in reading the code. 189 Chapter: PLC Programming “The Inspection Conveyor” . When viewing code online that was written in Structured Text the code window is split. is place the cursor after each comma and press the ‘Enter’ key. then set the ‘Distance of two variables value.It is also possible to select ‘Monitoring Options’ from the ‘Extras’ menu. 190 Chapter: PLC Programming “The Inspection Conveyor” . flashing stack lights or other indicator lights. 191 Chapter: PLC Programming “The Inspection Conveyor” . In the POU column double-click on P_MachineMonitoring. Then press ‘OK’ This will add the generic code for the Function Block to the program.A pulsing output can be used for many different things. 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. 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. Click ‘OK’ The declaration section should now contain the following Add the following values to the inputs of the Function Block. 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’. 192 Chapter: PLC Programming “The Inspection Conveyor” Before assigning variable name to the inputs and outputs format the code for easier reading. .Replace the name FB_Pulse with a specific instance name of fbPulseCpuUsage. After clicking away from line 20 the ‘Declare Variable’ Window will appear. When the value changes the code needs to create the message to be logged. For this example we will create a log message every time the Machine State changes based on the value of E_MachineState. Creating logging information can be done in several ways. We will be creating a Function Block to monitor the variable eStep which holds the current value of the State Machine. there is also Database and XML supplements for working with those file types. There is a File Read and Write Function Block in the TcSystem library for interacting with a text file. Chapter: PLC Programming “The Inspection Conveyor” Start by adding a new Function and name it FB_LogStateMachine 193 . Now when the code is running the output will toggle on and off at a rate of 1 second. and then log that message. By writing to xReadCpuUsage the fbTC_CpuUsage ‘START’ input will toggle and read the CPU Usage every other second.For the output use the variable that was used on the TC_CpuUsage ‘START’ input. 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. the R_TRIG Function Block monitors its CLK input and when it changes from FALSE to TRUE the Q output will be on for one PLC scan sStateLog will be the STRING representation of the State Machine 194 Chapter: PLC Programming “The Inspection Conveyor” .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. if lines 3 and 4 were not included the Function Block would only work once. Chapter: PLC Programming “The Inspection Conveyor” Note: Any time a variable is set to TRUE inside an ‘IF’ statement. When the output is TRUE lines 8 through 14 will be executed and when the Q output is false line 16 will be executed. Lines 10 calls the ADSLOGSTR Function in the TcSystem library. Line 8 passes the value of i_eState into the F_StateMachineLookup Function. Note: The Function on Line 8 (F_StateMachineLookup) does not yet exist. 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. When the ‘Declare Variable’ window appears press the ‘Cancel’ button. 195 . else it is set to false (Line 4). 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).Add the below code to the Function Block. 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. Functions do not retain any values from one PLC scan to the next. When calling a function the result of that function must be stored into another variable. A Function Block requires an instance name and is assigned its own memory space. The variable ‘a’ is assigned a value of Call the ADD function and pass in the value of the variables b and c Chapter: PLC Programming “The Inspection Conveyor” The single result of the ADD Function will be stored in the variable a The ADSLOGSTR Function returns a UDINT (Unsigned Double Integer) ADSLOGSTR has three inputs msgCtrlMask : DWORD. A Function does not have an instance name and does not have its own space in memory. The most basic Functions are the Math Operators: ADD. SUBTRACT. msgFmtStr : T_MaxString. The following line of code does not compile however for the sake of explanation let us assume that it would. DIVIDE. MULTIPLY. 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. each of these are a function and return a single result. Additionally Functions only return a single result. strArg : T_MaxString. 196 .Calling a Function is different from calling a Function Block. etc. For Example a Timer or Counter must be a Function Block and not a Function. msgCtrlMask is used to define the parameters of the logged event HINT . the value that is passed into the Function will replace the %s in msgFmtStr The code sets the Control Mask to Hint and Log 197 . WARN . and ERROR are the type of Message LOG will write the message to the Windows Application Log MSGBOX will display a pop up box that shows the message msgFmtStr is a string that contains the text of the message and ends with %s Note: the text in the sample code and the %s are inside of single quotes Chapter: PLC Programming “The Inspection Conveyor” strArg is also a string. 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. these values are ADS Return Codes. 198 Chapter: PLC Programming “The Inspection Conveyor” Note: The ADSLOGSTR should always be called conditionally using a Rising Trigger Function Block. .The message in the log will be a value of Auto Machine State Changed to: Auto if sStateLog has q_udiErrID will hold the value of the result of the ADSLOGSTR Function. otherwise it will create a log message every PLC scan. any value other than 0 is an error. However the call to F_StateMachineLookup is going to throw an error. Right-Click in the POU column and select ‘Add Object’ 199 Chapter: PLC Programming “The Inspection Conveyor” . ‘Rebuild all’ and save the project.Now would be a good time to ‘Rebuild’ the code and save the file. To prevent this and check the code place comment markers around the code on Line 8 Now. Let’s 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. 200 Chapter: PLC Programming “The Inspection Conveyor” Note: Because Functions only have one output there is no VAR_OUTPUT section. . There are several ways to do this. In the declaration section add the Input Variable The Input Variable eState holds the STRING representation of the Enumeration.Define the Function as below. and its type is defined on line 1 of the declaration section. This Function will convert this value to an actual STRING that can be passed into the ADSLOGSTR Function. it can be changed on line 1. the most common way would be to create nested IF statements as below. The Name of the Function is the output variable. If you forget to change the type in the ‘New POU’ window. On line 4 eState will be compared to 1. 201 .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. On line 1 eState will be compared to 0. this will return TRUE and the code will continue to line 8. Chapter: PLC Programming “The Inspection Conveyor” Line 9 is empty Line 10 is another ELSIF. On line 8 the output variable F_StateMachineLookup will be set to a value of ‘Manual’. On line 7 eState will be compared to 2. 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. representing ‘Manual’. this will return FALSE and the code will then go to line 7. 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. this will return FALSE and the code will then go to line 4. Let us assume that eState has a value of 2. that one step will run. Remember that a Function does not hold any data from one PLC scan to the next.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. Even in this very simple example it would be on the 4th PLC scan that iStep would have a value of 3. However if the variable to be evaluated is the variable that is passed into the Function as a VAR_INPUT then the one step that is equal to the value of the variable that was passed in. This code would never work inside of a Function. and a CASE statement takes one PLC scan to change to the next step. In the below code eState is passed into the Function eState is then evaluated by the CASE statement to determine which part of the CASE statement to run 202 Chapter: PLC Programming “The Inspection Conveyor” . By using a CASE statement in this way. the amount of code to be processed is less than the above example of IF and ELSIF statements. therefore the amount of CPU usage is reduced. Place the code for the CASE statement into the body of the Function Now would be a good time to ‘Rebuild all’ and ‘Save’ your project.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. 203 Chapter: PLC Programming “The Inspection Conveyor” . After the ‘Rebuild all’ F_StateMachineLookup should now be in black Chapter: PLC Programming “The Inspection Conveyor” 204 . Do another ‘Rebuild all’ and then ‘Save’.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. 7. 3. Starting a new project Creating Global Variables with addresses Adding Comments to Variable names. 5. 205 Chapter: PLC Programming “The Inspection Conveyor” . 8. 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. 6. 2. 4.At this point we have covered the following: 1. We will start by adding a call to the P_MachineControl program from MAIN. Then press the ‘Enter’ key twice. Then press ‘OK’. This will place the cursor on that line. The first conveyor will be manually loaded by an operator and then index the box along the conveyor. We will be adding code to the program that allows the conveyor to be loaded and material to enter the system. and then we will convert this PROGRAM to a FUNCTION BLOCK so that we can create multiple instances of it. Left click at the end of line 33 in MAIN. The cursor is now on line 35 Press the ‘F2’ key to open the ‘Input Assistant’ In the left column select ‘User Defined Programs’. Digital I/O The purpose of this section is to introduce the first mechanical part of the Inspection Conveyor. We will start by creating a PROGRAM to control a single conveyor. select ‘P_MachineControl’. 206 Chapter: PLC Programming “The Inspection Conveyor” .23. in the window on the right. Right-Click in the POUs column and select ‘Add Object’.‘P_MachineControl’ will now be called and scanned after ‘P_MachineMonitoring’. Eventually there will be several specialized conveyors in our conveyor system. For now let us create the ‘Infeed Conveyor’. Double-click on P_MachineControl in the POUs column. 207 Chapter: PLC Programming “The Inspection Conveyor” From ‘P_MachineControl’ we will be adding code to call the control program of the conveyor. . Double-Click on P_MachineControl and use the ‘F2’ key to call the ‘P_InFeedConveyor’ program from ‘P_MachineControl’. To prevent the ‘Declare Variable’ window from popping up we will create all of this as comments The first comment will be a general overview of what the code in this POU does. By placing (* at the beginning and *) at the end.Create a ‘Program’ and ‘Name’ the ‘POU’ ‘P_InFeedConveyor’. In keeping with ‘Top-Down’ programming principles we will add some ‘code’ that is more descriptive than functional. all text in between is ignored by the compiler. 208 Chapter: PLC Programming “The Inspection Conveyor” . therefore. 209 . both of these Function Blocks are writing to the same output (bLight) every PLC Scan.The next thing to do is add comments for what we expect to need the program to do. There are several ways to do this. This program will control this conveyor in all modes of operation. when in Manual the same light should flash at 2Hz. If you attempt to control an output from more than one location then the last one to write to the outputs will determine its final state. and Maintenance. we could set up a selection statement and write code for what to do when in each mode or each command (output) could monitor each mode and decide what to do. Auto. It is best to only write to an output in one location. Chapter: PLC Programming “The Inspection Conveyor” However. We could try the following: Note: (eMode = E_Manual) in the code will compare the two values and return either a TRUE or FALSE value. the Function Block fbPulseAuto always has control of the output. Manual. These are not in any specific order and more might be added later. but this gives us a place to start. As a simple example let us consider the following: When in Auto a light should flash at 1Hz. With only two possibilities (Auto or Manual) an ‘IF’ statement works well.The following ‘IF’ statement could be used to properly select which Function Block to call Only one of the two Function Blocks will be called at a time. therefore. However in the code shown there is nothing to reset the fbPulseManual Function Block. either the TON or the TOF was in the process of timing. a ‘CASE’ statement is more efficient. however. the code just stops calling the Function Block. The light has changed from a 1Hz pulse to a 2Hz pulse. The value of all of the variables have been ‘frozen’. For a light this probably will not cause a problem. The following provides the same functionality as above: Both of these examples have an inherent issue. 210 Chapter: PLC Programming “The Inspection Conveyor” . however. after a period of time eMode changes to E_Auto. it is not possible to ‘Pause’ a timer. if the output is something more critical it could be a serious issue. Because we are writing to the same output from two different Function Blocks when the transition happens the value of the output might not be what we expect. they record the start time and compare that to the current time to calculate the elapsed time. Let us assume the current value of eMode is E_Manual. only one of them will be attempting to control the value of bLight. however. Therefore. When eMode changes back to E_Manual the elapsed time (ET) will jump. Internally the TON and TOF Function Blocks do not need to increment each PLC scan. If eMode has a value of E_Auto and the active timer has an ET of greater than 500ms then when eMode changes to E_Manual that timer will instantly be done and the Q output of the timer will be TRUE. The time value will be loaded into the TON and TOF inside of fbPulseLight on the same PLC scan. but adjust the time value based on eMode: In the above example the value of tTime will change based on the value of eMode. it is ultimately up to the programmer to choose the implementation that best fits the specific implementation.In order to remove this problem we can use one Function Block to write to the output. all of these samples do the same thing. 211 Chapter: PLC Programming “The Inspection Conveyor” . In the below example the Pulse Function Block is called and the Enable input is set to FALSE when the value of eMode Changes In this scenario both the TON and TOF will be restarted when the value of eMode changes. The difference between them is how the output reacts on the PLC scan where the value of eMode changes. With the exception of the first example. The small changes that can happen in one PLC scan can create unexpected results that are difficult to detect and troubleshoot. however. the conveyor would continue to run. I would like to explore some options for how to write this control code before moving on to our slightly more complex example with a Middle PE. To fix this problem. what happens? In this case the ExitPE is looked at last and therefore the MotorStarter would be set to FALSE. and one Motor Starter. This is where a program like Scope View can be used to detect these short pulses. this would achieve the desired result. and try to optimize the code we could also do the following. The below code uses the EntryPE to start the conveyor and the ExitPE to stop the conveyor. If the two ‘IF’ statements were reversed and both PEs were blocked. 212 Chapter: PLC Programming “The Inspection Conveyor” .When writing a PLC program the above situation can cause many problems for new programmers. if both Photo Eyes are blocked. Once. If we look at a simple conveyor that has an Entry and Exit Photo Eye (PE). the box has reached the Exit PE the Motor Starter is de-energized and the conveyor will stop. but instead being used as an input to a Rising Edge or Falling Edge trigger. the Entry PE is blocked which causes the Motor Starter to energize and the conveyor moves forward. when a box is placed on the conveyor. If the output was not controlling a Light. the R_Trig and F_Trig Function blocks will see this transition but you may never see it simply by visually looking at the code. Notice that the only situation where the Motor Starter will be TURE is when the Entry PE is true and the ExitPE is FALSE. Normally as efficiency increases. Truth Tables are used to describe a Boolean function that has multiple inputs and one output. the third line shows the EntryPE is TRUE and the ExitPE is FALSE. the second line shows that the EntryPE is FALSE and the ExitPE is TRUE. Finding a balance between efficiency and readability is always a difficult task. The first line shows them both being FALSE. The numbers on the far left are decimal numbers starting at 0. The ExitPE will have a value of FALSE when there is not a box blocking the PE. Although as a programmer it is good to optimize your code. however. The Truth Table for our conveyor would look like the following. Therefore anytime a box is present at the ExitPE the nested ‘IF’ statement to look at the EntryPE will not be executed. the fourth line shows that both inputs are TRUE. . In the Motor Starter column is the state of the output that we would like. 213 Chapter: PLC Programming “The Inspection Conveyor” Each of the two inputs can only be either TRUE or FALSE. readability decreases and vice versa. Our conveyor has two PEs and one Motor Starter. you or someone else is going to have to read your code. The last option I want to explain will be the most difficult to understand. This covers all possible input situations. based on the input conditions.This does a couple of things. remember that at some point in the future. notice that the numbers under the Input conditions are the binary equivalent to these decimal numbers. This makes the code more CPU friendly and also ensures that any time the ExitPE is blocked (TRUE) the conveyor will stop. it will provide the most flexibility. and as PEs or other conditions are added to the system it will be the easiest to manage and change. Let us assume that iStep is declared in the PLC as an integer. iStep will represent the decimal equivalent of the status. and 3 When iStep is 0. of the two PEs. iStep has four possible values 0. or 3 the Motor Starter is False. If we then assign the ExitPE to the first bit of iStep and the EntryPE to the second bit of iStep. We can now use a ‘CASE’ statement to control this: 214 Chapter: PLC Programming “The Inspection Conveyor” .1.To translate this into code we will start by converting the Boolean inputs and combining them into an integer number.2. When iStep is 2 the Motor Starter is True. We can then control the output based on the value of iStep. 1. Although we are writing to the variable in multiple places. 215 Chapter: PLC Programming “The Inspection Conveyor” Adding the MiddlePE to the system will be simple in the ‘CASE’ statement. however. within the same PLC scan. If you wanted to start a timer when the ExitPE was blocked and the EntryPE was not. it will be the next PLC scan before the ‘CASE’ would change. The below could be used. simply separate the values with a comma. This also gives us the flexibility to easily add more functionality based on the status of the inputs.It is also possible to combine the CASES where the code is the same. which would be much easier than trying to add it to the ‘IF’ statements in the first examples. you could simple add that code to ‘CASE’ 1. because they are inside of a ‘CASE’ statement only one of them will be written to in a given PLC scan. . I would first like to repeat the first two ‘IF’ statements to show why and how this method becomes more complicated. If the value of iStep was to change. but if all three PEs are on then the PLC is writing to the output in two places. simply add a third bit. Previously there were two PEs. copy and adjust which inputs are copied to which bits. and therefore more difficult to debug.In the next example the code has been made more efficient and the PLC is only writing to the output once during the PLC scan. If the ‘CASE’ statement is used then we will see how flexible it really is. but it is more complicated to follow. to add a third PE. 216 Chapter: PLC Programming “The Inspection Conveyor” . 4.Expand the ‘Truth Table’ to include the new possible combinations From the ‘Truth Table’ we now see that the Motor Starter will be energized when iStep is equal to 2. or 6 217 Chapter: PLC Programming “The Inspection Conveyor” . If we start with the following code we will see that the code gets locked up. because any time the middle PE is blocked the Conveyor cannot move. Therefore we need to monitor the PE and select when it will have an effect on the conveyor. The xConvRunEnable will provide one of the start commands. each Photo Eye will provide a stop command. xConvRunEnable is defined as a local BOOLEAN. It will not be used to directly start and stop the conveyor.This can be reduced to: For an example of how to use a Truth Table and Boolean Algebra for the most efficient coding of this example please refer to Appendix II – Truth Tables and Boolean Algebra. For this program we will use the ‘CASE’ statement as it is easier to make changes to. This variable will be used to know when the Photo Eyes are in the correct states to start the conveyor. 218 Chapter: PLC Programming “The Inspection Conveyor” . I have changed the variables names to match the naming convention. It will be used later to stop the conveyor. and the Q output of the ‘R_Trig’ can be monitored for stopping the conveyor while the PE itself is ignored. . The timer needs a condition that will stay TRUE for the duration of the PT (Preset Time). 5 seconds later the conveyor should start again. then a 5 second timer to pause the conveyor. the simplest is to use a Rising Edge Trigger ‘R_Trig’ from the ‘Standard’ libray. When a box reaches a PE the conveyor should stop. 219 Chapter: PLC Programming “The Inspection Conveyor” Add the three R_Trig functions blocks to the code below the CASE statement. then monitoring the xConvRunEnable will give us everything we need. If the IN goes FALSE then the timer will reset and start again with an ET (Elapsed Time) of zero. In order to start the conveyor the enable needs to be TRUE and we are also going to pause the conveyor for 5 seconds each time a PE is blocked. The PE will provide the input and the output will be TRUE for one PLC scan. This will allow the program to know that a new boxed has arrived.There are several ways to do this. because they will not be used on this line of code. Using each PE to stop the conveyor. The Q outputs of the function blocks were removed. This sequence of steps is easily handled in a ‘CASE’ statement. this will allow the operator to place a new box at the Entry PE. this timer will be reset in the ‘Init’ step. therefore. Each step number also increases by a value of 10.The basic framework of the ‘CASE’ statement will look like the following. As an example we will be adding a TON (Timer On) in step 20. Each step has a comment that describes what will happen in that step. The ‘Init’ step is there because it is a good habit to start. this allows for steps to be added without having to change all of the step numbers. 220 Chapter: PLC Programming “The Inspection Conveyor” . I always include it. most ‘CASE’ statements are going to need to use it. 221 Chapter: PLC Programming “The Inspection Conveyor” .Below is the entire ‘CASE’ statement. Without the ELSE step the code would get stuck. if for some reason a change is made to the code and iStepSequence is given a value that is not defined then the commands in the ELSE step will be executed. The reason for the extra step is to ensure that the timer is reset before being used. Step 30 sets the Motor output to TRUE and increases iStepSequence by 10. Step 20 calls the timer with a FALSE command.Step 0 is the ‘Init’ step. because the timer is reset in step 20 we must go to another step to wait for it to finish. this is purely used for debugging purposes. After 5 seconds has elapsed the Q output will be TRUE. The last command of the step is to increase the value of iStepSequence by 10. Additionally iErrStepNumber is given a value of iStepSequence to help find what the value of iStepSequence was that sent us to the else statement. If the code stayed in step 20 the timer would be reset every PLC scan and therefore it would never complete. then iStepSequence will be increased by 10. Then iStepSequence is increased by 1. IF the PEs are in their correct state. Next the same timer is called with a TRUE command and given a time value of 5 seconds. On the next PLC scan step 21 will be executed. On the next PLC scan step 10 will be executed. here we set all Function Blocks that are going to be used within the ‘CASE’ statement to FALSE. Step 40 monitors the outputs of the three R_Trig Function Blocks. Step 21 calls the timer and monitors the Q output of the timer. when any one of them is TRUE the motor output is set to FALSE and iStepSequence is set to 0. the timer will be reset with a FALSE command and the value of iStepSequence will be set to 30. Step 10 monitors the xConvRunEnable from the previous ‘CASE’ statement. 222 Chapter: PLC Programming “The Inspection Conveyor” . The ELSE step is a good practice. The process will then repeat. On the next PLC scan step 20 will be executed. this will reset the ET of the timer to 0. If nothing ever went wrong our conveyor would be mostly complete at this point. The idea of a ‘De-bounce circuit’ is to detect that a BOOLEAN condition has changed and stayed at its new state. If we look at step numbers. Let us assume that a fly is in the building and it crosses in front of the path of the PE. One of them is the possibility of a glitch in the Photo Eye. Also the IF and END_IF have nothing in between them. it is easy to move downward and find the next step number. There are a couple of ways to do this. which makes the END_IF easy to locate. Compare the two pictures below to see the difference this makes. 223 Chapter: PLC Programming “The Inspection Conveyor” . all of them deal with timing. however. depending on the hardware of the PE it may or may not be detected. If it is detected then the conveyor is going to stop as if a box was present. When using a very sensitive PE it is possible that the PE will transition from FALSE to TRUE at times other than when a box appears in front of it on the conveyor. It is unlikely that you as a programmer will think of every possible situation that could cause a problem. To prevent this type of problem we can add a ‘De-bounce circuit’ to the code. if it can go wrong it will. and not bouncing between TURE and FALSE. Over time you will start to learn the most common problems.Also notice how the code is indented using the ‘TAB’ key. This is done to help make the code more readable. . If the conveyor is moving extremely slow then the code could wait for the PE to be True for 1 second before stopping the conveyor. For another version of the above. D=R*T Distance = Rate of travel * Time If the box is 10 inches long and we want to limit it so that no more than 25% of the box moves past the PE then our Distance will be 2. However as the conveyor increases in speed the 1 second wait might cause the box to move to far before stopping the conveyor. We would then have to monitor xInputDebounced in our code and possibly look at other conditions for setting it to FALSE and set iCount back to 0. If there is a way to know the velocity of the conveyor then we can calculate the precise time we need to ensure a box is present and still stop the conveyor before it falls off. In the above example when the PE is TRUE iCount will increase by a value of 1 each PLC scan.We will start with an obscure example because it makes for good sample code. If this was done on the machine and then for some other reason the PLC task time needed to change. This would be another reason not to use the above counter and rely on it to work in all situations. please refer to Appendix III – De-bouncing and Input. then all of the places in the code where we de-bounced an input would need to change. In my opinion using the PLC scan to control your code is never a good idea.5 inches 224 Chapter: PLC Programming “The Inspection Conveyor” When de-bouncing an input that involves motion the speed at which the product is moving needs to be considered. If the PLC scan is 10ms then after 100ms (iCount >= 10) xInputDebounced will be set to TRUE. but also should not allow boxes to fall into the floor. The box should stop at the end of the conveyor without stopping erroneously. The above example inherently uses the PLC cycle time as the timer. Imagine we have a simple conveyor with a PE on the end of the conveyor. Add a Function Block with a name of FB_DebounceInputFalseToTrue 225 Chapter: PLC Programming “The Inspection Conveyor” . Distance / Rate will return a LREAL value which cannot be stored in a variable of type TIME When the input is True for tTime (2.The Rate of travel will be the speed of the conveyor.5 inches / 1fps Time = 2. We will assume that out conveyor is moving at 1 foot per second (fps).5 seconds Therefore we could implement the following code with a simple timer Note: The above sample will not compile.5 seconds) the output will then be True. To make this more flexible and reusable we will place this into a Function Block and allow the values of Distance and Rate to adjusted by a variable. The output will turn False immediately when input turns False. Our reaction is now Time = Distance / Rate of travel Time = 2. 5ms. 226 Chapter: PLC Programming “The Inspection Conveyor” . multiplying by 1000.5s Open P_InFeedConveyor and use the Function Block to de-bounce the 3 PEs on the Conveyor.0 before converting will result in tTime having a value of T#2.5 into T#2.Declare the follow in the Function Block Add the following code to the body of the Function Block The LREAL_TO_TIME conversion will convert the 2. xExitPE, xMiddlePE, and xEntryPE are declared as local variables of type BOOL. In the Check if clear to advance and the Conveyor Advance sections we are using the real inputs in the code, these must be replaced by our new de-bounced inputs. 227 Chapter: PLC Programming “The Inspection Conveyor” In review of where we started We see that the following sections of code have been completed. De-bounce, Check if clear to Advance, and Conveyor Advance The On/Off delay was built into the CASE Statement for Conveyor Advance, so it can be removed. The next thing to implement is Jam Detection. The jam detector on this conveyor will detect when a box leaves either the Entry or Middle PE and does not reach the next PE. Because there will be two Jam Detectors we will implement this as a Function Block. This basic idea for the code is as follows If both PEs are False then start a Timer. If the timer completes within the given amount of time then this will indicate that the Box is stuck on the conveyor. A few things to consider: We don’t want the Jam Detector to cause an error if there are no boxes on the conveyor. 228 Chapter: PLC Programming “The Inspection Conveyor” We need to know how long it is supposed to take for the box to get from one PE to the Next. We can do a calculation similar to the one we used for the de-bounce D=R*T. The last thing to keep in mind is what happens if the conveyor starts and the box gets jammed before clearing the first PE. Therefore, instead of using the NOT PE we will use the command for the Conveyor to start moving. Create a Function Block with the following name FB_JamDetection Declare the following in the Function Block. 229 Chapter: PLC Programming “The Inspection Conveyor” Add the following code to the body of the Function Block. Lines 1-5 A rising edge of i_xStart will be used to start Jam detection (xJamDectectEnable). Line 7 Calculate the amount of time that can pass before turning on the error (q_xJamDetected). Line 9 Call the timer. Lines 11-16 If the destination is reached, disable the Jam Detection, disable the timer, and set the Jam Detected output to False. Chapter: PLC Programming “The Inspection Conveyor” 230 Place the following in P_InfeedConveyor fbJamDetection_MiddlePE and fbJamDetection_ExitPE are defined locally as type FB_JamDetection xJamDetectedMiddlePE and xJamDetectedExitPE are defined locally as type BOOL We are using the destination as the Jam Detection PE. Therefore the Function Blocks are for the Middle and Exit PEs. The variable gatq_xMotorOn will be used to start the monitoring for a Jam. The destination PE will stop the monitoring. A distance of 50 with a Rate of 1 will make the timer run for 50 seconds before turning on the Jam Detected output. Chapter: PLC Programming “The Inspection Conveyor” 231 Mode Handling In the Program ‘MAIN’ we created a CASE statement that would select the Mode based on the input selector switches, which were defined in ‘Global_Variables_IO’. eStep was defined locally in MAIN. We will need to change this to a global variable. Cut eStep :E_MachineState :=0; from the local declaration in MAIN, and Paste it into ‘Global_Variables’. Use the Resources tab to see the Global Variable lists. MAIN should now have no local variables. ‘Global_Variables’ should now have eStep. 232 Chapter: PLC Programming “The Inspection Conveyor” The current code inside of P_InfeedConveyor is for how we want it to operate when machine is in Auto. We still need code for Manual, and Maintenance. In order to organize the code we will use ‘Actions’. One Action will be created for each possible state of E_MachineState. To review E_MachineState has four possible values: E_Undefined, E_Maintenance, E_Manual, and E_Auto. To add an ‘Action’, Right-Click on P_InfeedConveyor and select ‘Add Action’ from the context menu. 233 Chapter: PLC Programming “The Inspection Conveyor” Name the ‘Action’ A_Auto, and set the language to ‘ST’. Then click ‘OK’. Notice tha P_InfeedConveyor is now expandable, and the Action is shown when it is expanded. If you Double-Click on the Action, you will notice that it does not have a local variable declaration section. It only has a code window. Actions will use the same local variable list from the POU in which it is contained. Create actions for the other possible Modes of E_StateMachine, E_Maintenance, E_Manual, and E_Undefined. Chapter: PLC Programming “The Inspection Conveyor” Place a semicolon ; in each of the Actions. Preform a Project-> Rebuild All to compile the code. You should get 1 error. Double-click on the error and look at the code 234 which was previously declared in MAIN. Jam Detection. We now need to move parts of the code from P_InfeedConveyor into the A_Auto Action De-bouncing the Input PEs. ‘Check if clear to advance’ and ‘Conveyor advance’ could happen in both Manual and Auto. Simply remove ‘MAIN. and then Save your program. Since we have now moved eStep to a Global Variable we need to correct this line of code. but the code was written for Auto.In P_MachineMonitoring we were looking at the status of eStep.’ In front of eStep. and Faults are not mode dependent and will stay in P_InfeedConveyor. Preform another Project -> Rebuild All. Copy and Paste the ‘Check if clear to advance’ and ‘Conveyor advance’ code from P_InfeedConveyor to A_Auto. Starting at line 40 Ending at Line 97 235 Chapter: PLC Programming “The Inspection Conveyor” . and the code for Manual will be different. The code in A_Auto is complete for now.We must now call the Action A_Auto (and the other Actions) from P_InfeedConveyor. 236 Chapter: PLC Programming “The Inspection Conveyor” . We will create a new CASE statement that selectively calls the Actions based on the value of eStep. 237 Chapter: PLC Programming “The Inspection Conveyor” . Declare gatq_xJogConveyor as a Global Input For now A_Maintenance and A_Undefined have no use.In A_Manual we will add code for Jogging the Conveyor. in them. Leave them with only a semicolon . We will create some faults for the most obvious conditions that could happen in our program. This code will turn on the two fault variables when a Jam is detected. 238 .Fault Handling Creating faults for every possible situation is a never ending task. Starting with Jam Detection. create a fault for each of the two Function Blocks Create a new Global Variable list called Global_Variables_Faults Declare the two new Fault Variables Chapter: PLC Programming “The Inspection Conveyor” In the Fault section of P_InFeedConveyor place the following code. giConveyorAutoSequenceErrID is an INT that will hold the value of the Error Step. giConveyorAutoSequenceErrID. and gsConveyorAutoSequenceErrMsg are defined in the Global_Variables_Faults list When the variable iErrStepNumber has a value other than zero three types of faults will happen. 239 Chapter: PLC Programming “The Inspection Conveyor” . then the fault variable will set back to True. if the fault condition still exists. gxConveyorAutoSequenceErr.Add the following code to reset the faults. Add the following code to create a fault when this error happens. gsConveyorAutoSequenceErrMsg will hold a STRING that gives a description of the error and the Error Step number. Note: This reset code will only reset the fault variable. gxConveyorAutoSequenceErr is a BOOL that will be set to TRUE. In the CASE statement that handles the conveyor in Auto we created an Error Step Number variable called iErrStepNumber. this program is not flexible. Not IF. and resetting them. the more difficult it is to read. Instead we will set it back to zero when the Reset button is pressed. We could do this somewhere in the CASE statement. However the easier it is to read the harder it is to program when changes have to be made. the power of this modular approach using Functions and Function Blocks will become very obvious. there is currently no code to change iErrSStepNumber back to 0.These Errors should be Reset by use of the variable gati_xReset. Add the following code As we expand upon our Faults in further chapters we will explore more efficient was to handle Faults. 240 . At this point our conveyor is complete. but there could potentially be a problem caused by the PLC scan. I would like to remind you of a point I made earlier. but WHEN someone decides that the machine needs to be modified it will be more difficult to do. The more efficient the code is. However. Comparing the above line of code with the program that we created gives the impression that we wrote a bunch of code for no reason. Chapter: PLC Programming “The Inspection Conveyor” The core of the program we just created could be summed up in 1 line of code However. However as we expand the machine. In the below picture is a simple circuit consisting of a power supply. and so on. Lamp Test One of the key points of trouble shooting any system is knowing where to dissect the system. a push button.VI. and a LED. Over the next few pages we will look at how the hardware is wired and how the communication happens when using a PLC to control our simple system. With a PLC the method of trouble shooting does not change. then test the push button. If you know where to break the system apart and what to look for then the problem can be more easily isolated. if that is good. If the LED is not illuminated then the first step is to decide where to start searching for the problem. Trouble shooting 24. Test the power supply. if it is good then test the continuity of the wire. 241 Chapter: Trouble shooting . The I/O cards receive their power from the cards to their left. Be aware that not all cards use and/or pass the power rail.  242 Chapter: Trouble shooting . and then pass power to the cards on their right. The Power Rail is powered by an external source.  The push button will be wired from Connection Point 2 on the EL1002 through the push button, and then back to Connection Point 1 on the EL1002. When the contacts are closed power is sent from the positive connection to the input.   The LED will be wired from Connection Point 3 on the EL2002 through the LED, and then back to Connection Point 1 on the EL2002. When the output is turned on, the LED will illuminate.  243 Chapter: Trouble shooting   The EtherCAT Coupler must be powered for communication to occur. Note: This power should be supplied separately from the power rail. 244 Chapter: Trouble shooting  The EtherCAT Coupler is connected to a network port on the Controller by an EtherCAT Cable. 245 Chapter: Trouble shooting  The Controller will communicate with the I/O through the coupler. When the Input is true this will be sent to the controller to be processed by the PLC. The PLC will then send a command to the output to turn on the LED. Note: The Coupler power and power rail power are supplied separately.  246 Chapter: Trouble shooting  In the TwinCAT System Manager the EtherCAT Coupler can be found under the I/O Configuration I/O Devices – Device 1 EtherCAT – Term 1 EK1100 (These are the default labels, they will probably be different on your machine.) The I/O Terminals can be found under the Coupler   247 Chapter: Trouble shooting  In the TwinCAT System Manager the Hardware is linked to the PLC variables. 248 Chapter: Trouble shooting  In the PLC the variables are declared with addresses so that they may be linked to the hardware  When the code is run, Light1 will have the same value as Switch1  Power passes from the supply through the power rail and to the Push Button, when the button is pressed power is supplied to the input 249 Chapter: Trouble shooting   When the EtherCAT update happens the status of the input will be given to the EtherCAT packet The EtherCAT card in the PC will pass the data directly to the PCs memory where it can be read by the System Manager 250 Chapter: Trouble shooting  The system manager will then pass the data from the I/O Configuration to the PLC Configuration  The PLC will then process the code 251 Chapter: Trouble shooting .  The system manager will then pass the data from the PLC Configuration back to the I/O Configuration 252 Chapter: Trouble shooting . 253 Chapter: Trouble shooting . The EtherCAT card in the PC will read the data directly from the PCs memory and send out the EtherCAT packet over the network.  When the data reaches the Output card the output will be energized and the LED will illuminate.     Electricity and Data flow “downstream” From the Push Button to the LED Along the path there are several places where the signal can be tested and/or monitored At the wiring connection of the card. 254 Chapter: Trouble shooting . in the I/O or PLC configuration of the System Manager and in the PLC Code itself. just as if the Push Button had been pressed However.     When a variable is Forced inside the PLC. if the Output in the PLC Configuration is Forced then only the hardware will be effected. The PLC Code will have no idea that the output has been energized. Here b has been Forced to a value of 1 and a is assigned a value of b + 1 or 2     Here b has also been forced to a value of 1 However. The Force is then applied again at the end of the PLC Scan. the Force is applied and then the PLC Code is allowed to run as it normally would. the first line of code assigns a value of 2 to b This will result in a being assigned the value of 3 255 Chapter: Trouble shooting .    When testing hardware it is possible to “Write” and to “Force” data into the system A “Write” is applied one time and then control is given back to the system A “Force” in the System Manager is applied before each update of the I/O or PLC task If a Write is applied to a variable that is not linked then nothing in the system will tell that variable to have any other state When Writing or Forcing in the system manager the Flow of data must be taken into consideration If the Force is applied to an Input in the I/O Configuration then everything downstream will react accordingly. 25. In the Task configuration of the Resources Tab you will find the Default ‘Standard’ task with its call to the program ‘MAIN’ Task ‘Standard’ is configured here with a Priority of 0 and an interval of 10ms  256 Chapter: Trouble shooting . 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. and the task ‘FastTask’ has an interval of 1ms and a Priority of 0 The highest Priority ‘0’ should always have the fastest interval time    In this configuration the ‘Standard’ task calls the program ‘MAIN’ ‘MAIN’ will then call its subsequent POUs 257 Chapter: Trouble shooting . 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. right click on a POU and select ‘Show Call Tree’ 258 Chapter: Trouble shooting .     In the below example ‘MAIN’ is calling the other programs The first line of code in ‘MAIN’ calls the program ‘Manual’ ‘Manual’ will run its code from top to bottom and then return to ‘MAIN’ ‘MAIN’ will then call ‘Semi_Auto’ ‘Semi_Auto’ will run its code from top to bottom and then return to ‘MAIN’  Note: To view the Call Tree.  If a Function Block is called from a program the same process applies  When the last line of code in ‘MAIN’ is reached the PLC will return to the first line and repeat the process Below is an online view of ‘MAIN’ The dark gray lines are code that is running. line 6 is the last line of code   259 Chapter: Trouble shooting . but with the PLC running every 10ms you probably won’t make it in time. 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). Breakpoints are enabled and disabled in the Project -> Options menu  260 Chapter: Trouble shooting .26.   In the left column select ‘TwinCAT’ Select ‘Enable breakpoints’ then click ‘OK’   Breakpoints can be used to aid in debugging the PLC code When the line is selected where the Breakpoint is to happen the PLC code will run until that line of code is reached When the breakpoint is reached the PLC will stop running and the status of variables can be seen in their current state This will allow the checking of the code to determine if the code is executing properly Note: Breakpoints can NOT be set in an instance of a function block they must be set in the implementation of the function block and therefore each instance of that function block will stop when the breakpoint is reached. To set a breakpoint. click on the rung or line number where you wish the PLC to stop     261 Chapter: Trouble shooting . bSwitch is currently TRUE and therefore the PLC is still running  Also note that the breakpoint indicator is set in the bottom right corner of the PLC Control   When bSwitch turns FALSE the breakpoint on line 4 will stop the PLC The code on line 4 is not executed  We can also see in the status bar that the PLC is no longer running 262 Chapter: Trouble shooting . Here the breakpoint has been set on line 4. 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. If only one breakpoint is set then the PLC will run from the breakpoint thru the last line of code.   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. upon the next Single Cycle command the PLC will run from the first line of code up to the breakpoint. 263 Chapter: Trouble shooting . 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.    The Breakpoint Dialog command opens the below window From here you can see a list of all breakpoints that exists in the PLC Breakpoints can also be added and removed from here 264 Chapter: Trouble shooting . Flow Control   Flow control allows you to see which lines of code are being executed In the sample lines 1 and 4 are running because 1 is greater than 0 265 Chapter: Trouble shooting .27. The task that is responsible for calling the program you are monitoring must be set to the ‘Debug Task’ 266 Chapter: Trouble shooting . You must be ‘Logged In’ to the PLC 2. Flow Control can be turned on thru the ‘Online’ menu or with the keyboard shortcut Ctrl+F11  Flow Control may appear at times to not be working. there are 3 possible reasons for this. The program you are monitoring is not being called 3. 1.   In this example when ‘a’ is greater than ‘b’ the program Light_On is called First take note that the code for Light_Off will only show the flow control if the program Light_Off is being called and you can see from ‘MAIN’ that it is not being called unless a is not greater than b Secondly note that only the selected window will display the flow control  267 Chapter: Trouble shooting .    The debug task can be set in the Task configuration when you are logged in to the PLC Right click on the Task name and set it as the ‘Debug’ task Flow Control is only displayed for the ‘Debug’ task     Warning!!! Flow control should never be used inside of a function block Only use Flow control in a Program If Flow Control is on inside of a Function Block it will display the values and status of the first instance of that Function Block 268 Chapter: Trouble shooting .  In the below picture you see that the second instance of the Function Block indicates that it is running even though it is not being called from ‘MAIN’ 269 Chapter: Trouble shooting .   Notice in this picture that bPulse is blue indicating that it has a value of TRUE However fbPulse2 is not being called from ‘MAIN’ and bPulse in the local delaration has a value of FALSE NEVER use Flow Control inside of a Function Block  270 Chapter: Trouble shooting . 28. Global Search  The Global Search tool allows for the search of anything inside of any part of the project or the entire project A Global Search can be started in 3 different ways    Project -> Global Search Ctrl+ Alt + S Tool Bar Icon  271 Chapter: Trouble shooting .     Selecting Global Search from the Project Menu will open the following window Ctrl+Alt+S will open the same window From here the sections of the program to be searched can be selected Holding the Ctrl key will allow for selecting multiple sections Note: Using the Tool Bar icon skips this selection window and will search the entire project. 272 Chapter: Trouble shooting .  Once the sections have been selected press the ‘OK’ button 273 Chapter: Trouble shooting . Note: If you are Logged In to the PLC. the message window is hidden by default. 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.    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. Selecting ‘Message Window’ from the ‘Window’ menu or pressing Shift+Esc on the keyboard will open the Message Window    274 Chapter: Trouble shooting .  Searching for the letter ‘a’ will return everywhere the letter ‘a’ is used in the sections selected   The first line shows the search phrase The last line shows how many times the search phrase was found 275 Chapter: Trouble shooting . the instance of the structure or both  276 Chapter: Trouble shooting . The second line below is stating the following   Double Clicking a line in the Message Window will take you to that line of code in the program When using the search tools on a structure remember that the Global Search will search for anything and the Cross Reference needs an exact variable name The Global Search tool can be used to search for an element within a structure. Additionally if a Build has not been done since the last change was made the cross reference could return incorrect results 277 Chapter: Trouble shooting . Cross Reference  The Cross Reference tool allows for searching specific items in the PLC     Variable Address POU The tool can be started 2 ways   Project -> Show Cross Reference Ctrl+Alt+C  Note: The code must compile with no errors before a cross reference can be done.29. Double clicking the POU name will also go to where the variable is used ‘Cancel’ will close the search window ‘To message window’ will send all of the search results to the message window. The format will be done the same as a ‘Global Search’   278 Chapter: Trouble shooting .    The variable name must me entered exactly as it is used in the PLC code Selecting the text before opening the tool will place the selected text in the ‘Name’ box. Get References’ will start the search After selecting an item in the POU column ‘Go To’ will open the POU to the line of code where the variable is used.  The ‘List of References’ shows the following      The POU and line where the variable was found The name of the variable The address of the variable (if it has one) The scope of the variable Global or Local The Variable access (Read or Write) 279 Chapter: Trouble shooting .   When searching by address the full address must be entered Only the address entered will be searched. overlapping memory addresses will not be found 280 Chapter: Trouble shooting .  The POU search is limited. but when multiple tasks are used this will tell you which task to set as the ‘Debug Task’ for displaying the ‘Flow Control’ 281 Chapter: Trouble shooting .  When looking for where a POU is in the POU list. click somewhere in the POU list and start typing the name of the POU This will bring up a dialog box that will narrow down the results as you type Select the POU name from the list and then select open This will open the POU and also highlight it in the POU list    282 Chapter: Trouble shooting . TwinCAT System. 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.30. TwinCAT Scope View  Right click on Scope and select Add Scope View 283 Chapter: Trouble shooting .  Leave the defaults and select OK  Right click on Scope View 1 and select Add Channel 284 Chapter: Trouble shooting .  Give the Channel a descriptive name and press OK  On the Acquisition Tab of the Channel press the Change button 285 Chapter: Trouble shooting .  In the Edit Acquisition window select the correct Server Port and press the Reload Symbols button 286 Chapter: Trouble shooting .  Select MAIN.BSWITCH and press OK 287 Chapter: Trouble shooting .  Press the Start button 288 Chapter: Trouble shooting .  When the PLC variable changes state the change can be seen in the Scope 289 Chapter: Trouble shooting . A range is defined as having an upper value and a lower value. Languages Assignment: Write a program that will monitor an Analog Value and energize an output if the value is within a specific range. and the second condition is that the value is less than the upper end of the range. Therefore Condition will be TRUE is the value is greater than 0. 290 Chapter: Labs . The output will be energized if the value is within range. Condition1 is that the value of the analog input is greater than the lower end of the Range.000. Therefore we have 2 conditions that determine if the output is energized. Therefore Condition will be TRUE is the value is less than 10.VII. If both conditions are TRUE then the output will be energized. Labs 31.000. The first condition is that the value is greater than the low end of the range. Condition2 is that the value of the analog input is less than the upper end of the Range. We will assume the lower end of the range is defined as 0. We will assume the upper end of the range is defined as 10. Thoughts: We have 1 output to control. Here is the Ladder Diagram (LD) Code to solve the problem 291 Chapter: Labs . Here is the Function Block Diagram (FBD) Code It could also be written this way 292 Chapter: Labs . 293 Chapter: Labs . If this order of operations is incorrect.In Continuous Function Chart (CFC) it will look very similar to the second FBD example. and then connected to both inputs. it will require multiple PLC scans to fully execute the code. Also notice the order of operation in the gray box. Notice that iPot is only used once. Load the value of Condition1 AND it with Condition2 Store the result in xLight1 For the comparison we do the following Load the value of iPot If it is Greater Than 0 then store a TRUE.For Instruction List (IL) the same ideas still apply. The AND command will perform the AND function on the value of the following variable and the value stored in the holding register. else store a FALSE Store the result in Condition2 294 Chapter: Labs Load the value of iPot . It will then store that result in the holding register. and we work with a ‘Holding Register’ The below code works like this: The LD command will load the value of the following variable into the holding register.000 the store a TRUE. else store a False Store the result in Condition1 If it is Less Than 10. The ST command will read the value from the holding register and store it in the following variable. but we now work with 1 simple instruction at a time. It should be noted that you should always set your Conditions before you evaluate them. and the 2 conditions required to energize it.In some of the previous example I started with the output first. We started with the xLight1. This was only done for planning and explanation. Although we wrote that conditions last. Below are the full solutions: Ladder Diagram (LD) 295 Chapter: Labs . when writing code it is a common practice to work backwards to find a solution. Starting with the Output and then working back towards the input conditions that control the state of that output. We then looked at the values of iPot that were needed to set the conditions. However. they should be analyzed first. Function Block Diagram (FBD) Or Continuous Function Chart (CFC) 296 Chapter: Labs . In ST we will do the same. It actually has little to do with being at the end of each line of code other than we humans like to put it there. 297 Chapter: Labs . The semi-colon is for the compiler. As long as it appears somewhere before the next statement. In ST the line of code will always start with the variable that we would like to assign a value to. Anytime you would like to assign a value to a variable this symbol will be used. we will apply this literally. not the human.Instruction List (IL) The last language option is Structured Text (ST) In the previous examples I started with the output first. however. It indicates that a given statement is separate from the one that follows. The above line of code reads as xLight1 is assigned a value of Condition1 and Condition2 The := is an assignment statement. it will be fine. and wrote the code that would control that output. In Structured Text the semi-colon is a separator. the compiler already knows how to parse it via predefined delimiters such as END_CASE. Are equally valid as these two lines of code: xMyOutput:=true.These two lines of code: xMyOutput:=true . IF myValue > 9 THEN xMyOutput:=true. xMyOtherOutput:=false. ELSIF. In the case of a block statement like IF-THEN. END_WHILE. CASE-OF or WHILE-DO. ELSE. xMyOtherOutput:=false.xMyOtherOutput:=false. Therefore a semicolon becomes unnecessary in a block statement except to parse the separation of the individual lines inside the block statement. et cetera. END_IF 298 Chapter: Labs . IF iPot is greater than 0 and iPot is less than 10. Parentheses aid in understanding and controlling the order of operation. and Condition1 will be set to TRUE. Chapter: Labs 299 . and there is either an evaluation or instruction that must happen to determine the value that will be assigned to the output.000 then the function will return TRUE. and Condition2 will be set to TRUE. If iPot is greater than 0 then the function will return a TRUE. and Condition1 will be set to FALSE. If iPot is not greater than 0 then the function will return a FALSE. Each line of code has an assignment instruction. This line of code simply compresses the above into one line. Condition1 is assigned a value of: (iPot > 0) end of line Greater Than > is a function. this tells us that each of them are their own lines of code. If the value of iPot is less than 10.000 then xLight1 will be TRUE. When looking at these three lines of code together. notice that each of them ends with a . Pass in 2 values and it will return either TRUE or FALSE. else xLight1 will be FALSE.Now we add the code to control the Conditions. Similar to the other languages. else the function will return FALSE. and Condition2 will be set to FALSE. there are many ways to write the code and obtain the same result. Between IF and THEN the code must simplify down to either TRUE or FALSE IF iPot is greater than 0 and iPot is less than 10.000 then xLight1 will be TRUE. It is similar to a jump instruction. IF TRUE THEN Run This Code ELSE Run This Code END_IF Every IF instruction requires an END_IF 300 Chapter: Labs . The code of the ELSE condition will only be executed if the IF statement returns a FALSE. ELSE xLight1 will be FALSE.The IF instruction will selectively call parts of the code. Thoughts: Because both scales start at 0 we can simply divide the maximum scale-to value by the maximum scaled-from value. This will give us a ratio that we can multiply by the input and it will give us the scaled value.32. 301 Chapter: Labs . ScaledValue := InputValue * Ratio. Linear scaling using a Ratio Assignment: Create a function the will scale a value between 0 and 32767 to a value between 0 and 100. The formula will be Ratio := MaxOutput / MaxInput. an increase on the X-axis is called a Run. The 9/5 comes from the step required to get from one position on the line to the next. 212-32 / 100-0 = 180 / 100 = dividing both numerator and denominator by 20 will reduce the fraction to 9/5 Step = Y2 – Y1 / X2 – X1 = 212-32/100-0 = 9/5 Chapter: Labs 302 . 32 degrees F = 0 degrees C and 212 degrees F = 100 C Think of the Celsius scale as the X-axis and the Fahrenheit scale as the Y-axis. For each increase of 9 degrees in Fahrenheit. This can be calculated using the two known positions 100.32. Thoughts: This is similar to converting temperature from one scale to another. For any given value on 1 scale there is exactly 1 possible value on the other scale. The difference in the values will give us the change in Step. An increase on the Y-axis is referred to as Rise. The Formula to convert from Celsius to Fahrenheit is: TempF = 9/5 * TempC + 32 The +32 is the offset of the line. because it does not cross the Y-axis at 0. The numbers can go both positive and negative. you must increase 5 degrees in Celsius. So we have a Rise of 9 and a Run of 5.212 and 0.33. Linear scaling using an equation Assignment: Create a function that will scale a value between any two numbers to a value between any two other numbers. X1 b = How do you calculate b if you don’t have a graph? b = y1 – ( x1 * m ) If we know two points on the graph 0.32 and 100. the location where the line crosses the Y-axis y = 9/5 * TempC + 32 TempF = 9/5 * TempC +32 Using this formula we can now convert from any scale to any other scale y = mx + b m = Y2 .Because the step is actually a ratio it is referred to as the slope of the Line.Y1 / X2 .212 we can calculate everything else in the PLC 303 Chapter: Labs . in the formula we will use the letter m. The formula needed to do our conversion is y=mx+b m = Y2 – Y1 / X2 – X1 = 212-32/100-0 = 9/5 x = Temp in Celsius b = 32 the Y-Intercept. 304 Chapter: Labs . 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. The VDI does have plans to publish a new document in English that will focus more on software camming. 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. even if the TwinCAT Cam Design Tool is used. TcMC2. 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.lib has been included with TwinCAT NC PTP and higher since version 2.chm files and you must ‘UnBlock’ them before they can be opened.lib is required.VIII. This library is provided as a supplement to TwinCAT and must be purchased. however no indication of when this might occur has been given. The current publication from the VDI is geared toward mechanical cams and is only published in Deustch. with the new MC2 PLC Open Standard This document is mostly compiled with information and screen shots directly from the Beckhoff Information System version 01/2010.10 build 1340. Preface Creation of Cam Tables with or without TC Cam Design Tool. The registration form must have a valid email address and the requested version can be selected at the bottom of the form. but can also be evaluated for 30 days by entering ‘DEMO’ when asked for a product key. After ‘submitting’ the information a link to download the requested version will be emailed to the email address provided. The current version can be downloaded from here. The TwinCAT Cam Design Tool must be purchased. This document covers a brief introduction to the new TcMC2 library. 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. If you prefer not to download and install the Beckhoff Information System you can also access it on the web. The use of Motion Functions as defined by the VDI 2143 Guidelines is covered in the document. 305 Chapter: Camming . and its differences from the previous TcMC library. as defined by PLCopen. 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. To download the TwinCAT development software please go here.lib Note: these are . however the functions themselves are not covered. Camming 34. This library is required for all camming functionality. the programming PC and the control PC. This makes adaptation of target position or travel speed during the movement much easier. Users maintaining existing projects are advised to continue using the original TcMC library for these projects. On remote programmable controls. It enables transition of two travel commands with a defined velocity at a certain position.PLCopen.Lib a. Compatibility The TcMC2 motion control library contains enhanced and new functions. Move commands can be followed by further Move commands during execution. The function blocks are better adapted to the requirements of the PLCopen specification and are not compatible with the first version (TCMC). both systems. Windows CE systems must have installed an image from version Windows CE 3.org).08. must have installed an appropriate version. Intro to TcMC2.35.10 build 1340. 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. 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. 306 Chapter: Camming . TwinCAT Version The TcMC2 library is available from TwinCAT version 2. 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. e.g. An exception of this rule is. After Execute is reset to FALSE. MC_Stop sets Done to TRUE as soon as the axis is in standstill. for example. ErrorID and CommandAborted are reset with a falling edge at input Execute. If an axis is scaled in millimeters. since the axis is locked. which ensure defined processing through the PLC program. Busy and Active stay TRUE. if the function block is not active (Busy=FALSE). InVelocity. i. Exclusivity of the outputs The outputs Busy. InSync. the last value transferred to this block remains valid. the following units are used: Velocity [mm/s]. If an input parameter is not transferred to the function block. A meaningful default value is used for the first call. When the Execute input becomes TRUE.General rules for MC function blocks For all MC function blocks the following rules apply. Position and Distance are specified in technical units. Input parameters The input parameters are read with rising edge at Execute. Acceleration [mm/s2]. Error and CommandAborted are mutually exclusive. MC_Stop. one of the outputs must become TRUE. Similarly. Error. deceleration [mm/s2]. [mm] or [°]. a falling edge at Execute has no influence on the command execution. according to the axis scaling. only one of the outputs Active. Dynamic parameters The dynamic parameters for Move functions are specified in technical units with second as time base.e. Resetting Execute during command execution ensures that one of the outputs is set at the end of the command for a single PLC cycle. Done and CommandAborted can be TRUE at any one time. However. InGear. If Execute is triggered more than once while a command is executing. Position and Distance The Position input denotes a defined value within a coordinate system. the function block will not execute further commands and will not provide any feedback. jerk [mm/s3]. the axis is released and Busy as well as Active are reset to FALSE. Initial state The outputs Done. only one of these outputs can be TRUE at a function block at any one time. Only then are the outputs reset. while Distance is a relative measure for the distance between two positions. Chapter: Camming 307 . Error. Done. They are reset automatically when the Execute input is reset. etc. The status Busy=TRUE and Active=FALSE means that the command is not or no longer executed. Enable input and Valid output Chapter: Camming In contrast to Execute. MC_ReadStatus cyclically updates the status of an axis.g. for example. incorrect parameterization). Communication errors (the function block cannot address the axis. An axis error must be reset through MC_Reset. Function block errors do not have to be reset explicitly. The outputs Done. the Active output of each block indicates that the axis executes the command. an error in the logical NC axis. a separate reset mechanism may be required (e. Behavior of the Busy output The Busy output indicates that the function block is active. In many cases axis errors and drive errors can be reset together through MC_Reset. Axis errors (logical NC axis) usually occur during the motion (e. Depending on the drive controller. Busy is immediately set with a rising edge at Execute and is only reset when the command was completed successful or unsuccessfully.) is set when a command was executed successfully. It depends on the unique. the Enable input results in an action being executed permanently and repeatedly. Error indicates the error. Behavior of the Done output The Done output (or alternatively InVelocity.e. A reset is not possible. As long as Busy is TRUE. A function block with an Enable input indicates through the Valid output that the output data is good. the Done output for the first block is not set. 308 .g. InVelocity. If several function blocks are used for an axis and the running command is interrupted through a further block. The data is updated continuously while Valid is TRUE. Behavior of the CommandAborted output CommandAborted is set if a command is interrupted through another block. for example). if Busy is FALSE. not the axis (e. The error type is not specified explicitly. as long as Enable is TRUE. as long as Enable is TRUE. system-wide error number. InGear and InSync indicate successful command execution and are not set if Error becomes TRUE. The function block can only be triggered again after the configuration was corrected. Error types Function block errors only related to the function block. InSync. Errors of different type are signaled at the function block output. i.g. They cause the axis to switch to error status. connection of a reset line to the control device). the function block must be called cyclically for the command to be executed. Communication errors usually indicate incorrect configuration or parameterization. following error). Behavior of the Active output If the axis movement is controlled by several functions.Error handling All function blocks have two error outputs for indicating errors during command execution. Drive errors (control device) may result in an axis error. ErrorID contains a supplementary error number. InGear. The block can only be triggered with a rising edge at Execute. In non-queued mode a subsequent command leads to termination of a running command. but passes through this position with the higher velocity of two commands. infrequently required options. BlendingPrevious: The command is executed after no other command is running on the axis. BufferMode can specify that a command interrupts another command (nonqueued mode) or that the following command is only executed after the previous command (queued mode). In contrast to Buffered the axis does not stop at the previous target. BlendingLow : The command is executed after no other command is running on the axis. but passes through this position with the velocity of the first command. For the basic block function these options are often not required. The following command is started from standstill. This is referred to as Blending. The user only has to populate the Options data structure in cases where the documentation explicitly refers to certain options. Buffered : The command is executed after no other command is running on the axis. In this case just Buffer-Mode Aborting can be used. Chapter: Camming Slave Axes Motion commands like MC_MoveAbsolute can be passed to slave axes if they are explicitly enabled in the axis parameters. it becomes active and interrupts the running and an already queued command. In queued mode a subsequent command waits until a running command is completed. A motion command will then decouple the axis and move it afterwards. the command started last for queuing is rejected with an error. If the last command is started in non-queued mode (Aborting). Only one command is queued while another command is executed.BufferMode Some function blocks have a BufferMode input for controlling the command flow with several function blocks. Options input Many function blocks have an Options input with a data structure containing additional. but passes through this position with the velocity of the last command. In contrast to Buffered the axis does not stop at the previous target. 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. so that the input can remain open. For example. 309 . If more than one command is triggered while a command is running. BlendingNext : The command is executed after no other command is running on the axis. BufferModes Aborting : Default mode without buffering. which specifies the velocity at the transition point. The command is executed immediately and interrupts any other command that may be running. but passes through this position with the lower velocity of two commands. The previous movement continues until it has stopped. In queued mode BufferMode can be used to specify the movement transition from one command to the next. In contrast to Buffered the axis does not stop at the previous target. In this case the previous command sets the CommandAborted output. Migration from TcMC to TcMC2 The main differences and modifications between the TcMC motion control library and the extended TcMC2 library are listed here. 310 Chapter: Camming . Axis data structure In the past an axis required two data structures for cyclic data exchange with the NC.SetPos Please note that the sub elements for the NcToPlc and PlcToNc structures now have English names in view of the international market. the NCTOPLC_AXLESTRUCT data structure was transferred at the Axis input. the current set position for an axis is no longer referred to as fPosSoll.NcToPlc. In most function blocks. An existing project generally accesses the content of the NcToPlc structure.fPosSoll TcMC2 : Axis1. For example. Axis1: AXIS_REF. so that the effort for converting an existing project can be estimated. which is transferred to each MC function block. Certain function blocks. The structure contains the cyclic input and output data for the NC plus additional status information. PlcToNc_Axis1 AT %Q* : PLCTONC_AXLESTRUCT. In the TcMC2 environment the axis structure was extended so that all required data are included in a single structure. NcToPlc_Axis1 AT %I* : NCTOPLC_AXLESTRUCT. Example: TcMC : NcToPlc_Axis1. including MC_Power. The data are also available in the Axis1 structure and can be used to adapt the application program. expected an additional PLCTONC_AXLESTRUCT structure.b. but as SetPos. including MC_MoveAbsolute. MC_SetPosition can be used in relative mode (Mode=TRUE). These modifications generally only require little migration effort. If started in motion.. the block will behave like 311 Chapter: Camming . The main new feature is support for MC_BufferMode in Move blocks.. Motion commands like MC_MoveAbsolute can be passed to slave axes if they are explicitly enabled in the axis parameters (from TwinCAT 2.11). In this case just Buffer-Mode Aborting can be used. The new function block sets both. MC_OrientedStop MC_MoveModulo MC_MoveModulo can be executed from standstill or in motion. the blocks now also support a Busy and Active output. MC_MoveAbsoluteOrRestart MC_Move. A motion command will then decouple the axis and move it afterwards. TcMC MC_GearInFloat TcMC2 MC_GearIn Remark MC_GearIn now accepts the gear ratio as a floating point value The new BufferMode enables each Move block to be used to assign a new target for the axis or change the velocity.. In addition. The NewPos function blocks are therefore no longer required. MoveAbsoluteOrRestart can be replaced with two instances of a Move block (see BufferMode). Setting and resetting of the reference flag (axis is referenced) can be achieved with the MC_Home block. The following table contains a list of blocks with more extensive modifications. actual and set position. MC_CamIn MC_CamInExt MC_CamIn MC_SetReferenceFlag MC_Home MC_SetPositionOnTheFly MC_SetPosition MC_SetActualPosition MC_SetPosition MC_GearOutExt MC_Move. The input configuration was adapted accordingly. To set an axis position on the fly.. MC_SetActualPosition can be replaced with MC_SetPosition.Function blocks The input and output configuration of the function blocks has changed slightly compared with TcMC... MC_NewPos MC_NewPosAndVelo MC_Move. The new MC_CamIn function block deals with the function of the extended MC_CamInExt block. MC_OrientedStop MC_Stop MC_Halt. 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. TcNC library The previous TcMC library required declarations and functions from the TcNC library. MC_Stop MC_Halt stops the axis in a normal operation cycle. the TcNC library can still be used for compatibility reasons. MC_Stop is only used in a particular condition when the axis must be locked against further motion. Nevertheless. so that this was always integrated in a project. 312 Chapter: Camming . Status information In existing motion applications axis status information was often determined via a function call (AxisHasJob(). AxisIsMoving() etc. 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. Current status information is then available at any point in the program during the PLC cycle.). While these functions can still be used if the TcNC library is integrated.ReadStatus action at the start of the PLC cycle. However. 313 Chapter: Camming . this data must be updated cyclically by calling the function block MC_ReadStatus or an Axis1.c. and there are no uncertainties due to interpolation. A motion function is a singlecolumn table of interpolation points. Here the table contains a certain number of prescribed reference points. one which cannot be described by a simple mathematical formula. Axes can be coupled together in the TwinCAT NC PTP. each point between the interpolation points are precisely defined through the mathematical function. a motion function requires only very few interpolation points. but a complete description of the shape of the curve within a section (segment) of the cam plate. Each interpolation point not only contains a position. 314 Chapter: Camming . A master axis is then actively controlled. Using this procedure. and the NC interpolates position and speed between them. Two types of cam plates are supported. the points of a motion function can be manipulated at run time. The TwinCAT NC PTP offers the possibility of coupling a slave axis to a master axis by means of a table (electronic cam plate). Unlike a standard table. The associated slave position is determined from the second column using the interpolation points of the table. is specified up to the next interpolation point in the form of a mathematical function. Position jumps are thus avoided. Despite this. the shape of the function. ascending from a minimum position value to a maximum value. Such a dependency can be described by means of a table that specifies an associated slave position for every master position. When to use a Cam Table a. The system ensures that a manipulation only becomes effective once an alteration has no direct influence on the slave. Some applications require a more complex coupling of master and slave. In addition to the master and slave position at the start of the segment.36. One option is a cam plate in the form of a 2-column table containing master and slave positions (standard table). and the position of one or more coupled slave axes is synchronously controlled by the NC. Another option is to define a cam plate as a so-called motion function. for example. Values between these points are interpolated. The master column defines interpolation points via the travel path of the master. Overview In many applications it is necessary to synchronize two or more axes. The TcMC2_Camming library contains function blocks for handling cam plates. The simplest type of coupling is linear coupling with a fixed ratio of transmission (an electronic gearbox). Gearing With a 1:1 gear Ratio the two axes will move the tooling at a 45 degree angle. With a 3.b.6:1 gear ratio the axes will move the tooling in a diagonal line as seen below. 315 Chapter: Camming . 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. The cam table allows you to specify any point for the slave to be at any position of the master. So gearing works well for linear changes but not arbitrary changes. 316 Chapter: Camming .c. Linearly Increasing Gear Ratio (Dynamic) Dynamically changing the gear ratio by a fixed increment each PLC cycle will create a curve. The math for any other curve is long and complicated. 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. 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. For example if at 360 degrees both slave and master must be at 360 degrees. if the ratio is changed too early or too late the target position will not be reached. but when the master reaches 720 the slave must be at 1080. The key behind the cam table is that it is used when the slave position relative to the master position is critical. This can be accomplished by having the gear ratio doubled. In the below graph the Master is moving along the X-Axis from left to right. Cam tables can be made cyclical so that they repeat. If Motion Functions are used then TwinCAT will use the VDI 2143 Motion Function standard to calculate a curve between the points. Return. Additionally the type of points can be selected. 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. 317 Chapter: Camming . Slave positions can be defined in the forward direction of the Master and TwinCAT will do the math for you. and Movement. If only the points are defined on the table then TwinCAT will calculate a straight line from one point to the next. The Slave is moving along the Y-Axis from bottom to top. Typically Polynomial 5 will be used. 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. typically a rotary axis will be the master and after every 360 degrees of the Master the Cam Table will repeat. Cam Table With a Cam Table. As the Master position increases from 0 to 100 the Slave axis moves from 0 to 100.d. these include Rest. Velocity. (* Y'' *) SlaveJerk : LREAL. implemented. The description includes the point itself. the individual points.37. MasterPos : LREAL. (* X *) SlavePos : LREAL. Additionally the table type must be defined. RelIndexNextPoint : MC_MotionFunctionPoint_ID. adjusted. The data structure MC_MotionFunctionPoint describes an interpolation point of a motion function.10 Build 1340 or Higher TcMC2_Camming. In order to provide more flexibility. Motion Function Points define the points on the table and the associated Motion Function to be used with that point. (* Y' *) SlaveAcc : LREAL. and the properties of those points. (* Y *) SlaveVelo : LREAL. TYPE MC_MotionFunctionPoint : STRUCT PointIndex : MC_MotionFunctionPoint_ID. FunctionType : MC_MotionFunctionType. and used directly from the PLC. Defining the Points on the Cam Table i. Creating a Cam Table with Function Blocks Prerequisites: TwinCAT NC PTP 2. This table ID will be used by the programmer to reference the Cam Table when creating and/or selecting it for use. a definition of the function type and a relative pointer to the end point of the motion function segment. b. Each Cam Table will have a unique TableID from 1 to 255. 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.lib (From the TwinCAT NC Camming Supplement) a. Overview By the use of the TcMC2_Camming library a cam table can be created. Motion Function Point A motion function point describes a start point of a motion function. A motion function is a one-dimensional list (array) of type MC_MotionFunctionPoint. PointType : MC_MotionPointType. 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. The use of the CamIn procedure will couple the slave axis to the master axis with the given TableID as a reference. (* Y''' *) END_STRUCT END_TYPE 318 Chapter: Camming . (* Turn point *) MOTIONPOINTTYPE_MOTION := 16#0008. Notes: The first point in a list must start AT any index > 0. MOTIONFUNCTYPE_POLYNOM1 := 1. FunctionType: Type definition for motion functions. The point index of all interpolation points must increase strictly monotonously and must have no gaps and be greater than 0. MOTIONFUNCTYPE_POLYNOM5_MM := 15. TYPE MC_MotionFunctionType : ( MOTIONFUNCTYPE_NOTDEF. (* Adding of segments *) MOTIONPOINTTYPE_ACTIVATION := 16#2000 (* 1: activation point *)). 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) *)). 319 Chapter: Camming . MOTIONFUNCTYPE_POLYNOM3 := 3. PointType: Type MC_MotionPointType of this interpolation point. (* Ignore point *) MOTIONPOINTTYPE_REST := 16#0001. Type MC_MotionFunctionType of the mathematical function between this and the subsequent interpolation point. TYPE MC_MotionFunctionPoint: ( MOTIONPOINTTYPE_IGNORE. MC_MotionFunctionPoint_ID is of type UDINT. Notes: The type Automatic motion function type used in the TwinCAT Cam Design Editor corresponds to MOTIONFUNCTYPE_POLYNOM5_MM. END_TYPE RelIndexNextPoint: Relative reference to the subsequent interpolation point (usually 1). MOTIONFUNCTYPE_POLYNOM5 := 5. (* Velocity point *) MOTIONPOINTTYPE_TURN := 16#0004. (* Motion point *) MOTIONPOINTTYPE_ADD := 16#0F00. (* Rest point *) MOTIONPOINTTYPE_VELOCITY := 16#0002.PointIndex: Absolute index of this interpolation point within the motion function. All following points in the list add 1 to the PointIndex. SlavePos (*Point 4*) VM_MotionFunctionPoints[4].FunctionType VM_MotionFunctionPoints[3]. 1. 1.PointType VM_MotionFunctionPoints[2]. 45.FunctionType := 15.RelIndexNextPoint := 1.PointType VM_MotionFunctionPoints[3].PointIndex VM_MotionFunctionPoints[4].PointIndex VM_MotionFunctionPoints[3].RelIndexNextPoint VM_MotionFunctionPoints[2]. 320 Chapter: Camming := := := := := := 4. VM_MotionFunctionPoints[1]. 150. Point3 Point4 X--------X / \ / \ / \ / \ ------X--------X Point1 Point2 X-------------X Point5 Point6 (*Point 1*) VM_MotionFunctionPoints[1]. 1. VM_MotionFunctionPoints[1]. 15. (*MOTIONPOINTTYPE_REST*) VM_MotionFunctionPoints[1].SlavePos := := := := := := 2.PointType VM_MotionFunctionPoints[4].MasterPos VM_MotionFunctionPoints[4]. .FunctionType VM_MotionFunctionPoints[4]. := := := := := := 3.ii. Sample Code: Below is a really bad graphical representation of the Points on the Cam Table below. 1. (*1 = Increment PointIndex by 1 to get to Next Point. (*Point 2*) VM_MotionFunctionPoints[2]. must be 0 for the last point on the table*) VM_MotionFunctionPoints[1]. 0.SlavePos := 0. 1.PointType := 1.MasterPos := 0. 150.PointIndex VM_MotionFunctionPoints[2]. 1. 15.FunctionType VM_MotionFunctionPoints[2]. (*MOTIONFUNCTYPE_POLYNOM5_MM*) VM_MotionFunctionPoints[1].MasterPos VM_MotionFunctionPoints[2].SlavePos (*Point 3*) VM_MotionFunctionPoints[3].RelIndexNextPoint VM_MotionFunctionPoints[4].MasterPos VM_MotionFunctionPoints[3]. 60. 30.RelIndexNextPoint VM_MotionFunctionPoints[3].PointIndex := 1. 15. FunctionType VM_MotionFunctionPoints[5]. 0.SlavePos (*Point 6*) VM_MotionFunctionPoints[6]. 360. 321 Chapter: Camming . 15. 75. 0.PointIndex VM_MotionFunctionPoints[5]. 1.PointIndex VM_MotionFunctionPoints[6].(*Point 5*) VM_MotionFunctionPoints[5]. 15. 1.MasterPos VM_MotionFunctionPoints[5]. 0. := := := := := := 6.FunctionType VM_MotionFunctionPoints[6].PointType VM_MotionFunctionPoints[5].PointType VM_MotionFunctionPoints[6].RelIndexNextPoint VM_MotionFunctionPoints[6].RelIndexNextPoint VM_MotionFunctionPoints[5].SlavePos := := := := := := 5.MasterPos VM_MotionFunctionPoints[6]. 1. or MC_TABLETYPE_NONEQUIDISTANT it the distance is variable. b. ArraySize : Storage capacity of the two-dimensional array. Chapter: Camming 322 . Example 1: Position table structure description pArray: Address of a two-dimensional array. MC_CAM_REF TYPE MC_CAM_REF : STRUCT pArray ArraySize TableType NoOfRows NoOfColumns END_STRUCT END_TYPE : : : : : UDINT.. The address can be assigned with the ADR function. MC_TableType. UDINT. i. The number of rows is entered in the component NoOfRows.38. The first column contains an ascending list of master positions.360. pArray := ADR( Table1 ). The data structure depends on the table type TableType. size. UDINT. NoOfRows: The number or rows corresponds to the number of table points. The second column contains the associated slave positions. Example: Table1 : ARRAY[0. The first parameter pArray is a pointer to a data structure containing the cam plate data. which can be determined with the SIZEOF function. Example: ArraySize := SIZEOF( Table1 ). the number of columns in NoOfCols (usually 1 or 2). if the master positions have the same distance. NoOfColumns: The number of columns is 2. and table type. UDINT. The data structure MC_CAM_REF describes the data memory of a cam plate in a further PLC variable (array). 0.. TableType: The table type is MC_TABLETYPE_EQUIDISTANT. Defining the Cam Table in the PLC a. Overview Within the PLC a Cam Table can be defined by providing a starting memory location.1] OF LREAL. The address can be assigned with the ADR function. NoOfRows: The number or rows corresponds to the number of table points... 323 Chapter: Camming .1] OF LREAL.ii. 0. ArraySize : Storage capacity of the one-dimensional array. The second column contains the associated slave positions. Example 2: Structure description of a motion function pArray: Address of a two-dimensional array.360. which can be determined with the SIZEOF function. TableType: The table type is MC_TABLETYPE_MOTIONFUNCTION. Example: ArraySize := SIZEOF( MotionFunction ). pArray := ADR( Table1 ). Example: Table1 : ARRAY[0. The first column contains an ascending list of master positions. NoOfColumns: The number of columns is 1. 324 Chapter: Camming . size.6] OF MC_MotionFunctionPoint..TableType := MC_TABLETYPE_MOTIONFUNCTION. END_TYPE (* i.NoOfColumns := 1. CamTable_Slave. CamTable_Slave. (*MC_Cam_Ref contains the location. CamTable_Slave. and type of the Cam Table*) (*Provide MC_Cam_Ref with the data of the CAM Table*) CamTable_Slave. motion function calculated in runtime *) MC_TABLETYPE_MOTIONFUNCTION := 22 ).pArray := ADR(VM_MotionFunctionPoints). MC_TableType TYPE MC_TableType : ((* n*m tabular with equidistant ascending master values *) MC_TABLETYPE_EQUIDISTANT := 10. CamTable_Slave. (* n*m tabular with strictly monotone ascending master values (not imperative equidistant) *) MC_TABLETYPE_NONEQUIDISTANT := 11. (*The size of the Array determines the number of points in the Cam Table*) CamTable_Slave : MC_Cam_Ref.c.ArraySize := SIZEOF(VM_MotionFunctionPoints).NoOfRows := 6. Sample Code: (*Cam Table Data*) VM_MotionFunctionPoints : ARRAY [1. Inputs Execute: The command is executed with a rising edge at input Execute. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. ErrorID: If the error output is set. MC_CamTableSelect With the function block MC_CamTableSelect. Outputs Done: becomes TRUE.39. Creating the Cam Table a. this parameter supplies the error number. Error: Becomes TRUE. a table can be specified and loaded into the NC. the function block is ready for a new command. At the same time one of the outputs. as soon as an error occurs. b. if the cam plate was created successfully. simple coupling with MC_CamIn is sufficient. The block creates a new table and simultaneously fills it with data provided by the PLC. Done or Error. MasterAbsolute: Absolute interpretation of master positions. Input/Outputs Chapter: Camming Master: Axis data structure of the master Slave: Axis data structure of the slave CamTable: The data structure of type MC_CAM_REF describes the data storage for the cam plate in the PLC. 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. In this case. if a table created with the TwinCAT cam plate editor is to be used. When Busy becomes FALSE again. CamTableID: ID of the cam plate used for coupling. and the reference to the Cam Table. SlaveAbsolute: Absolute interpretation of slave positions. is set. Periodic: Periodic is TRUE if the cam plate is repeatedly cyclically. MC_CamTableSelect does not have to be used. 325 . CamTableID:=1 . SlaveAbsolute:=TRUE . Sample Code: (*Axes*) VM Slave (*Triggers*) bCamTableSel1 (*FB Error Info*) bErrorCamCreate iErrorIDCamCreate : : Axis_Ref. (*MC_CamTableSelect*) : : BOOL. 326 Chapter: Camming . : BOOL. Error=>bErrorCamCreate . UDINT. Done=> . Master:=VM . Periodic:= TRUE.i. fbMC_CamTableSelect1 : MC_CamTableSelect. Busy=> . Slave:=Slave . (*Create the Cam Table*) fbMC_CamTableSelect1( Execute:= bCamTableSel1. Axis_Ref. MasterAbsolute:=TRUE . ErrorID=>iErrorIDCamCreate ). CamTable:=CamTable_Slave . right click on Tables and select Append Table… Leave the defaults and select OK. Overview Without a license for the TwinCAT Cam Design Tool. 327 Chapter: Camming . and then corresponding changes can be made to the PLC code. Importing a Cam Table for Verification a. the Cam Table created by the PLC can be viewed but changes will not be saved. Creating a Blank Table Under the NC-Configuration. Once the Cam Table has been uploaded changes can be made to tweak the table. b.40. Right click on Master 1 and select Append Slave… Leave the defaults and select OK. Select OK. 328 Chapter: Camming .If you do not have a license for the Cam Design Tool you will receive the following message. 329 Chapter: Camming .You should now see an empty Cam Table. c. 330 Chapter: Camming . If it does not match then right click on the Slave and select Change ID. Importing the Cam Table On the Slave Tab verify that the Table ID matches the Table ID used in the PLC program. 331 Chapter: Camming . After verifying the Table ID. select Upload.Change the ID: and select OK. Leave the defaults and select OK. Your Cam Table should now look like the following. 332 Chapter: Camming . 0. verified. BufferMode : MC_BufferMode. b. in particular the time or position. StartMode can be relative or absolute for master (X coordinate) and slave (Y coordinate). Inputs VAR_INPUT Execute : BOOL. and created. Camming the two Axes together a.Status. MC_CamIn The function block MC_CamIn activates master-slave coupling with a certain cam plate.CamTableQueued can be used to check whether a cam plate is queued for switchover. In addition it is possible to switch to a new cam plate in coupled state. can be specified. END_VAR Chapter: Camming Execute: The command is executed with a rising edge at input Execute MasterOffset: Offset to the master position of the cam plate SlaveOffset: Offset to the slave position of the cam plate MasterScaling: Scaling of the master position of the cam plate StartMode: StartMode determines whether the cam plate position is interpreted absolute or relative to the coupling position. 333 . MasterOffset : LREAL. the two axes are now ready to be cammed together.0. Options : ST_CamInOptions. Overview Once the Cam Table has been defined. CamTableID : MC_CAM_ID.41. The switching rules. SlaveScaling : LREAL := 1. MasterScaling : LREAL := 1. The status flag Axis. StartMode : MC_StartMode. SlaveOffset : LREAL. if the coupling was successful and the cam plate is active. as soon as an error occurs. For cam plate switching Active becomes TRUE. this parameter supplies the error number. ActivationPosition: Optional master position at which a cam plate is switched. 334 Chapter: Camming . When Busy becomes FALSE again. At the same time one of the outputs. 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. AXIS_REF. If the cam plate is activated depending on the ActivationMode. the position refers to the non-scaled cam plate. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. BOOL. Active becomes FALSE and InSync is set. InSync. Inputs/outputs VAR_IN_OUT Master Slave END_VAR : : AXIS_REF. is set. if the command could not be fully executed. the function block is ready for a new command. BOOL. BOOL. END_VAR BOOL. If the position in the application refers to the scaled cam plate.) If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used. Not required for motion functions Outputs VAR_OUTPUT InSync : Busy : Active : CommandAborted : Error : ErrorID : UDINT. Error: Becomes TRUE.CamTableID: ID of the cam plate used for coupling BufferMode: currently not implemented Options: Data structure with further coupling and switching options: ActivationMode: ActivationMode specifies the switching time or position at which cam plate coupling or switchover takes place. BOOL. Active: Active indicates that the command is executed. CommandAborted or Error. The axis may have become decoupled during the coupling process (simultaneous command execution). if the coupling command was executed successfully but the cam plate is still queued. CommandAborted: Becomes TRUE. depending on the ActivationMode. ActivationMode can also be specified when a slave is coupled for the first time. InSync: Becomes TRUE. it can be divided by the MasterScaling before the function block is called. ErrorID: If the error output is set. (not required for first coupling. StartMode:=MC_STARTMODE_ABSOLUTE . CamTableID:=1 . MasterOffset:= . Slave:= Slave. MasterScaling:= . BufferMode:= . Options:= . SlaveScaling:= . 335 Chapter: Camming . Sample Code: (*Couple the Axes using the Cam Table*) fbMC_CamInSlave( Execute:=bExectueCamInSlave . Master:=VM . Active=> . CommandAborted=> . Error=>bErrorCamIn . Busy=> . ErrorID=>iErrorIDCamIn ). SlaveOffset:= . InSync=> .i. At the same time one of the outputs. is set. Although the point before and after the current Slave position cannot be adjusted every other point can be. Inputs VAR_INPUT Execute CamTableID PointID END_VAR : BOOL. CamTableID: ID of the loaded table. if the data were written successfully. : MC_MotionFunctionPoint_ID. Done or Error. the function block is ready for a new command. : BOOL.42. Execute: The command is executed with rising edge. as soon as an error occurs. END_VAR 336 Chapter: Camming Done: Becomes TRUE. Overview While the Cam Table is in operation it may be necessary to adjust the location and/or properties of the points. Error: Becomes TRUE. MC_WriteMotionFunctionPoint The function block MC_WriteMotionFunctionPoint can be used to write the data of a motion function interpolation point. b. PointID: Point ID of the first point of the motion function to be read. : MC_CAM_ID. : BOOL. The way the change is to be implemented can also be defined. this parameter supplies the error number . : UDINT. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. ErrorID: If the error output is set. When Busy becomes FALSE again. Outputs VAR_OUTPUT Done Busy Error ErrorID END_VAR : BOOL. Changing a table point via the PLC a. Inputs/Outputs VAR_IN_OUT Point : MC_MotionFunctionPoint. If the position in the application refers to the scaled cam plate. (MC_CamActivationMode) ActivationPosition: Optional master position at which scaling is carried out (depending on ActivationMode). written but not yet activated). This function specifies the activation mode for modifications but does not affect a change or changeover of cam plates. 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.e. The function block MC_SetCamOnlineChangeMode is used to specify when and how these changes take effect. If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used. it can be divided by the MasterScaling before the function block is called. The status flag Axis. : MC_CamScalingMode. : MC_CamActivationMode.Point: Data structure containing the data of a motion function interpolation point Motion Function Point: Refer to Creating a Cam Table with Function Blocks c.CamDataQueued can be used to check whether data has been queued (i. Inputs VAR_INPUT Execute ActivationMode ActivationPosition MasterScalingMode SlaveScalingMode CamTableID END_VAR : BOOL. : LREAL. . : MC_CamScalingMode. The set mode affects all subsequent write operations. Cam plate can be modified at run time via the PLC (see MC_WriteMotionFunction. the position refers to the non-scaled cam plate. : MC_CAM_ID. ActivationMode: Defines when and how scaling takes place. MC_WriteMotionFunctionPoint). 337 Chapter: Camming Execute: The command is executed with rising edge. It is therefore not necessary to call the block before each write access. If activation of the data is to be delayed until the master reaches a certain position.Status. the system will initially queue the written data and activate them at the master position. ErrorID: If the error output is set. (MC_CamScalingMode) SlaveScalingMode: Type of slave scaling. Done: Becomes TRUE.MasterScalingMode: Type of master scaling. the function block is ready for a new command. as soon as an error occurs. When Busy becomes FALSE again. : BOOL. Error: Becomes TRUE. is set. (MC_CamScalingMode) CamTableID: Table ID. if the data were written successfully. : UDINT. : BOOL. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. At the same time one of the outputs. this parameter supplies the error number 338 Chapter: Camming . Outputs VAR_OUTPUT Done Busy Error ErrorID END_VAR : BOOL. Done or Error. d. Data are queued if the change was requested at a certain master position or at the end of the cycle. If the position in the application refers to the scaled cam plate. modification of the cam plate data. (* instantaneous change *) MC_CAMACTIVATION_ATMASTERCAMPOS. END_TYPE MC_CamActivationMode specifies the timing and type of change for a cam plate. MC_CAMACTIVATION_NEXTCYCLE: For a cyclic cam plate. MC_CamActivationMode TYPE MC_CamActivationMode : ( MC_CAMACTIVATION_INSTANTANEOUS. MC_CAMACTIVATION_ATMASTERCAMPOS: The change takes effect at a certain cam plate position (master position within the cam plate). In both cases the following modes are possible: MC_CAMACTIVATION_INSTANTANEOUS: The change takes effect immediately. for example. it can be divided by the MasterScaling before the function block is called. MC_CAMACTIVATION_OFF: Changes in cam plate data are ignored. 339 Chapter: Camming . the change takes effect at the transition to the next period. (* 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 *) ). activation is valid for one cycle only *) MC_CAMACTIVATION_ASSOONASPOSSIBLE. 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). or switching of cam plates. MC_CAMACTIVATION_ATMASTERAXISPOS: The change takes effect at a certain absolute position of the master axis. Changes can be affected through scaling. (* modify the data at a defined master position referring to the cam tables master position *) MC_CAMACTIVATION_ATMASTERAXISPOS. (* modify the data at the beginning of the next cam table cycle *) MC_CAMACTIVATION_NEXTCYCLEONCE. (* modify the data at a defined master position referring to the absolute master axis position *) MC_CAMACTIVATION_NEXTCYCLE. MC_CAMACTIVATION_ASSOONASPOSSIBLE: Modified cam plate data take effect as soon as system dynamics allow. MC_CAMACTIVATION_DELETEQUEUEDDATA : Queued cam plate data are deleted. The command must be issued ahead of this position. The position refers to the non-scaled cam plate. The command must be issued ahead of this position. (* Not Yet Implemented! Modify the data at the beginning of the next cam table cycle. := := := := := := 5. 75. SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET . Error=> bErrorChangeMode_1st. 1. ErrorID=>iErrorIDWritePoint_1st ). CamTableID:=1 . (*Use new Data for Point 5*) fbMC_SetCamOnlineChangeModeTable1_1st( Execute:= TRUE . Error=>bErrorWritePoint_1st . Busy=> . 15.PointType VM_MotionFunctionPoints[5]. Point:=VM_MotionFunctionPoints[5] .MasterPos VM_MotionFunctionPoints[5]. CamTableID:=1 . 75. 1. MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET . PointID:=5 . Done=> .i.RelIndexNextPoint VM_MotionFunctionPoints[5]. Sample Code: (*New data for point 5 of the Cam Table*) VM_MotionFunctionPoints[5].FunctionType VM_MotionFunctionPoints[5]. ErrorID=>iErrorIDChangeMode_1st ). ActivationPosition:=370 . Done=> . 340 Chapter: Camming . ActivationMode:=MC_CAMACTIVATION_ATMASTERAXISPOS .SlavePos (*Buffer the Data for Point 5*) fbMC_WriteMotionFunctionPoint5_1st( Execute:=TRUE . Busy=> .PointIndex VM_MotionFunctionPoints[5]. PointType VM_MotionFunctionPoints[5]. ActivationMode:=MC_CAMACTIVATION_ATMASTERAXISPOS . ErrorID=>iErrorIDWritePoint_2nd ). 1.PointIndex VM_MotionFunctionPoints[5]. 1. Error=>bErrorWritePoint_2nd .RelIndexNextPoint VM_MotionFunctionPoints[5].SlavePos (*Buffer the Data for Point 5*) fbMC_WriteMotionFunctionPoint5_2nd( Execute:=TRUE . 75. PointID:=5 .MasterPos VM_MotionFunctionPoints[5]. Done=> . MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET . Point:=VM_MotionFunctionPoints[5] . (*Use new Data for Point 5*) fbMC_SetCamOnlineChangeModeTable1_2nd( Execute:= TRUE . Done=> . CamTableID:=1 .FunctionType VM_MotionFunctionPoints[5]. := := := := := := 5. Busy=> . SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET . 341 Chapter: Camming .(*New data for point 5 of the Cam Table*) VM_MotionFunctionPoints[5]. ActivationPosition:=730 . Error=> bErrorChangeMode_2nd. CamTableID:=1 . 0. 15. ErrorID=>iErrorIDChangeMode_2nd ). Busy=> . 6). The first column (with the exception of the header line) contains the master positions. 342 Chapter: Camming . There are no separating characters between the data. (This might be greater in newer versions) A position table is a 2D array that provides a slave position relative to the master position. Most 2D tables contain at least 1000 points and are commonly generated by 3rd party software using a mathematical formula (similar to a motion function) to create a table of 1000+ points. A table consists of a header (the first line) and the table data (the remaining lines). There are no separating characters between the data. Table can be read from an ASCII file but you have to parse the file. The header contains two numbers of type unsigned short. The downside of a position table is that the segments between defined points are calculated in a straight line between the points. The quantity of data is restricted to 64 KB (TwinCAT Version 2. while the second column contains the associated slave positions (both in mm).43. Therefore the more points on the table the shorter the segments and the better the motion. while the second column contains the number of columns (for table-slave tables this is always 2). Position Tables a. Position Tables General Table Conventions Tables only contain binary data. The first column contains the number of lines (without header). the table only contains data of type double. Motion Functions vs. Apart from the header. 343 Chapter: Camming . The values highlighted in red are the defined points.Below are the points generated by using Motion Functions from our above sample code. If this was a table of points the Slave axis values would increase linearly. The values highlighted in yellow are the master. among others. can be used (for cam examples see: Cam design tool examples). can now simply and clearly be defined and modified from the PLC. i.e. either the position tables or the motion function points are generated when the configuration is activated. The resulting dynamic limit values ultimately depend on the motion of the master and relate to constant master velocity. Meff) in the torque/speed diagram of the motor. Subsequently. Very flexible cams can thus be realized. 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. but also individual segments or subsections. The realization of motion laws in the NC has a further crucial advantage: A motion diagram.b. Unlike classic table couplings that only transfer discrete steps (scatter plots) in the form of larger data quantities to the NC. which the user has to analyze. i. for calculating the effective torque or the operating point PA (nm . The PLC can access the current characteristic values of the NC via function blocks. the system calculates characteristic values (such as maximum and minimum position values. the mean velocity and the effective acceleration are calculated. Motion Functions A motion function (MF) describes a cam disc via mathematical functions.).e. The characteristic values are thus calculated with the idealized assumption of constant master velocity. 344 Chapter: Camming .e. Problems originating from data granularity (position reference points) in the table are thus eliminated. In addition. Users can influence not only the complete motion description. for which different motion laws. Associated PLC function blocks make the application of this functionality very convenient. these points can subsequently be modified individually by the PLC. the complete information is stored in the NC in very compact form. The motion laws for mechanical cams are defined in VDI guideline 2143 and other documents. the complete description of the motion of a slave axis. In order to ensure that the drive system can actually implement a cam in practice. i. The electronic cams in TwinCAT use these functions. It is possible to modify individual values or complete sections of the motion functions online according to associated rules. while the cam is active. If motion functions are used. The motion functions realize these motion functions directly in the real-time driver of the NC. velocity and acceleration etc. for example. These values may be used. special mathematical functions. It sub-divides the curve into appropriate segments (sections). Point structure PointIndex FunctionType PointType RelIndexNextPoint MasterPos SlavePos SlaveVelo SlaveAcc SlaveJerk/Symmetry UINT32 Point index UINT16 Function type UINT16 Point type Relative index of the end point (default: 0. Definition of a Point The information contained in the cam design tool table is sufficient for defining the motion in the NC. In order to keep the definition simple for motion diagrams with simple interrelationships. These requirements lead a description that in addition to the starting point of a segment. The user therefore does not have to update this information. a relative index is used to refer to the point index of the end point of this segment. referred to as IGNORE below) at a later stage. for motion diagrams with simple interrelationships the end point of a section is identical to the starting point of the next segment. subsequently corresponds INT32 to 1) REAL64 Master position REAL64 Slave position at this reference point REAL64 Slave velocity at this reference point REAL64 Slave acceleration at this reference point Slave jerk at this reference point or symmetry value of the segments REAL64 for rest in rest motion laws In this structure. symmetry value). The possible point types of the cam design tool therefore includes the IGNORE point. Chapter: Camming 345 . In addition. although for a standard list with simple link the value should be ‘1’. also contains the segment information (function type. The more complex point types offered by the cam design tool. such as slide point. Because the motion is described in segments (sections). The default value of the relative point index may therefore be zero. The relative point index is therefore automatically adjusted internally. d. are not yet implemented. However. users want to be able to deactivate individual points in a particular motion diagram (MOTIONPOINTTYPE_IGNORE. point type). closer inspection of this MF table reveals the presence of redundant data.c. the IGNORE points are indeed ignored completely. including the point information (velocity. acceleration. 346 Chapter: Camming . These can be activated online at a later stage by specifying the associated values (point type not equal IGNORE).e. A Velocity point will have 0 acceleration and the velocity will be defined by the Cam Table or the user. Warning: The master position has to be either strictly monotonic rising or falling. A Turn point will have a velocity of 0. a=? v=?. a=0 v=0. A Motion point is the default type in which the velocity and acceleration will be calculated by the Cam Table. Otherwise it is rejected with an associated error message. a=0 v=?. Since no points can be added while the MF is active. and the acceleration will be calculated by the Cam Table or the user. 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=? At Rest the velocity and acceleration will be 0. the IGNORE point type enables associated points to be included. the user must remember that it is physics that sets the limits to the possible movement. The cam design editor is a flexible tool that provides the user with optimum support and only the minimum of restrictions. acceleration and jerk through the graphic display facilities. A cam design editor is integrated into TwinCAT. for instance. With all these options. the user is offered the best possible assistance for checking velocity. On the other hand. Therefore.44. under the Tables item. The user. Cam Design Tool a. 347 Chapter: Camming . Overview A cam design editor is used to design the movements for a cam plate. and it can be found in the System Manager under the NC Configuration. should carefully check whether the starting and end points correspond exactly to requirements. responsibility for the choice of parameters lies with the user. however. 348 Chapter: Camming .b. Creating a Cam Table Right click on Tables and select Append Table… Leave the defaults and select OK. If you then click the master in the structure tree. but also of the associated slaves. 349 Chapter: Camming . the property pages can be used to set the properties not only of the master.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. 350 Chapter: Camming . the co-ordinates of the points are displayed in the table window above it.the movement plan . The rough design of the movement . and it is only possible to delete existing points via the graph. however.The general procedure for developing a design of a cam is based on VDI (Verein Deutscher Ingenieure) Guideline 2143. they will show the same data. Following interactive graphic entry of the points in the graphic window.defines the starting and end points of the movement section.the co-ordinate values or their derivatives . 351 Chapter: Camming .can also be interactively manipulated in the table window. New points can only be inserted in the graph. The editor. does not make a distinction between the movement sketch and the movement diagram containing the detailed description of the movement. The properties of the points . The user's interface to the cam design editor is graphic. but also the velocity. 352 Chapter: Camming . The mode of the display can be changed by a right mouse click in the graphic window. acceleration and jerk can be displayed in the graphic area. which opens the following menu: Thus a separate Graphic Window is opened for each derivative.Not just the position. 353 Chapter: Camming . For a rotary Master. The normalized display refers these displays to the master position. If an equidistant table is to be generated. the choice between a linear and a rotary axis specifies whether the table type is linear or cyclic. to distinguish here between a linear and a rotary axis (angular values quoted in degrees). When the project is saved in the registry.csv file this option will either generate a straight line (Fixed Table) or calculate the points using the Motion Function. The Rounding Value rounds the master position in the graphic input with the given value. 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. it is necessary. if the starting and end positions of the slave correspond to the minimum and maximum positions of the master. the information required to generate and transfer the tables with this increment is created in the NC. the first and second derivatives at the end are set equal to the corresponding values at the start of the movement cycle. first of all. The velocity of the master is needed for the physically oriented display. Fixed Table / Motion Function: When exporting the cam table to a . The increment specifies the increment of the master position used for output of the table into a file. acceleration and jerk of the slave are shown against time.i. the total length (the actual maximum minus the minimum) should be divisible by the increment. When the data is transferred to the NC. according to the values. The master position increment is specified in the master's property page. 354 Chapter: Camming . The type of the spline still needs to be adjusted in the table.ii..255) for the table. Import allows files in the format just described to be read in. acceleration and jerk.. The values can then be displayed as cubic splines. velocity. on one line each.. Export allows the slave's values to be stored in an ASCII file in the form of master position. command. with the aid of which the table data is stored in the NC. The Rounding Value rounds the slave position in the graphic input with the given value. Adjustment to the current values in the diagram can be performed in the relevant graphic window with the Adjust to Extreme Values command. The Table Id provides a unique identifying number (1. It can be changed to using a right mouse click in the menu with the Change Id. slave position. These values can be used as initial specifications when the graphic window is first displayed. Slave Tab Maximum and minimum values can be specified for position. When the Overview Window is switched on. If you're using an IntelliMouse with a ScrollWheel you can zoom with the ScrollWheel. 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 scrollbar acts on all the graphic windows at the same time. 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.c. 355 Chapter: Camming . The horizontal and vertical Scrollbars can be used to shift the Graphic Section. but somewhat darker. All the horizontal scrollbars are synchronized. The current data can be read by switching the mode on and off. the information required to generate and transfer the tables is created in the NC. The Show Online Data displays the table data that is currently in the NC. This window also has a Horizontal Scrollbar if the Horizontal Scrollbar option is activated. as soon as Online Mode is switched on. When the project is saved in the registry (Activate Configuration). The data is displayed in the same color. The Cross on Point option causes the starting and end points of a movement section to be indicated by a cross. The data is automatically transferred by ADS. Currently this can result in a distorted display. 356 Chapter: Camming .The toolbar and its commands can be displayed or hidden via the menu that is opened by a right mouse click (in the graphic window). because the linear tables are displayed as natural splines (second derivative at the edges equals 0). with the associated table ID as a cubic spline. Polynom5. The symmetry of the functions can only be changed for the following types: Polynom3. Since movement sections are normally continuous. consideration should be given to the boundary conditions applying to the points. except for Slide Points.5. If certain values in the table cannot be changed. ModSinusline. 357 Chapter: Camming . Tables Window The values for the movement section are displayed in the table window: The values can be altered via the keyboard.d. Bestehorn. The boundary conditions limit the scope of the functions in sections in accordance with their type. if any inconsistencies are seen in the graph of a completed movement diagram. This value can be changed in the table or in the diagram of the acceleration (Example 6). the agreement of the initial and end points should be checked. In addition to this. Polynom8. remember that restrictions are applied arising from the choice of function type or other boundary conditions for the 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. Normally the inflection on the curve (acceleration = 0) at 50 % = 0. It may be appropriate to change them. Sinusline. and AccTrapezoid. Function Types In addition to the standard types (synchronous/automatic). additionally. T for Turn. there are the cubic splines. When the combo box. The types correspond to those of VDI Guideline 2143. As soon as another field in the table window is activated. V for Velocity. tangential and periodical. is first clicked. and M for Motion. either the rectangle for this one is shown. or no rectangle is displayed at all. Changing the type of spline at the first point implies that the spline type as a whole is changed. the boundary conditions (first derivative at the starting and end point) should be modified. Chapter: Camming 358 . with the boundary conditions of natural. or a field in the first column. with the initial and end points of the section at its corners. the function type can also be modified in the combo box. At the Motion functions with fit to boundary values the R is for Rest. If Spline Tangential is chosen as the spline type. a rectangle is temporarily shown in the position window. including that of the end point. which can be changed by command on the graph.i. Adjustment to the Extreme Values The window's coordinates are adjusted to the extreme values of the movement. Horizontal Shift Moves the selected point horizontally In the velocity window for synchronous functions: shift along a straight line in the position window. 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). The left-hand edge of the graphic area can be temporarily moved in this way. and these may be called up through the toolbars on the relevant graphic window: All these commands are only applicable to the associated window. Chapter: Camming 359 . Shift Moves the selected point. 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. Commands The cam design editor offers the following commands. 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).ii. so that the scale can be more easily read. as is the corresponding section. Delete Slide Point The slide point is deleted and the sections are joined together as they were previously. This restriction can mean that the end value of a section does not agree with the initial value for the following section. 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. 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. Reversal Point The selected point is defined as a reversal point (boundary condition: v=0). Velocity Point The selected point is defined as a velocity point (boundary condition: a=0).The following commands only apply in the graphic window for position: Insert Point Inserts a point at the cursor position. without changing the selected section. The point can then be moved on to the section using horizontal shift. a=0). Delete Point The selected point is deleted. Rest Point The selected point is defined as a rest point (boundary condition: v=0. Movement Point The selected point is defined as a movement point (no boundary conditions). 360 Chapter: Camming Slide Point The starting position of the following section or the end position of the previous section is set at the cursor position. 0. MasterScalingMode : MC_CamScalingMode.Status. The following parameters can be modified.45. MasterOffset : LREAL. MasterScaling : LREAL := 1. SlaveOffset : LREAL. Caution when scaling during motion! The slave position at the time of scaling should only be affected slightly by the change. MC_CamScaling A cam plate coupling can be scaled with the function block MC_CamScaling. scaling factors for master and slave. The status flag Axis.CamcalingPending can be used to check whether a scaling procedure is queued. b. Overview As required by the application the scale of the Cam Table can be adjusted. ActivationMode : MC_CamActivationMode. END_VAR Execute: The command is executed with a rising edge at input Execute 361 Chapter: Camming . enabling precise scaling during the motion. ActivationPosition : LREAL. Master and Slave offsets can also be given to provide more flexibility to the programmer. the modification will only take effect from a certain master position. Cam Table Scaling a. the scaling refers to an existing master/slave coupling. The raw table data of the cam plate are not affected. Optionally.0. SlaveScalingMode : MC_CamScalingMode. and offsets for the cam plate within the coordinate system. SlaveScaling : LREAL := 1. Inputs VAR_INPUT Execute : BOOL. ActivationMode: ActivationMode specifies the scaling time and position. the position refers to the nonscaled cam plate. as soon as an error occurs. depending on the ActivationMode If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used. BOOL. Error: Becomes TRUE. If the position in the application refers to the scaled cam plate. 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. Inputs/outputs VAR_IN_OUT Master : AXIS_REF. it can be divided by the MasterScaling value before the function block is called. END_VAR BOOL. the function block is ready for a new command. 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. Done or Error. END_VAR 362 Chapter: Camming . ActivationPosition: Master position at which a cam plate is scaled. At the same time one of the outputs. is set. BOOL. Slave : AXIS_REF. if the cam plate was created successfully. ErrorID: If the error output is set. this parameter supplies the error number. Done: becomes TRUE. (* offset is calculated automatically for best result *) MC_CAMSCALING_OFF (* no modification accepted *) ).c. 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. since otherwise a jump in velocity cannot be avoided. Autooffset can be used independently for the master or slave axis of a cam plate and affects both switchover and scaling of cam plates.g. Master-Autooffset determines the master offset of the cam plate such that the master position within the cam plate is maintained. END_TYPE Type and scope of the scaling of a cam plate coupling via function block MC_CamScaling. MC_CAMSCALING_AUTOOFFSET: The scaling takes effect and the system adjusts the offset such that a jump in the position is avoided. The user has to calculate the scaling and offset such that a jump in the position is avoided. 363 Chapter: Camming . the position would change. MC_CAMSCALING_OFF: The scaling and offset are ignored. through scaling. Scaling should nevertheless occur during a phase with slave velocity 0. e. 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. This mode is used when only slave scaling (i. MC_CAMSCALING_USERDEFINED: The scaling and offset are retained unchanged. The function operates based on the rules described below. Autooffset Autooffset mode ensures automatic adaptation of a cam plate offset. 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).scaling and offset *) MC_CAMSCALING_AUTOOFFSET. without master scaling) is to be implemented. MC_CamScalingMode TYPE MC_CamScalingMode : ( MC_CAMSCALING_USERDEFINED. (* user defines scaling parameters . Scaling takes place at the 90° position within the cam plate. 364 Chapter: Camming . After the scaling the relative master position in the cam plate at 180° is therefore also 25% of the start of a cycle.i. Master-Autooffset ensures a seamless sequence of cam plates. i. During a switchover at the edges of a cam plate (see MC_CamActivationMode MC_CAMACTIVATION_NEXTCYCLE). both for cyclic and linear cam plates. at 25% of the start of a cycle.e. Example: A cam plate has master cycle of 360° and is scaled by a factor of 2 to 720°. Further restrictions apply to initial coupling. 365 Chapter: Camming . Slave-Autooffset Slave-Autooffset calculates a slave offset such that discontinuities in the slave position are avoided during cam plate switching or scaling. Slave-Autooffset can be used with any MC_StartMode and will always adjust the cam plate such that the slave position doesn't jump. the master offset is calculated first. The slave offset is adjusted to ensure that the slave position is identical before and after the action. since these functions are mutually exclusive.Master-Autooffset cannot be used for a cam plate with relative coupling or switching. If both Master Autooffset and Slave-Autooffset are used for cam plate switching or scaling. These are shown in the following table. followed by the slave offset. ii. Sample Code: IF VM.NcToPlc.ActPos > 540 THEN fbMC_CamScaling( Execute:=TRUE , ActivationMode:=MC_CAMACTIVATION_NEXTCYCLE , ActivationPosition:=721 , MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET , SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET , MasterOffset:=0 , SlaveOffset:=0 , MasterScaling:= 0.5, SlaveScaling:=1 , Slave:=Slave); END_IF 366 Chapter: Camming 46. Cyclic Cam Plates with Lift Please refer to MC_CamIn Appendix in the Information System or at the end of this document. This document makes use of the Cam Design Tool to create the following cam table where the Slave axis travels 100 for each 360 degree revolution of the Master axis. Calculations for the Lift are handled internally. Only the configuration needs to be correct to implement this type of Cam Table. 367 Chapter: Camming The Master Axis must be set for Rotation. The StartMode of the MC_CamIn FB must be set properly. In this example we are using MC_STARTMODE_MASTERABS_SLAVEREL Where the Master axis is calculated to an Absolute position and the Slave axis is calculated Relative to its current position. 368 Chapter: Camming a. MC_StartMode TYPE MC_StartMode : ( MC_STARTMODE_ABSOLUTE := 1, (* cam table is absolute for master and slave *) MC_STARTMODE_RELATIVE, (* cam table is relative for master and slave *) MC_STARTMODE_MASTERABS_SLAVEREL, (* cam table is absolute for master and relative for slave *) MC_STARTMODE_MASTERREL_SLAVEABS (* cam table is relative for master and absolute for slave *) ); END_TYPE StartMode is used for coupling with cam plates through MC_CamIn and defines whether a cam plate is interpreted absolute (based on the origin of the axis coordinate system) or relative to the coupling position. The mode can be specified as absolute or relative separately for both coordinate axes. With StartMode absolute the cam plate coordinate system is congruent with the axis coordinate system and can be moved through an offset, if required (master or slave offset). With StartMode relative the origin of the cam plate coordinate system is at the axis position of the respective axis (master or slave) at the time of coupling or cam plate switching. The cam plate can additionally be moved through an offset. Note: The modes MC_STARTMODE_RELATIVE and MC_STARTMODE_MASTERREL_SLAVEABS cannot be used in conjunction with automatic master offset calculation (MC_CamScalingMode), since this would cause a conflict. 369 Chapter: Camming As can be seen below, when running the Cam Table cyclically the Slave axis will increase from its current position by 100 for each 360 degrees of travel by the Master Axis. The Red line is the Modulo position of the Master Axis. The Green line is the Absolute position of the Slave Axis. 370 Chapter: Camming 47. Cam Out and Restarting a. Overview MC_CamOut is used to decouple the Slave axis from the Master axis. The slave axis must be stopped after it is decoupled. To couple the axis back to the Master via the Cam Table simply call the MC_CamIn FB again. If the Slave axis has not changed positions then the default values will suffice for Camming the Slave axis to the Master axis on the next cycle of the Cam Table. In the below Scope the Green horizontal line shows the Slave axis not moving because it was decoupled from the Master for 3 revolutions, and then coupled again. 371 Chapter: Camming b. MC_CamOut The function block MC_CamOut deactivates a master-slave coupling. Note: If a slave axis is uncoupled during the movement, it is not automatically stopped, but reaches a continuous velocity with which it will continue to travel endlessly. The axis can be stopped with a Stop command. Inputs VAR_INPUT Execute Options END_VAR : BOOL; : ST_CamOutOptions; (*Not Yet Implemented*) Execute: The command is executed with a rising edge at input Execute. Options: Currently not implemented Outputs VAR_OUTPUT Done : Busy : Error : ErrorID : UDINT; END_VAR BOOL; BOOL; BOOL; Done: Becomes TRUE, if the axis was successfully uncoupled. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done or Error, is set. Error: Becomes TRUE, as soon as an error occurs. ErrorID: If the error output is set, this parameter supplies the error number. Inputs/Outputs VAR_IN_OUT Slave END_VAR : AXIS_REF; Chapter: Camming Slave: Slave axis data structure. The axis data structure of type AXIS_REF addresses an axis uniquely within the system. Among other parameters it contains the current axis status, including position, velocity or error status. 372 c. MC_Halt MC_Halt stops an axis with a defined braking ramp. In contrast to MC_Stop, the axis is not locked against further motion commands. The axis can therefore be restarted through a further command during the braking ramp or after it has come to a halt. Note: Motion commands can be passed to slave axes if they are explicitly enabled in the axis parameters. A motion command will then decouple the axis and move it afterwards. In this case just Buffer-Mode Aborting can be used. Inputs VAR_INPUT Execute : BOOL; Deceleration : LREAL; Jerk : LREAL; BufferMode : MC_BufferMode; Options : ST_MoveOptions; END_VAR Execute: The command is executed with a rising edge at input Execute. Deceleration: Deceleration (≥0). If the value is 0, the deceleration parameterised with the last Move command is used. MC_Halt and MC_Stop as well cannot be executed with lower dynamical parameters than the currently active motion command. Parameters will be adapted automatically. Jerk: Jerk (≥0). If the value is 0, the jerk parameterised with the last Move command is used. MC_Halt and MC_Stop as well cannot be executed with lower dynamical parameters than the currently active motion command. Parameters will be adapted automatically. BufferMode: BufferMode is currently not supported by MC_Halt. Halt takes effect immediately with a rising edge at Execute, similar to BufferMode=MC_Aborting Options: Currently not implemented - The data structure option includes additional, rarely required parameters. The input can normally remain open. 373 Chapter: Camming Active: Active indicates that the command is executed If the command was queued. : BOOL. Axis: Axis data structure The axis data structure of type AXIS_REF addresses an axis uniquely within the system. is set. The running command may have been followed by a Move command. the function block is ready for a new command. it becomes active once a running command is completed. Inputs/outputs VAR_IN_OUT Axis END_VAR : AXIS_REF. CommandAborted or Error. Among other parameters it contains the current axis status. Done: The Done output becomes TRUE. : BOOL. velocity or error status. Done. : UDINT. 374 Chapter: Camming . CommandAborted: Becomes TRUE. including position. At the same time one of the outputs. if the command could not be fully executed.Outputs VAR_OUTPUT Done Busy Active CommandAborted Error ErrorID END_VAR : BOOL. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. ErrorID: If the error output is set. if the axis was stopped and has come to a standstill. When Busy becomes FALSE again. : BOOL. this parameter supplies the error number. Error: Becomes TRUE if an error occurs. : BOOL. but it will jump if it is not already at the table position. b. In practice the question arises. Scaling is also possible. Notes: For all subsequent calculations only axis set positions are used. After the coupling and once the master has been started. The actual positions are not used in the calculations. The slave therefore stops at the table edges as soon as the master leaves the defined range. The slave axis is therefore not slowly synchronized with the cam plate. The following figures illustrate the procedure. 375 Chapter: Camming . particularly with cyclic cam plates. Linear cam plates A linear cam plate is only defined via a limited master position range. MC_CamIn Appendix TwinCAT PLC Library: MC (Version 2) a. since they would lead to calculation errors. 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. and how this is calculated.48. Outside this range the slave position is defined by the first or last table position. the coupling position of the master or slave axis is considered in the calculations as an additional offset. the slave position is calculated directly from the cam plate. The cam plate coordinate system may be offset by a master offset or a slave offset. For relative couplings. what position the slave should be in prior to the coupling. Note that prior to the coupling the slave axis has to be at a position defined by the cam plate. Only absolute table couplings are considered. The diagram shows that the absolute axis coordinate system (blue) does not have to be identical to the cam plate coordinate system (red). Alternatively. it is divided by this scaling factor.SlavePosition. The master table position is used as an input parameter for the function block MC_ReadCamTableSlaveDynamics. SlavePosition := (SlaveCamTablePosition * SlaveScaling) + SlaveOffset. the master may be moved to a position that corresponds to the current slave position. SlaveCamTablePosition := ReadSlaveDynamics. generally this position cannot be determined from the cam plate. Note: Since the master offset is added in the first formula. the master offset in the diagram is negative. Accordingly. MasterCamTablePosition := (MasterPosition + MasterOffset) / MasterScaling. The block refers to the raw table data. the master offset is added to the current master position. which means that offsets and scaling factors have to be considered via the PLC program itself. Initially. If the cam plate is to be scaled. However. A positive slave offset leads to the cam plate coordinate system being shifted upwards in positive direction. The result is converted to an absolute slave position with slave offset and scaling.The slave position relating to a certain master position can be determined via the function block MC_ReadCamTableSlaveDynamics . The slave is moved to this position prior to the coupling. since the cam plate may be ambiguous. if necessary. a positive offset leads to the cam plate coordinate system being shifted to the left in negative direction. 376 Chapter: Camming . master/slave coupling requires the same preparation as for a linear cam plate. It is not necessary to use the modulo position of the master for the calculation.c. The slave therefore moves cyclically within a defined range. 377 Chapter: Camming . since the absolute position is already correctly taken into account via the coupling command. For these cam plate types. 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 starting position of the slave can therefore be calculated as described above. without changing its position permanently in a particular direction. With each new cycle.d. Such a cam plate is continued cyclically at the end of the table. 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. 378 Chapter: Camming . the motion continues steadily. The slave position does not jump back to the initial table value. the lift is therefore added as an additional internal slave offset or subtracted if the motion is reversed. Instead. NewSlaveOffset := SlaveOffset + (SlaveHub * lift number).SlaveOffset). SlaveCamTablePosition := ReadSlaveDynamics. If necessary.SlavePosition. SlavePosition := (SlaveCamTablePosition * SlaveScaling) + NewSlaveOffset. Uncoupling and re-coupling for cyclic cam plates with lift If a slave is coupled to a cam plate with lift.e. Lift number := MODTURNS( (SlavePosition . In addition. the slave position returns to the basic cycle. i. particularly for switching of cam plates.e. The Autooffset function can simplify the calculation of offsets. the number of pending lifts must be calculated and added to the slave position. SlaveHub ). if necessary. The result is converted to an absolute slave position with slave offset and scaling. this behavior has to be taken into account and compensated by re-calculating the slave offset. the coupling is always done in the basic cycle (red coordinate system). The master table position is used as input parameter for the function block MC_ReadCamTableSlaveDynamics. 379 Chapter: Camming . If the slave is uncoupled after a few cycles and then recoupled. without added lifting distances. MasterCamTablePos := (MasterPosition + MasterOffset) / MasterScaling. this document will not suffice if your problem is within your . When needed a sub subgroup will be identified by the second byte 0x0n00. Overview The following covers the error codes as provided by either the function blocks or the TwinCAT System Manager.49. Error Format The error codes within TwinCAT are given in accordance with the following structure. are sometimes not easily understood by new users. although complete. Remember that just because TwinCAT allows you to do something. The added descriptions are only relevant for helping to find a problem within TwinCAT. or an incorrect linking in the system manager. The cause of the errors can vary greatly. These errors indicate that something is fundamentally wrong with your system. The remaining bytes are used to give the exact error code. The error codes provided by the system. The errors range from 0x0000 to 0xFFFF.NET or other 3rd party application. The errors between 0x0000 and 0x0FFF refer to the TwinCAT System itself. that doesn’t mean that that’s what you wanted to do. The most significant byte 0xn000 can be considered as the grouping for the errors. All errors are generated in hexadecimal. The explanations of the error codes provided are based solely on the experience of myself and others. Diagnostics a. it can be anything from a corrupted file to forgetting to start the PLC. b. 380 Chapter: Camming . If all communication is local. and the frequency increases when switching between development. This error is trying to tell you that there is a communication problem. General ADS Error Codes 0x0700 The common errors in this group are fairly self-explanatory.Error Groups Offset 0x0000 0x0500 0x0600 0x0700 0x0800 0x1000 0x1900 0x2000 0x3000 0x4000 0x6000 0x7000 0x7800 Description ERR_GLOBAL ERR_ROUTERERRS ERR_TASKERRS ERR_ADSERRS ERR_SYSSMPLERRS ERR_RTIMEERRS ERR_TRACEERRS ERR_IOERRS ERR_SPSERRS ERR_NCERRS ERR_PLCERRS ERR_STRKERRS ERR_PRJSPECIFIC Global Error Codes 0x0000 0x6 0x7 target port not found target machine not found These errors commonly occur when setting up a system for the first time. and that the correct PLC program is loading and running. These normally occur because of something not being configured correctly. and is commonly an ADS communication problem. the red folder in the system manager will ‘Open from Target’. then make sure TwinCAT is running the correct System Manager file. Ping the IP of address of one PC from the other to make sure cabling and network configuration is correct. If you are unsure of what system manager file is running. 381 Chapter: Camming . simulation. and machine. 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. If communication is remote then check the AMS router on both PCs to make sure the info is valid. 255) has been or a table that does not exist in the system has been named. 382 Chapter: Camming . Check your value of your TableID 0x4052 for "Axis not ready for operation" The axis is not complete. it must be at D013: Axis Op. NC Error Sub Groups 0x40nn 0x41nn 0x42nn 0x43nn 0x44nn 0x45nn 0x46nn 0x4Ann 0x4Bnn General NC Errors Channel Errors Group Errors Axis Errors Encoder Errors Controller Errors Drive Errors Table Errors NC-PLC Errors General NC Errors 0x40nn 0x4016 used. These sub groups cover all things motion. If the Ready Status of the Axis is not TRUE and the axis receives a command then this error will be given. Look at the ErrorID.. The ‘R’ button on the right side of the ErrorID display will issue an IDN99 reset command to the drive. "Table identifier not allowed" Either an unacceptable value (not 1.. from Overtemp errors to syntax errors in G-Code to bad PLC commands. A value less than 13 or an F value will prevent the axis being ready. 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.NC Errors 0x4000 The NC error group is comprised of 9 sub-groups. This is usually a consequence of problems at system start-up. from For an AX5000 the first place to check is on the ‘Configuration’ Tab of the axis. and is therefore not ready operation. With the new ‘Buffered Moves’ in MC2 this shouldn’t be an issue any more. Value 0: Passive (buffered operation) Value 1: Active (single-block operation). However keep in mind that if you issue a second move before the first one is complete. However there is one here that should be covered. 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. 0x4208 "Single step mode not allowed" The flag for the activation or deactivation of single step mode is not allowed. The majority of these errors are for incorrect (out of range) parameters or monitoring the control of the axis position. This error does not stop the axis. The majority of these errors are for incorrect (out of range) parameters or monitoring the state of the drive and motor. it just appears in the Log window of the System Manager. 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.Channel Errors 0x41nn These errors are for NC-I and are not within the scope of this document. 383 Chapter: Camming . where it previously would ignore the command. Group Errors 0x42nn These errors are for NC-I also. Prior to MC2 if an axis was given a command while the Status bit ‘Has Job’ was TRUE this error would be given. Encoder Errors 0x44nn These Errors relate to the parameterization and monitoring of an encoder. Drive Errors 0x46nn These Errors relate to the parameterization and monitoring of the drive and motor. it will now Abort the previous command and Execute the new one. The Flying Saw function blocks will generate these errors as well as Cam Table function blocks..0x4B4F 0x4B50. The majority of these errors are for incorrect (out of range) parameters or invalid cam table data.0x4B0F 0x4B10.Table Errors 0x4Ann These Errors relate to the parameterization and initialization of a cam table..0x4B5F 0x4B60. When generating a Cam Table from the PLC or from the Flying Saw this error can happen. for example. because.. 0x4A06 "Table is not monotonic" The value for the step size is not allowed. 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. NC-PLC Errors TwinCAT NC I TcMcCam TcNc TcRemoteSync TcMC2 0x4B00..0x4B6F TcPlcInterpolation 0x4B70.. This can also happen for a Cam Table generated by the PLC when the position would require the Master Axis to move backwards.0x4B7F 384 Chapter: Camming .. PLC Errors 0x4Bnn The majority of these errors are well described within the Information System.0x4B3F 0x4B40. it is less than or equal to zero.0x4B2F 0x4B30.. IX. Remote Connections 50. Embedded Controllers  The TwinCAT AMS Router allows for TwinCAT to communicate between computers    Configuring your local IP address Establishing a Route to the Target Opening the active system manager of the Target 385 Chapter: Remote Connections .  Right-Click on the Network Card and select “Properties” 386 Chapter: Remote Connections .   Click “Start” Expand “Connect To” Click “Show all connections”   The network card you are going to use should be the only one with a Status of “Connected”. If the other cards are connected TwinCAT may try to one of scan these networks for devices and not scan the correct network. Select “Internet Protocol (TCP/IP)” Click on “Properties” 387 Chapter: Remote Connections .   Scroll to the bottom of the list.     Select “Use the following IP address” Enter the following IP address. 192.2 Enter your Subnet mask Click “OK” 388 Chapter: Remote Connections .0.168.  Click “OK” 389 Chapter: Remote Connections . You can do this if you like. but it is not needed for connecting to remote devices. 390 Chapter: Remote Connections . If the below window appears click on “STOP Installation”. and select System Manager.  Click on the TwinCAT icon in the Windows System Tray. If you click on “Continue Anyway” windows will install the Real-Time Ethernet driver for your network card. then New  Set/Reset TwinCAT to Config mode. Select File.  Click “Ok” 391 Chapter: Remote Connections . Open a new System Manger file.  Select “SYSTEM – Configuration”. then “Choose Target”  Click “Search (Ethernet)” 392 Chapter: Remote Connections .    If you know the IP address of the remote device it can be entered. Click “Enter Host Name / IP:” It is also possible to use the ‘Broadcast Search’ button to look for computers on the local network that are running TwinCAT. if a static IP address is being used then set ‘Address Info’ to ‘IP Address’ Select the computer form the list and select ‘Add Route’ Chapter: Remote Connections  393 .  If the computer you are connecting to is using DHCP then the ‘Address info’ should be set to ‘Host Name’. however a broadcast search will not go through a network router.    Enter User name and password of an Administrator account on the Target PC Not required for Windows CE Click “OK”  Verify the “X” appears in the “Connected” column. 394 Chapter: Remote Connections . Click on “Close”.  Select “BasePLC” Click “OK” 395 Chapter: Remote Connections . A yellow background indicates a Timeout. Click on the red folder to “Open from Target”    If the below window appears click on “Yes” 396 Chapter: Remote Connections . Verify the device status. Verify connection to “BasePLC” the red background indicates you are connected to a remote device. A blue background indicates the remote device is in config mode. A green background indicates that TwinCAT is running on the remote device.    File name of the System Manager *.tsm file Name of remote device List of hardware connected to the device 397 Chapter: Remote Connections . unless the customer has specified other guidelines for the project. The programming guidelines must be used for the development of new programs.X. 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 programmer can judge the extent to which the guidelines can be applied to existing programs. 398 Chapter: Appendix I – Variable Naming Convention . Appendix I – Variable Naming Convention 51. 52.     Font: Tahoma Font style: Regular Size: 12 Character set: Western b. Font A non-proportional font is recommended with the following settings: This can be adjusted under "Project -> Options -> Editor -> Font". 399 Chapter: Appendix I – Variable Naming Convention . Programming System Settings The TwinCat project options must be defined uniformly to achieve identical notation for individual editors and for documentation. a. This is especially true in multi-user projects. Tab Width A tab width of 4 is recommended. This can be adjusted under "Project -> Options -> Editor". A. description for each designator name and the designator should be self-explanatory. property. NOTE: The TwinCat IEC compiler is not case sensitive.. Valid Characters Names should contain the following letters. Naming a. and program organization units (POU). 400 . the fewer the better. The underscore should not be used otherwise. Because data type designators are usually formed from capital letters. constants.. Choose a relevant...9.Z.z Underscore Designators always begin with a letter. Please limit the name to 20 characters. The underscore is used to display prefixes more clearly. b. c.. numbers. Prefixes are included with the designator name to indicate scope.53. a. short. The syntax is explained in the respective prefix section. General This naming convention applies to variables. the individual words are put together with an underscore as a separator to increase readability. especially for prefixes. to improve readability. and special characters only: Chapter: Appendix I – Variable Naming Convention    0. The first letter of each word in the designator is capitalized (example: FileSize).. Case Sensitivity Pay close attention to case sensitivity. and type as will be explained below. d. The prefix types are as follows:     Type – designator type such as Boolean or integer Scope – designator scope as either local or global Property – designator property such as retained or VAR_IN_OUT POU – POU type such as function or function block The general syntax for variables and constants is as follows:  [Scope][Property] _ [Type][Name]     g_diFirstUserFault xEnable c_iNumberOfAxes gc_sMyGlobalStringConstant The general syntax for POU’s is as follows:  [POU] _ [Name] Chapter: Appendix I – Variable Naming Convention     FB_AxisController FB_HeatGun P_Main F_GetLeftString 401 . Prefix Types Prefixes are used to quickly identify a designator’s function. : DINT := 100. : ST_EVENTLIST.e. A lower case "c" is added to global constants. : BOOL.5 Scope Prefix 402 Chapter: Appendix I – Variable Naming Convention . 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. (* Maximum Quantity of Active Faults *) (* Maximum Quantity of Events *) VAR_GLOBAL g_stMasterFaultList g_stMasterEventList g_xReset END_VAR : ST_FAULTLIST. Global variables are indicated by a lower case "g". You can see if it is a local or a global variable or a constant from the scope prefix. VAR_GLOBAL CONSTANT gc_diMaxFaults gc_diMaxEvents END_VAR : DINT := 100. Scope Prefix Scope prefix indicates the scope of variables and constants. Type Prefix x b w dw si i di usi ui udi r lr date tod dt t s p a e Type BOOL BYTE WORD DWORD SINT INT DINT USINT UINT UDINT REAL LREAL DATE TOD DT TIME STRING POINTER ARRAY ENUM Use (Bytes) Boolean (1) Byte (8) Word (16) Double Word (32) Short Integer (8) Integer (16) Double Integer (32) Unsigned Short Integer (8) Unsigned Integer (8) Unsigned Double Integer (32) Floating Point Value (32) Long Floating Point Value (64) Date (32) Time of Day (32) Time and Date (32) Time Duration (32) Character String (x Chars + 1) Pointer Array List Type Example xName bName wName dwName siName iName diName usiName uiName udiName rName Chapter: Appendix I – Variable Naming Convention lrName dateName todName dtName tName sName pxName adiName eMotorType 403 .f. The IEC 61131-3 standard data type prefixes are listed in the following table. Type Prefix Type prefixes identify the data type of variables and constants. .10] OF INT.. : ARRAY [0. followed by the prefix of the pointer type or array type as the following examples show: piCounter aiCounter paiRefCount astList : POINTER TO INT. : POINTER TO ARRAY [1. : ARRAY[0.10] OF INT.gc_diMaxFaults] OF ST_FAULT. 404 Chapter: Appendix I – Variable Naming Convention . for example. The pointer or array is listed first.6 Standard Date Type Prefixes The type prefix can also be composites.. for pointers and arrays.Type Prefix st fb Type STRUCT FUNCTION BLOCK Use (Bytes) Structure Function Block Example stRecipe fbTrigger Table 3. Property Prefix Property prefixes are used for identifying the properties of variables and constants as shown in the following table: Property Prefix c_ r_ Type VAR CONSTANT VAR RETAIN Use Local constant Remnant variable type retain Remnant variable type persistent Input variable of POU Output variable of POU In/out variable of POU Example c_xName r_xName p_ i_ q_ iq_ VAR PERSISTENT VAR_INPUT VAR_OUTPUT VAR_IN_OUT AT %IX AT %IB p_diName i_xEnable q_xError iq_stParameters ati_ AT %IW AT %ID Direct access to input memory ati_bName AT %QB atq_ AT %QW AT %QD AT %MX AT %MB atm_ AT %MW AT %MD Direct access to output memory atq_bName Direct access to memory location atm_bName 405 Chapter: Appendix I – Variable Naming Convention AT %QX .g. The name of the AT-declared variable also contains the type of the target variable. 406 Chapter: Appendix I – Variable Naming Convention . AT %MW4 : REAL.Table 3.7 Property Prefix NOTE: Do not declare constants as RETAIN or PERSISTENT. It is used like the type prefix:   atm_rMyVar1 atm_rMyVar2 AT %MW0 : REAL. g. 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. the first letter of each word in the POU name is capitalized. Just like a variable.8 POU Prefix 407 . The prefix comes with an underscore before the name and identifies the type of POU on the basis of the following table: POU Prefix P_ FB_ F_ A_ Type PROGRAM FUNCTION_BLOCK FUNCTION ACTION Use Program Function block declaration Functions Action Example P_RecipeManagement FB_AxisController F_GetLrealString A_GetCommand Chapter: Appendix I – Variable Naming Convention Table 3.h. FB_GetResult). We recommend that you form a composite POU name from a verb and a noun. g. If several words have been put together. : LREAL := 2000.0.0. : LREAL := 10000.i. : LREAL := 2000. Each component of the structure must be identified with a type prefix. Structures The name of each structure data type consists of a prefix ST_ and a short.  stAxis1Feed : ST_FEED_PARAMETERS.0. : MC_Direction := MC_Positive_Direction.0. they are separated by an underscore. : LREAL := 0. ST_STATION_NUMBER). 408 Chapter: Appendix I – Variable Naming Convention Declaration example: . TYPE ST_FEED_PARAMETERS : (* Parameters for MC_MoveVelocity FB *) STRUCT lrVel lrAcc lrDecel lrJerk eDirection lrStopPos END_STRUCT END_TYPE : LREAL := 100.0. meaningful description in upper case (e. g. they are separated by an underscore. List Types The name of a list type consists of a prefix ET_ and a short. 409 Chapter: Appendix I – Variable Naming Convention  eMyEvent : ET_EVENT_TYPES. meaningful description in upper case (e. END_TYPE (* Fault Just Occurred *) (* Fault Is Gone and Acknowledged By AutoReset *) (* Fault Is Are Gone and Ack By Reset Input *) (* User Event *) Variables and constants declared as a list type are prefixed with a lower case: NOTE: 2 bytes of memory are reserved for each list variable. E_EVENT_USER_1 := 10 ). ET_WORKING_DAY). If several words have been put together.j. The individual elements of list types are identified with the prefix E_. TYPE ET_EVENT_TYPES : ( E_EVENT_NO_EVENT := 0. E_EVENT_FAULT_ACK := 3. E_EVENT_FAULT_ACTIVE := 1. E_EVENT_FAULT_RESET := 2. .   MyLib_gc_diMaxConvCount MyLib_ConveyorControl.lib 410 Chapter: Appendix I – Variable Naming Convention .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. : ARRAY[1. each individual line of code does not need to be commented. if the code is difficult to understand and there are no comments. If variables have been given unusual values. The first element of the array. The problem is corrected as follows:  astRecipes : ARRAY[0.10] OF ST_RECIPE. However. It is more important to keep code clear and understandable. 0. This minimizes the amount of comments required. it is extremely important to explain the reason for this to prevent future misunderstandings.. Good Programming Practices a. is either not used or used as a default. 411 Chapter: . Comments Comments are essential for understanding source code. comments can be shorter. If all POUs and variables have meaningful names. Limit your comments to the necessary minimum.54. Write your comments so that they are not only notes for the programmer but can also be understood by third parties.. for example. b.   iCurrentRecipe astRecipes : INT. Program Calls Parenthesis should be used when calling programs and actions as shown below:  P_SearchData().10] OF ST_RECIPE. c. even the programmer will have trouble understanding it after a short time. 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. however. . 406 POU ... 77. 135 ST 12.. 13.. 12. 70.. 268. 66. 290. 34 F FBD. 57. 337... 64 Remote . 266. 84... 175... 270.. 25. 300. 96.. 133.. 240. 263.. 156. 178..... 369..... 216..405 S SFC .. 379 I IL 12. 394..... 88..... 378 412 Chapter: . 228. 165... 375.. 75.. 317... 179. 299... 81... 61. 312.... 109.. 58.. 187.. 78 T P TwinCAT 1. 202.. 168. 21. 16. 17............. 20.... 135.. 67.. 29. 326. 22....... 82...... 375...... 23.. 83... 110. 268.... 187.... 374. 340.. 288.. 21... 58.... 107.. 26.... 267.. 285.... 13............ 30... 64...... 37..... 318.. 72. 199... 60. 103.. 315.... 396... 210. 49... 46. 285. 104........ 76. 69... 284....... 215.... 367. 166... 206... 13...... 406 L LD 12... 59.... 11. 37.. 41.. 15.. 106... 214..... 144... 77..8.... 299. 42..... 28...... 50.. 320.. 196. 22. 309. 306... 168. 62....... 24.. 21... 304. 204... 14. 310... 378... 387. 320... 133. 153.. 57.. 286...... 271.. 177......... 87. 376.. 45.... 25...... 298. 401... 12... 63. 289. 31. 217. 77. 74... 281. 140.. 19.. 330... 153.... 170. 18.. 86. 391 PLC 10.... 63..... 171........ 305.......... 12.. 298.... 178... 163. 77 Instruction List ........ 11.... 81.. 398.. 73.... 399. 164.... 323. 155.... 329.... 337.... 225. 222... 43.... 205. 273. 200. 58.... 402 Priorities ... 22... 69.. 135... 38.... 112.. 397... 400.. 132..... 200... 82... 220.. 107..... 218.. 47... 14.... 108.. 375........... 318.. 97. 297. 59. 10.... 307.. 172.... 69. 335... 20. 68... 79. 384. 380...... 139... 84......... 221. 403.. 164.. 311. 32.... 13. 15..... 263.. 374.. 77.. 370.... 23. 77..... 165... 170 R Registration . 379 Array . 112.... 385. 132.. 16...... 366.. 269.......... 379.... 230. 369.. 290. 208. 50... 29.. 186...... 68. 171... 65.. 134. 139.. 275.. 48. 110. 97 AMS . 67. 59. 77.. 26.. 75.... 311. 65.. 170. 80. 265........ 284..Index A Actions . 270..... 12.... 22... Documents Similar To TwinCAT 2 Manual v3.0.1Skip carouselcarousel previouscarousel nextBECKHOFF TwinCAT 3 BasicsTwin Cat Module 1Structured Text TutorialTwinCAT Getting StartedBeckhoff Training - 03 CX900x Comms & Hardware Setup 2011 (1).pptDay 1 Basic ClassTwinCAT IO System ManualTutorial TwincatTwinCAT IEC61131-3Twincat ManualModule 4 - Introduction to ADS-ProgrammingEtherCAT Training.pdfTwinCAT 2 Manual v3.0.056664365-Day-1-Basic-ClassTwinCAT 2 Manual v2_1_0Beckhoff TwinCAT3 042012 eInfoPLC Net Creating Boot Projects in TwinCATInfoPLC Net Accessing TwinCAT Variables With VB6 ActiveXEtherCAT CommunicationBECKHOFF-EtherCAT TrainingTwinCAT EC Diag Eng 2141213161-Beckhoff-TwinCatBeckhoff TwinCAT3 042012 eInfoPLC Net Basic Configuration of TwinCAT NC AxisBeckhoff and TwinCAT GuideTcPlcLibControllerToolboxTwinCAT QuickStartTC3_E_04 Assigning IP Addresses Beckhoff Ethernet Devicesbeckhoff-twincat-manual.pdfMore From Vladimir FrizSkip carouselcarousel previouscarousel nextInfoPLC Net Guia1ManualCD-0169T-ESPE-025353.pdfInfoplc Cursillo Basico Intouch 7 1Diseno Sistema MonitoreoDoc1problemasmatlabvectoresmatricespolinomios.docInforme 201740638504 PID Para Control de Temperatura de Un Horno ElectricoMateriales para la Red de ComunicaciónTutorial de Configuracion de PID Con RSLogic RevisadoPm IntroduccinQuien Se Ha Llevado Mi Queso[1]Tarea 1 WindowsManual Instrucciones PLC1769 L32E Compact LogixAttachment2 Capitulo i ScadaDH-485 Cables used with SLC-500 processors and the 1747AIC.pdfManual Del Emprendedor364815510.1.1.72Best Books About Programmable Logic ControllerPLC: programmable logic controller based on the microprocessor FULCRUM - B.by Mario FrancoINSTANT PLC Programming with RSLogix 5000by Austin ScottLearning RSLogix 5000 Programmingby Austin ScottProgrammable Logic Controllersby William BoltonMitsubishi FX Programmable Logic Controllers: Applications and Programmingby John RidleyBasic Hydraulics and Controlsby Winston LMFooter MenuBack To TopAboutAbout ScribdPressOur blogJoin our team!Contact UsJoin todayInvite FriendsGiftsLegalTermsPrivacyCopyrightSupportHelp / FAQAccessibilityPurchase helpAdChoicesPublishersSocial MediaCopyright © 2018 Scribd Inc. .Browse Books.Site Directory.Site Language: English中文EspañolالعربيةPortuguês日本語DeutschFrançaisTurkceРусский языкTiếng việtJęzyk polskiBahasa indonesiaSign up to vote on this titleUsefulNot usefulYou're Reading a Free PreviewDownloadClose DialogAre you sure?This action might not be possible to undo. Are you sure you want to continue?CANCELOK
Copyright © 2024 DOKUMEN.SITE Inc.