Beckhoff New Automation TechnologyTwinCAT 2Revised: October 18, 2012 Brian McClure [email protected] 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] 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 modified4I.Contents10 10 17 25 43 44 44 46 61 63 63 67 68 71 75 81 85 94 95 97 100 104 106 110 110 186 221 221 225II. TWINCAT OVERVIEW 1. 2. 3. 4. OVERVIEW SYSTEM SERVICE SYSTEM MANAGER PLC CONTROLIII. 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. IDE PROGRAMS DATA TYPES AND CONVERSIONS VARIABLES LANGUAGES FUNCTIONS FUNCTION BLOCKS ACTIONS STRUCTURES ENUMERATIONS ARRAYS BOOT PROJECT SOURCE CODE DOWNLOADV. PLC PROGRAMMING THE INSPECTION CONVEYOR 21. MACHINE CONTROL WITH TOP-DOWN PROGRAMMING 22. DIGITAL I/O VI. TROUBLE SHOOTING 23. CODE SEQUENCING 24. BREAK POINTS525. 26. 27. 28.FLOW CONTROL GLOBAL SEARCH CROSS REFERENCE SCOPE VIEW230 236 242 248 255 255 256 256 260 263 264 264 265 266 267 268 268 268 268 270 272 272 272 272 273 274 274 275 275 275 276 277 277 277 280 283 283 283VII. CAMMING 29. PREFACE 30. INTRO TO TCMC2.LIB A. OVERVIEW B. MIGRATION FROM TCMC TO TCMC2 C. STATUS INFORMATION 31. WHEN TO USE A CAM TABLE A. OVERVIEW B. GEARING C. LINEARLY INCREASING GEAR RATIO (DYNAMIC) D. CAM TABLE 32. CREATING A CAM TABLE WITH FUNCTION BLOCKS A. OVERVIEW B. DEFINING THE POINTS ON THE CAM TABLE I. MOTION FUNCTION POINT II. SAMPLE CODE: 33. DEFINING THE CAM TABLE IN THE PLC A. OVERVIEW B. MC_CAM_REF I. EXAMPLE 1: POSITION TABLE STRUCTURE DESCRIPTION II. EXAMPLE 2: STRUCTURE DESCRIPTION OF A MOTION FUNCTION C. MC_TABLETYPE I. SAMPLE CODE: 34. CREATING THE CAM TABLE A. OVERVIEW B. MC_CAMTABLESELECT I. SAMPLE CODE: 35. IMPORTING A CAM TABLE FOR VERIFICATION A. OVERVIEW B. CREATING A BLANK TABLE C. IMPORTING THE CAM TABLE 36. 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.6B.MC_CAMIN I. SAMPLE CODE: 37. CHANGING A TABLE POINT VIA THE PLC A. OVERVIEW B. MC_WRITEMOTIONFUNCTIONPOINT C. MC_SETCAMONLINECHANGEMODE D. MC_CAMACTIVATIONMODE I. SAMPLE CODE: 38. MOTION FUNCTIONS VS. POSITION TABLES A. POSITION TABLES B. MOTION FUNCTIONS C. DEFINITION OF A POINT D. POINT STRUCTURE E. POINT TYPES 39. 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 40. CAM TABLE SCALING A. OVERVIEW B. MC_CAMSCALING C. MC_CAMSCALINGMODE I. EXAMPLE: II. SAMPLE CODE: 41. CYCLIC CAM PLATES WITH LIFT A. MC_STARTMODE 42. CAM OUT AND RESTARTING A. OVERVIEW B. MC_CAMOUT C. MC_HALT 43. MC_CAMIN APPENDIX A. AXIS COUPLING WITH CAM PLATES B. LINEAR CAM PLATES C. CYCLIC CAM PLATES WITHOUT LIFT D. CYCLIC CAM PLATES WITH LIFT E. UNCOUPLING AND RE-COUPLING FOR CYCLIC CAM PLATES WITH LIFT 44. DIAGNOSTICS283 285 286 286 286 287 289 290 292 292 294 295 295 296 297 297 298 303 304 305 307 308 309 311 311 311 313 314 316 317 319 321 321 322 323 325 325 325 327 328 329 3307A.OVERVIEW B. ERROR FORMAT VIII. REMOTE CONNECTIONS 45. EMBEDDED CONTROLLERS IX. APPENDIX I VARIABLE NAMING CONVENTION 46. SCOPE 47. PROGRAMMING SYSTEM SETTINGS A. FONT B. TAB WIDTH 48. 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 49. GOOD PROGRAMMING PRACTICES A. COMMENTS B. ARRAY INDEXING C. PROGRAM CALLS II. APPENDIX II TRUTH TABLES AND BOOLEAN ALGEBRA X. APPENDIX III DE-BOUNCING AN INPUT XI. APPENDIX IV QUICK START OVERVIEW330 330 335 335 348 348 349 349 349 350 350 350 350 351 352 353 355 357 358 359 360 361 361 361 361 362 365 368 36889II.TwinCAT Overview1. OverviewThe Windows Control and Automation Technology The Beckhoff TwinCAT software system turns any compatible PC into a real-time controller with a multi-PLC system, NC axis control, programming environment and operating station. TwinCAT replaces conventional PLC and NC/CNC controllers as well as operating devices with: open, compatible PC hardware embedded IEC 61131-3 software PLC, software NC and software CNC in Windows NT/2000/XP/Vista, Windows 7, NT/XP Embedded, CE programming and run-time systems optionally together on one PC or separated connection to all common fieldbuses PC interface support data communication with user interfaces and other programs by means of open Microsoft standards (OPC, OCX, DLL, etc.)Architecture TwinCAT consists of run-time systems that execute control programs in real-time and the development environments for programming, diagnostics and configuration. Any Windows programs; for instance, visualization programs or MS Office programs, can access TwinCAT data via Microsoft interfaces, or can execute commands. A practical oriented software solution TwinCAT offers a precise time base in which programs are executed with the highest deterministic features, independently of other processor tasks. The real-time load on a PC is set with TwinCAT; defined operating behavior is achieved in this way. TwinCAT indicates the system load for programs that are running. A load threshold can be set in order to assure a defined computing capacity for the operating programs and for Windows NT/2000/XP/Vista. If this threshold is exceeded, a system message is generated.10Chapter: TwinCAT OverviewTwinCAT supports system diagnosis The general use of hardware and software from the open PC world requires some checking: Unsuitable components can upset the PC system. Beckhoff has integrated a practical indicator of the real-time jitter, giving administrators an easy way to evaluate the hardware and software. A system message during operation can draw attention to incorrect states. Start/Stop behavior Depending on the setting, TwinCAT is started and stopped manually or automatically. Since TwinCAT is integrated into Windows NT/2000/XP/Vista and Windows 7as a service, an operator is not needed to start the system: switching on is enough. Restarting and data backup When a program is started or restarted, TwinCAT loads programs and remnant data. To back up data and to shut down Windows NT/2000/XP/Vista and Windows 7 correctly, a UPS (uninterruptible power supply) is of great value. World-wide connection through message routing remote connection is inherent to the system According to the requirement for operating resources, the TwinCAT software devices can be distributed: TwinCAT PLC programs can run on the PCs or on Beckhoff Bus Terminal Controllers. A message router manages and distributes all the messages, both in the system and via TCP/IP connections. PC systems can be connected with each other via TCP/IP; Bus Terminal Controllers are integrated via serial interfaces and fieldbuses (EtherCAT, Lightbus, PROFIBUS DP, CANopen, RS232, RS485, Ethernet TCP/IP). World-wide access Since standard TCP/IP services of NT/2000/XP/Vista/CE and Windows 7 can be used, this data can be exchanged across the world. The system offers scalable communication capacity and timeout periods for the supervision of communications. OPC provides a standardized means for accessing many different SCADA/MES/ERP packets.11Chapter: TwinCAT OverviewPLC and Motion Control on the PC TwinCAT I/O universal I/O interface for all common fieldbuses Many PC fieldbus cards from various manufacturers are supported. It is possible to operate more than one fieldbus card per PC. Master and slave functionality is supported, depending on the selected fieldbus card. The fieldbus cards can be configured and diagnosed conveniently via the TwinCAT System Manager. TwinCAT I/O includes the TwinCAT real-time system for operating the fieldbuses and a DLL interface to application programs. TwinCAT PLC the central pillar of automation software Conceived as a pure software PLC, TwinCAT PLC allows up to four virtual PLC CPUs, each running up to four user tasks, on one PC. The PLC program can be written in one or more of the languages provided for in the IEC 61131-3 standard: IL (Instruction List), LD (Ladder Diagram), FBD/CFC (Function Block Diagram), SFC (Sequential Function Chart) and ST (Structured Text).TwinCAT PLC running under the Windows NT/2000/XP/Vista operating systems includes both the programming environment and the run-time system, so that an additional programming device is not required. ander the CE operating system and the embedded operating systems for the series BX and BC controllers, only TwinCAT run-time is available. Program modifications are implemented via network-capable powerful communication with the run-time system. Programming can be done locally, via TCP/IP or via the fieldbus (BXxxxx and BCxxxx). Chapter: TwinCAT Overview12IEC 61131-3 advanced programming standard for all Beckhoff controllers The TwinCAT PLC is programmed in accordance with IEC 61131-3 independently of the manufacturer. TwinCAT supports all the IEC 61131-3 programming languages with convenient editors and a fast, effective compiler, so that the development cycle for the creation even of large PLC programs of several megabytes can be short. Incremental compilation prevents long turnaroand times. Only genuinely new sections are compiled. Powerful editor features, such as autoformat, autodeclare or find and replace enable fast programming. For all programming languages, the project comparison function facilitates differences to be identified and accepted if appropriate. If a project (comments, directories, etc.) is to be translated into a language other than the original language, all terms can be exported into a table, translated and re-imported. If a team is dealing with the development, all objects (blocks, data types, lists) can be managed within a source code management tool via the TwinCAT Engineering Interface. This enables changes to be traced back and differences between individual versions to be displayed. The concept of the instantiation of function blocks, in which each instance is associated with its own data, leads naturally to object-oriented and structured programming styles. All common data types specified in IEC 61131-3 are supported. Multi-dimensional fields and structures are possible, as are enumeration and subrange types. TwinCAT PLC is certified for the languages IL and ST (base level). The online change function can be used for code and/or data modifications while the PLC is running, providing maximum data retention. Source code can be stored in the target system (except for BCxxxx series controllers). The criteria analysis function is very helpful for the detection of process errors. Code can very easily be reused via the convenient library manager. For know-how protection, multi-stage password protection can be applied to programs and libraries. Many target platforms one tool The PLC programs created with TwinCAT PLC can be executed on a number of target platforms. Apart from Industrial PCs and the Embedded PCs, the PLC project can also be loaded into the BC and BX series fieldbus controllers from Beckhoff. Program development and debugging proceed in the same working environment, regardless of which unit is executing the program. Extensive supplementary libraries As an extension to the blocks defined by the IEC language standard, Beckhoff offers a wide range of supplementary libraries for the execution of tasks typical in automation technology: e.g. libraries for controlling electrical and hydraulic axes via TwinCAT NC, serial communication libraries, system libraries for message outputs, write/read files, control technology blocks, etc. Chapter: TwinCAT Overview13Helpful practice tools Extensive fault finding functions in TwinCAT PLC facilitate the solution of problems either on site or via remote maintenance. For this purpose, the PLC programming environment in TwinCAT offers: Online Monitoring Power Flow (flow control) Break Points Sampling trace of PLC variables Single step Watchlist Call hierarchy Forcing of variables. In addition, the TwinCAT ScopeView (a software oscilloscope) can be used to record one or several variables simultaneously. TwinCAT NC Motion Control on the PC A software NC consists of: positioning (set value generation and position control) integrated PLC with NC interface operating programs for commissioning purposes I/O connection for axes via fieldbus With TwinCAT NC, the position controller is calculated on the PC processor as standard. It exchanges data cyclically with drives and measurement systems via the fieldbus. Chapter: TwinCAT Overview Central NC positioning on the PC The computing capacity of a PC enables axis motion simultaneously with the PLC, whereby the position controller is usually calculated on the PC: The computing capacity of a PC enables many axes to be positioned simultaneously. TwinCAT enables a PC to process the operating programs, the PLC and the NC at the same time. The division of the system load is supported by TwinCAT with appropriate functions.14Analytical path calculation The algorithms that TwinCAT NC/NC I/CNC uses to control axes take account of the dynamic parameters of the axis: speed, acceleration and jerk. In this way, the axes are moved at any time within the limits of what is dynamically possible, and are precisely analytically coordinated. A range of different regulation algorithms are available in order to reduce the deviations from the ideal trajectory that will occur in practice. Individual or joint Based on the normal methods for positioning an individual electrical axis, moving from its starting point to its destination (point-to-point positioning), TwinCAT NC also allows the coordinated movement of a number of axes in multi-stage master-slave operation (e.g. gearing functions or cam plates) to be executed. TwinCAT NC I further allows the interpolated path sequencing described in accordance with DIN 66025 to be carried out involving up to three axes. Software PLC included TwinCAT combines software NC and software PLC to form a powerful controller. The communication between the two packages is a pure software/software channel with minimum delay times. The NC functionalities are called from the PLC program via standardized, PLCopencertified function blocks. Axis movements can be simulated without hardware; the actual value is instructed to ideally track the set value, and the complete machine flow is checked. TwinCAT ScopeView is helpful for commissioning and maintenance. It records all axis variables such as position, speed, acceleration and jerk.Convenient commissioning Commissioning is simplified significantly by the configuration and diagnostic dialogs offered in the TwinCAT System Manager. For each axis, all main data are displayed at a glance. The axes can be moved via function keys. Special functions such as couplings, cam plates or distance compensation can be triggered and observed via the System Manager. A convenient dialog enables the dynamic parameters of an axis to be determined. Chapter: TwinCAT Overview15TwinCAT NC I axis interpolation in three dimensions TwinCAT NC I (interpolation) is the NC system for linear and circular interpolated path movements of axis groups each involving two or three drives. The system includes interpreter, set value generation and position controller. PLC functionality is integrated, as is the connection of the axes with the fieldbus. The interpreter interprets the code described in DIN 66025. Comprehensive PLC libraries enable interaction between NC and PLC. NC programs, for example, can be loaded directly from the PLC program into the interpreter. TwinCAT CNC the software CNC for toughest requirements TwinCAT CNC expands TwinCAT NC I with classic CNC features: Up to 32 interpolating axes and comprehensive coordinate and kinematic transformations are possible. Parts programming is carried out according to DIN 66025 using high-level language extensions. TwinCAT CNC can operate with up to 64 axes or 32 path axes and controlled spindles that can be distributed across up to twelve CNC channels. In a CNC channel, up to 32 axes can be interpolated simultaneously, enabling even the most difficult motion tasks to be solved.16Chapter: TwinCAT Overview2. System Service The TwinCAT System Service is represented by the TwinCAT icon in the Windows system tray.The TwinCAT System Service can be accessed through the TwinCAT icon in the windows system tray (Right-Click and Left-Click provides the same menu)From this menu the other parts of the TwinCAT system can be accessed and the TwinCAT System Properties can be changed17Chapter: TwinCAT OverviewThe General tab of the system properties provides the version number and registration information of TwinCAT Note that the 30 day counter has started and the Reg. Key is empty18Chapter: TwinCAT OverviewThe 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 upAuto 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 machineConfig Mode The TwinCAT System Service will boot in Config Mode ADS services are running, remote communication is possible Chapter: TwinCAT OverviewAuto Logon: Enabling this option and providing a User Name and Password will allow for the Windows Logon screen to be bypassed, this is ideal for a running machine but not for a development laptop as this information is stored in plain text in the windows registry.Note: See the security section for protecting the windows registry.19AMS Router Automation Machine SpecificationAMS 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 RouterAMS NetID xxx.xxx.xxx.xxx.1.1 The address of the local TwinCAT Service Every address on the network should be unique The default address is generated by the IP address of the network card with an additional .1.1 added to the end The first four octets of the address can be changed to any number between 0 and 255. They do not have to match the IP address The last two octets should not be changed as .1.1 represents the external address and other values are used internally Chapter: TwinCAT Overview20Remote 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 Manager21Chapter: TwinCAT OverviewPLC 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 made22Chapter: TwinCAT OverviewRegistration The System ID is needed for licensing It is advised that on a running machine the customer should record the System ID and Registration Key. In the event of a Hard Disk failure these two numbers and the new System ID can be used to generate a new Registration Key Otherwise the original PO is needed to generate a new Registration Key23Chapter: TwinCAT OverviewThe System Manager and PLC Control can be also be accessed through this menu or the Windows Start menu Additionally the local TwinCAT System can be placed into its different modes Stop Mode The system is not capable of communication and no services are runningConfig 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 levelRun Mode (Requires License beyond 30 Trial) All services are enabled and running if configured to do so (i.e. Boot Project)24Chapter: TwinCAT Overview3. System Manager The TwinCAT System Manager is used to configure the links between Hardware and Software I/O Configuration All Fieldbus Hardware PLC Configuration PLC Run-Times (up to 4) NC Configuration Axes (real and virtual), Cam Tables, Interpolation Channels System Configuration Properties of the Target System and Real-Time Usage25Chapter: TwinCAT OverviewMenus and Controls File Menu Allows for creating a new file or opening a saved file. Additionally provides a way to open the CurrentConfig.tsm file from the Boot folder, by using Open from Target also referred to as The Red Folder.26Chapter: TwinCAT OverviewActions Any time a change is made to the System Manager, the Activate Configuration must be done to implement this change into the running system. Note: The first 6 commands in the Actions menu will be sent to the Target system either local or remote.27Chapter: TwinCAT OverviewThe tree view on the left provides access to the configurations of the system manager. When an item on the left is selected its information will be displayed on the right. Items can be added to the System Manager be Right-Clicking on an existing item. Become familiar with this, almost every item you wish to add in both the system manager and the PLC will be done by RightClicking and select Add... or Append System Configuration Provides information and settings for the overall TwinCAT System The settings available from the Properties of the TwinCAT icon can be accessed from here on a remote system.28Chapter: TwinCAT OverviewGeneral The TwinCAT version is provided here in bold The Choose Target button can be used to access a remote TwinCAT system.29Chapter: TwinCAT OverviewBoot Settings can be used to set the TwinCAT Mode on startup and the Auto Logon When pointed to a remote system these setting will be applied to the remote system. The Apply button must be used, and an Administrator level user name and password must be provided.30Chapter: TwinCAT OverviewReal-Time SettingsSettings Here the Base Time is set; no task can be set to a faster interval than the base time. The CPU limit of 80% means that TwinCAT will consume no more than 80% to run all of its tasks.31Chapter: TwinCAT OverviewOnline 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 secondsNote: Image taken from a laptop with power save features and CPU throttling enabled, both of these create latency problems.32Chapter: TwinCAT OverviewPriorities The list of tasks and their priorities can be seen here33Chapter: TwinCAT OverviewAdditional TasksTask 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 simulation34Chapter: TwinCAT OverviewWhen used for simulation the Auto start must be checked35Chapter: TwinCAT OverviewRoute SettingsCurrent Routes The Remote Computers shown in this list are the same as in the Properties of the TwinCAT icon.36Chapter: TwinCAT OverviewNC Configuration (Numerical Control) This is the software based motion controller of TwinCAT. The software side of all axes are configured here.Axes The software limits the total number of axes to 255, the real limit is the amount of CPU and RAM in the computer.37Chapter: TwinCAT OverviewThe Online tab provides an overview of the status of all axes38Chapter: TwinCAT OverviewAxes 1 Online The Online tab of each axis provides a useful interface to setup and troubleshoot an axis39Chapter: TwinCAT OverviewPLC ConfigurationIEC Project The PLC editor will create a tpy file that contains addressed variables that can be linked to hardware. The name of the PLC project file is shown directly below the PLCConfiguration The IEC1131 Tab shows the path of where the tpy file was located when it was added to the project. If addressed variables are added to the PLC program the ReScan button can be used to update the list of variables in the System Manager40Chapter: TwinCAT OverviewStandard Task The default task in the PLC is the Standard task and runs every 10msInputs of the PLC Program Input variables have a yellow icon, Output variables have a red icon41Chapter: TwinCAT OverviewOnce a variable has been linked (connected) to hardware the icon changes as below42Chapter: TwinCAT Overview4. PLC Control The PLC Control provides the user with a combination of tools. The IEC 61131-3 Language editors A Visualization Editor Task Configuration Utility The Beckhoff Compilers specific to the Target Hardware (BC, BX, CX-ARM, X86)43Chapter: TwinCAT OverviewIII.TwinCAT Software Installation5. TwinCAT VersionsThere are several builds within each version New builds are released primarily to accommodate new hardware New versions are released when features are added A Brief History TwinCAT 2.6 Build 315 August 2, 1999 TwinCAT 2.7 TwinCAT 2.8 Change from wsm to tsm Use of XML for system configuration Config Mode for scanning hardwareTwinCAT 2.9 TwinCAT 2.10 TcMC2.libTwinCAT 2.11 Build 1552 TwinCAT 2.11 R2 Change in preparation for TwinCAT 3 Chapter: TwinCAT Software Installation Required for CX5000TwinCAT 2.11 R344Release Notes:Changes from 2.10 to 2.11 TwinCAT Base System Integration of MDP (Modular Device Profile a generic interface for device information) Integration of configuration tool for AX5xxx drives Optimized behavior for use with Windows Vista and Windows 7 Optimization for TwinCAT running on Quad-core and Octo-core CPUs Time synchronization with EL6692 (EtherCAT bridge) Time synchronization with EL6688 (IEEE 1588/Precision Time Protocol) New modular structure of I/O drivers Base for new supplement products like TwinCAT Kinematic TransformationIn addition to the features available in 2.11, the following new features were implemented in Release 2 (2.11 R2): support for CX50xx controllers support for CU2508 (port multiplier) support for AX5805 (safety card for AX5xxx) support for EP1908 new Motion Control feature: multi-cam extended slave error handling for NC multi-linear coupling (multi-GearIn)In addition to the features available in 2.11 R2, the following new features were implemented in Release 3 (2.11 R3): CX50xx, additional interfaces like EtherCAT Slave EL7201 support (NC PTP) Supports new PCIe fieldbus adapters New Phasing functionality for NC PTP45Chapter: TwinCAT Software Installation6. Software, Download & Installation The TwinCAT software can be downloaded from www.beckhoff.com Select Download from the top of the page46Chapter: TwinCAT Software InstallationScroll down to the Software section and select TwinCAT 30 days versionSelect TwinCAT47Chapter: TwinCAT Software InstallationThe form must be filled in with a valid email address Below the form you can select the version and build of TwinCAT you would like to download After selecting the Registration button an email will be sent; to the address provided, containing a link to download the software48Chapter: TwinCAT Software InstallationSelecting the link in the email will start the downloadDouble-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 process49Chapter: TwinCAT Software InstallationIf you receive the following warning select RunSelect your preferred language and then select next50Chapter: TwinCAT Software InstallationThe InstallShield Wizard will begin the install process51Chapter: TwinCAT Software Installation When prompted select next52Chapter: TwinCAT Software InstallationAccept the license agreement and select next53Chapter: TwinCAT Software InstallationFill in the User Name and Company Name (This information will be viewable in the software) Use DEMO for the serial number54Chapter: TwinCAT Software InstallationSelecting the level of TwinCAT to install (All levels are inclusive of lower levels) CP Includes the ADS driver, used for OPC Server, Beckhoff Control Panels, and other ADS communication I/O Includes the system manager for configuring hardware, used when writing C/C++ code to control the I/O PLC Includes the IEC 61131-3 PLC editor and the Beckhoff compilers NC PTP Numerical Control for Point to Point motion with associated libraries NC I Numerical Control for Interpolated motion with associated libraries55Chapter: TwinCAT Software InstallationRegistration Type 30 Day demo Full functionality for 30 days, after 30 days TwinCAT will no longer go into run mode. Development and Remote connections are still possible. Re-installing will provide another 30 days Register now A System ID will be provided for you to call in with The recommended practice is to select the 30 Demo and then send screenshots of the System ID via email. Licenses can be provided within 24 hours except weekends and holidays56Chapter: TwinCAT Software InstallationSelect the additional features to install with TwinCAT The desired features should be selected here, afterwards select Next to continueTwinCAT I/O Allows the direct access to IO via a DLL. Can be installed with TwinCAT PLC or TwinCAT NC PTP. TwinCAT Scope View A software Oscilloscope for monitoring variables in real time TwinCAT Cam Server A Cam tool for setting outputs on Lightbus, has never been sold in North America, replaced by newer technology Chapter: TwinCAT Software Installation TwinCAT EDS and GSD files files for DeviceNet and Profibus hardware TwinCAT Remote Manager For managing different versions of TwinCAT on one PC. TwinCAT Drive Manager Used for Configuring the AX5000 servo drives TwinCAT BACnet/IP BACnet Server for building Automation and HVAC systems.57Specify the path for the TwinCAT installation The default path is highly recommended, project files that the user creates can be stored in any desired location58Chapter: TwinCAT Software InstallationSpecify the Program Folder for the TwinCAT installation The default path is highly recommended, project files that the user creates can be stored in any desired locationThe installer will now install the needed components Chapter: TwinCAT Software Installation59You must reboot the PC after the installer has completedAfter rebooting the PC you will see the TwinCAT icon in the Windows System Tray TwinCAT is in Stop Mode by default60Chapter: TwinCAT Software Installation7. Licensing and RegistrationSingle left click the TwinCAT Icon in the system tray, and select properties61Chapter: TwinCAT Software InstallationOnce properties is selected the TwinCAT System Properties window will appear. Select the last tab (Registration) on the top of the window. At this point you can take a screen capture of the current System ID and report it to your Inside Sales Representative.62Chapter: TwinCAT Software InstallationIV.PLC Overview8. IDEThe Integrated Development Environment (IDE) of TwinCAT provides a complete set of development tools for the PLC. TwinCAT PLC Control puts a simple approach to the powerful IEC languages at the disposal of the PLC programmer. Use of the editors and debugging functions is based upon the proven development program environments of advanced programming languages.The Left column provides four tabs at the bottom.63Chapter: PLC OverviewPOUs Program Organizational Units This will contain the code written by the programmer, Programs, Function Blocks, and FunctionsData Types Here the programmer can create Structures and Enumerations to be used in the PLC codeVisualizations Interface screens for use by Maintenance personnel or Operators can be created.64Chapter: PLC OverviewResources The resources tab contains several items. The Global Variable Lists, Library Manager, PLC Configuration, and Task Configuration are all accessible from this tab.A POU is opened by double-clicking on it.65Chapter: PLC OverviewThe POU contains 2 parts, the Declaration section, and the Code section. The first line of the declaration section defines the type of POU and the name of the POU. Following this is the local variable declaration, the variables that are local to this POU are defined between the Keywords VAR and END_VAR. Below the Declaration section is the Code section, this part of the window will contain the PLC code of the POU.Additionally there is a Message Window at the bottom.The Message window will show Errors, Warnings, and compile information.66Chapter: PLC OverviewThe Message Window can be hidden or shown, from the Window menu select Messages or the keyboard shortcut Ctrl + ESC9. ProgramsA program is a POU which returns several values during operation. Programs are recognized globally throughout the project. All values are retained from the last time the program was run until the next. Programs are called from either a PLC Task or another Program. If a one program calls another program, and if thereby values of the program are changed, then these changes are retained the next time the program is called, even if the program has been called from within a different program. Programs can call all types of POUs, they can call Functions, Function Blocks, and other Programs. By default when a new Project is started, a Standard Task is created that calls the Program MAIN, from MAIN all other POUs are called. Because Programs are recognized globally, the local variables declared inside of them will referenced by first using the name of the program and then the name of the variable, separated by a dot ., for example is the variable bStart is defined with an address as a local variable in MAIN, in the PLC-Configuration of the TwinCAT System Manager the variable will be MAIN.bStart, whereas a variable defined globally will only show the name of the variable.67Chapter: PLC Overview10. Data Types and ConversionsElementary data types form the foundation of the programmers tools to represent and use information. The elementary data types within TwinCAT Plc Control are below.68Chapter: PLC OverviewThe BOOL data type is used to define a Boolean or Bit-wise variable. The BOOL data type takes the value of either TRUE or FALSE at runtime. The conversion operator BOOL_TO_INT may be used to convert a TRUE/FALSE into 1/0, respectively. Declaration syntax: VariableName : BOOL := InitialValue ; Example: pushButton01 : BOOL ;Declaration with Initial Value: drainValveOpen : BOOL := TRUE ; Use the {BYTE, WORD, DWORD, SINT, USINT, INT, UINT, REAL, LREAL} data set is to define an appropriate value range for a variable. Declaration syntax: VariableName : DataType { := , Busy=> , Error=>bErrorWritePoint_1st , ErrorID=>iErrorIDWritePoint_1st ); (*Use new Data for Point 5*) fbMC_SetCamOnlineChangeModeTable1_1st( Execute:= TRUE , ActivationMode:=MC_CAMACTIVATION_ATMASTERAXISPOS , ActivationPosition:=370 , MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET , SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET , CamTableID:=1 , Done=> , Busy=> , Error=> bErrorChangeMode_1st, ErrorID=>iErrorIDChangeMode_1st ); := := := := := := 5; 15; 1; 1; 75; 75;29 0Chapter: Camming(*New data for point 5 of the Cam Table*) VM_MotionFunctionPoints[5].PointIndex VM_MotionFunctionPoints[5].FunctionType VM_MotionFunctionPoints[5].PointType VM_MotionFunctionPoints[5].RelIndexNextPoint VM_MotionFunctionPoints[5].MasterPos VM_MotionFunctionPoints[5].SlavePos (*Buffer the Data for Point 5*) fbMC_WriteMotionFunctionPoint5_2nd( Execute:=TRUE , CamTableID:=1 , PointID:=5 , Point:=VM_MotionFunctionPoints[5] , Done=> , Busy=> , Error=>bErrorWritePoint_2nd , ErrorID=>iErrorIDWritePoint_2nd );:= := := := := :=5; 15; 1; 1; 75; 0;(*Use new Data for Point 5*) fbMC_SetCamOnlineChangeModeTable1_2nd( Execute:= TRUE , ActivationMode:=MC_CAMACTIVATION_ATMASTERAXISPOS , ActivationPosition:=730 , MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET , SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET , CamTableID:=1 , Done=> , Busy=> , Error=> bErrorChangeMode_2nd, ErrorID=>iErrorIDChangeMode_2nd );29 1Chapter: Camming38. Motion Functions vs. Position Tables a. Position TablesGeneral Table Conventions Tables only contain binary data. Table can be read from an ASCII file but you have to parse the file. A table consists of a header (the first line) and the table data (the remaining lines). The header contains two numbers of type unsigned short. The first column contains the number of lines (without header), while the second column contains the number of columns (for table-slave tables this is always 2). There are no separating characters between the data. Apart from the header, the table only contains data of type double. The first column (with the exception of the header line) contains the master positions, while the second column contains the associated slave positions (both in mm). There are no separating characters between the data. The quantity of data is restricted to 64 KB (TwinCAT Version 2.6). (This might be greater in newer versions) A position table is a 2D array that provides a slave position relative to the master position. The downside of a position table is that the segments between defined points are calculated in a straight line between the points. Therefore the more points on the table the shorter the segments and the better the motion. Most 2D tables contain at least 1000 points and are commonly generated by 3rd party software using a mathematical formula (similar to a motion function) to create a table of 1000+ points.29 2Chapter: CammingBelow are the points generated by using Motion Functions from our above sample code. The values highlighted in yellow are the master. The values highlighted in red are the defined points. If this was a table of points the Slave axis values would increase linearly.29 3Chapter: Cammingb. Motion FunctionsA motion function (MF) describes a cam disc via mathematical functions. It sub-divides the curve into appropriate segments (sections), for which different motion laws, i.e. special mathematical functions, can be used (for cam examples see: Cam design tool examples). The motion laws for mechanical cams are defined in VDI guideline 2143 and other documents. The electronic cams in TwinCAT use these functions, among others. The motion functions realize these motion functions directly in the real-time driver of the NC. Unlike classic table couplings that only transfer discrete steps (scatter plots) in the form of larger data quantities to the NC, the complete information is stored in the NC in very compact form. Problems originating from data granularity (position reference points) in the table are thus eliminated. The realization of motion laws in the NC has a further crucial advantage: A motion diagram, i.e. the complete description of the motion of a slave axis, can now simply and clearly be defined and modified from the PLC. Associated PLC function blocks make the application of this functionality very convenient. Users can influence not only the complete motion description, but also individual segments or subsections. In order to ensure that the drive system can actually implement a cam in practice, the system calculates characteristic values (such as maximum and minimum position values, velocity and acceleration etc.), which the user has to analyze. The resulting dynamic limit values ultimately depend on the motion of the master and relate to constant master velocity. The characteristic values are thus calculated with the idealized assumption of constant master velocity. In addition, the mean velocity and the effective acceleration are calculated. These values may be used, for example, for calculating the effective torque or the operating point PA (nm ; Meff) in the torque/speed diagram of the motor. The PLC can access the current characteristic values of the NC via function blocks. In the cam design tool (TwinCAT Cam Design Editor) the decision whether to use classic table couplings (scatter plot) or motion functions can be configured via an associated selection. Subsequently, either the position tables or the motion function points are generated when the configuration is activated. If motion functions are used, these points can subsequently be modified individually by the PLC. It is possible to modify individual values or complete sections of the motion functions online according to associated rules, i.e. while the cam is active. Very flexible cams can thus be realized.29 4Chapter: Cammingc. Definition of a PointThe information contained in the cam design tool table is sufficient for defining the motion in the NC. However, closer inspection of this MF table reveals the presence of redundant data. Because the motion is described in segments (sections), for motion diagrams with simple interrelationships the end point of a section is identical to the starting point of the next segment. The more complex point types offered by the cam design tool, such as slide point, are not yet implemented. In addition, users want to be able to deactivate individual points in a particular motion diagram (MOTIONPOINTTYPE_IGNORE, referred to as IGNORE below) at a later stage. These requirements lead a description that in addition to the starting point of a segment, including the point information (velocity, acceleration, point type), also contains the segment information (function type, symmetry value).d. Point structurePointIndex FunctionType PointType RelIndexNextPoint MasterPos SlavePos SlaveVelo SlaveAcc SlaveJerk/Symmetry UINT32 Point index UINT16 Function type UINT16 Point type Relative index of the end point (default: 0, subsequently corresponds INT32 to 1) REAL64 Master position REAL64 Slave position at this reference point REAL64 Slave velocity at this reference point REAL64 Slave acceleration at this reference point Slave jerk at this reference point or symmetry value of the segments REAL64 for rest in rest motion lawsIn this structure, a relative index is used to refer to the point index of the end point of this segment. In order to keep the definition simple for motion diagrams with simple interrelationships, the IGNORE points are indeed ignored completely. The relative point index is therefore automatically adjusted internally. The default value of the relative point index may therefore be zero, although for a standard list with simple link the value should be 1. The user therefore does not have to update this information. The possible point types of the cam design tool therefore includes the IGNORE point.29 5Chapter: Camminge. Point typesMOTIONPOINTTYPE_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 pointv=0, a=0 v=?, a=0 v=0, a=? v=?, a=?At Rest the velocity and acceleration will be 0. A Velocity point will have 0 acceleration and the velocity will be defined by the Cam Table or the user. A Turn point will have a velocity of 0, and the acceleration will be calculated by the Cam Table or the user. A Motion point is the default type in which the velocity and acceleration will be calculated by the Cam Table. Since no points can be added while the MF is active, the IGNORE point type enables associated points to be included. These can be activated online at a later stage by specifying the associated values (point type not equal IGNORE). Warning: The master position has to be either strictly monotonic rising or falling. Otherwise it is rejected with an associated error message.29 6Chapter: Camming39. Cam Design Tool a. OverviewA cam design editor is used to design the movements for a cam plate. A cam design editor is integrated into TwinCAT, and it can be found in the System Manager under the NC Configuration, under the Tables item. The cam design editor is a flexible tool that provides the user with optimum support and only the minimum of restrictions. Therefore, responsibility for the choice of parameters lies with the user. The user, for instance, should carefully check whether the starting and end points correspond exactly to requirements. On the other hand, the user is offered the best possible assistance for checking velocity, acceleration and jerk through the graphic display facilities. With all these options, however, the user must remember that it is physics that sets the limits to the possible movement.29 7Chapter: Cammingb. Creating a Cam TableRight click on Tables and select Append TableLeave the defaults and select OK.29 8Chapter: CammingRight click on the Master and select Append SlaveLeave the defaults and select OK.It is possible here to insert additional masters, and to enter corresponding slaves under. If you then click the master in the structure tree, the property pages can be used to set the properties not only of the master, but also of the associated slaves.29 9Chapter: Camming30 0Chapter: CammingThe general procedure for developing a design of a cam is based on VDI (Verein Deutscher Ingenieure) Guideline 2143. The rough design of the movement - the movement plan - defines the starting and end points of the movement section. The editor, however, does not make a distinction between the movement sketch and the movement diagram containing the detailed description of the movement, they will show the same data.The user's interface to the cam design editor is graphic. Following interactive graphic entry of the points in the graphic window, the co-ordinates of the points are displayed in the table window above it. New points can only be inserted in the graph, and it is only possible to delete existing points via the graph. The properties of the points - the co-ordinate values or their derivatives - can also be interactively manipulated in the table window.30 1Chapter: CammingNot just the position, but also the velocity, acceleration and jerk can be displayed in the graphic area.The mode of the display can be changed by a right mouse click in the graphic window, which opens the following menu:Thus a separate Graphic Window is opened for each derivative.30 2Chapter: Cammingi. Master TabThe minimum and maximum master positions can be specified. The Normed switch allows you to choose between a normalized display and a physically oriented display in which the velocity, acceleration and jerk of the slave are shown against time. The normalized display refers these displays to the master position. The velocity of the master is needed for the physically oriented display; it is necessary, first of all, to distinguish here between a linear and a rotary axis (angular values quoted in degrees). When the data is transferred to the NC, the choice between a linear and a rotary axis specifies whether the table type is linear or cyclic. For a rotary Master, the first and second derivatives at the end are set equal to the corresponding values at the start of the movement cycle, if the starting and end positions of the slave correspond to the minimum and maximum positions of the master. The increment specifies the increment of the master position used for output of the table into a file. If an equidistant table is to be generated, the total length (the actual maximum minus the minimum) should be divisible by the increment. When the project is saved in the registry, the information required to generate and transfer the tables with this increment is created in the NC. The Rounding Value rounds the master position in the graphic input with the given value. Fixed Table / Motion Function: When exporting the cam table to a .csv file this option will either generate a straight line (Fixed Table) or calculate the points using the Motion Function.30 3Chapter: Cammingii. Slave TabMaximum and minimum values can be specified for position, velocity, acceleration and jerk. These values can be used as initial specifications when the graphic window is first displayed. Adjustment to the current values in the diagram can be performed in the relevant graphic window with the Adjust to Extreme Values command. The Rounding Value rounds the slave position in the graphic input with the given value. Export allows the slave's values to be stored in an ASCII file in the form of master position, slave position, on one line each. The master position increment is specified in the master's property page. Import allows files in the format just described to be read in. The values can then be displayed as cubic splines. The type of the spline still needs to be adjusted in the table, according to the values. The Table Id provides a unique identifying number (1..255) for the table, with the aid of which the table data is stored in the NC. It can be changed to using a right mouse click in the menu with the Change Id... command.30 4Chapter: Cammingc. Graphic WindowThe slave's position and derivatives are each shown in separate graphic windows.The associated toolbar includes both buttons that are only related to the graph as well as the special commands for the cam plate editor.When the Overview Window is switched on, it is not only possible to see which section the graph window is looking at, but this section can be moved, or it is possible to zoom to a new section. The horizontal and vertical Scrollbars can be used to shift the Graphic Section; the horizontal scrollbar acts on all the graphic windows at the same time. If you're using an IntelliMouse with a ScrollWheel you can zoom with the ScrollWheel.30 5Chapter: CammingThe toolbar and its commands can be displayed or hidden via the menu that is opened by a right mouse click (in the graphic window).This window also has a Horizontal Scrollbar if the Horizontal Scrollbar option is activated. All the horizontal scrollbars are synchronized. The Cross on Point option causes the starting and end points of a movement section to be indicated by a cross. The Show Online Data displays the table data that is currently in the NC, with the associated table ID as a cubic spline. Currently this can result in a distorted display; because the linear tables are displayed as natural splines (second derivative at the edges equals 0). The data is displayed in the same color, but somewhat darker. The data is automatically transferred by ADS, as soon as Online Mode is switched on. The current data can be read by switching the mode on and off. When the project is saved in the registry (Activate Configuration), the information required to generate and transfer the tables is created in the NC.30 6Chapter: Cammingd. Tables WindowThe values for the movement section are displayed in the table window:The values can be altered via the keyboard, remember that restrictions are applied arising from the choice of function type or other boundary conditions for the points. Since movement sections are normally continuous; except for Slide Points, the end point and its derivatives at the end of the section are equal to the corresponding values at the start of the following movement section. For this reason it is normally always the initial values that should be manipulated. In addition to this, if any inconsistencies are seen in the graph of a completed movement diagram, the agreement of the initial and end points should be checked. If certain values in the table cannot be changed, consideration should be given to the boundary conditions applying to the points. It may be appropriate to change them. The boundary conditions limit the scope of the functions in sections in accordance with their type. Chapter: Camming The symmetry of the functions can only be changed for the following types: Polynom3, Polynom5, Polynom8, Sinusline, ModSinusline, Bestehorn, and AccTrapezoid. Normally the inflection on the curve (acceleration = 0) at 50 % = 0.5. This value can be changed in the table or in the diagram of the acceleration (Example 6).30 7i. Function TypesIn addition to the standard types (synchronous/automatic), which can be changed by command on the graph, the function type can also be modified in the combo box. When the combo box; or a field in the first column, is first clicked, a rectangle is temporarily shown in the position window, with the initial and end points of the section at its corners. As soon as another field in the table window is activated, either the rectangle for this one is shown, or no rectangle is displayed at all.The types correspond to those of VDI Guideline 2143; additionally, there are the cubic splines, with the boundary conditions of natural, tangential and periodical.Changing the type of spline at the first point implies that the spline type as a whole is changed, including that of the end point. Chapter: Camming If Spline Tangential is chosen as the spline type, the boundary conditions (first derivative at the starting and end point) should be modified. At the Motion functions with fit to boundary values the R is for Rest, V for Velocity, T for Turn, and M for Motion.30 8ii. CommandsThe cam design editor offers the following commands, and these may be called up through the toolbars on the relevant graphic window:All these commands are only applicable to the associated window.Adjustment to the Extreme Values The window's coordinates are adjusted to the extreme values of the movement. Measurement of Distance The horizontal and vertical distance to the current point from the point first clicked with the left mouse button is displayed at the top right hand corner of the window (please hold the mouse button down for this). Current Position The absolute horizontal and vertical position of the point currently clicked with the left mouse button is displayed at the top right hand corner of the window (please hold the mouse button down for this). Horizontal Shift Moves the selected point horizontally In the velocity window for synchronous functions: shift along a straight line in the position window. The left-hand edge of the graphic area can be temporarily moved in this way, so that the scale can be more easily read. Vertical Shift Moves the selected point vertically In the velocity window for synchronous functions: adjustment of the position in the position window to the velocity. In the acceleration window for automatic function: adjustment of the acceleration. Chapter: Camming Shift Moves the selected point.30 9The following commands only apply in the graphic window for position: Insert Point Inserts a point at the cursor position. Synchronous Function The chosen section is passed through with a synchronous function. Automatic Function An optimum function is selected automatically for the chosen section including adjustment to the boundary values. Delete Point The selected point is deleted, as is the corresponding section.The following four items define specific boundary conditions for the points: The point type is correspondingly displayed in front of the point in the table window. This restriction can mean that the end value of a section does not agree with the initial value for the following section. Rest Point The selected point is defined as a rest point (boundary condition: v=0, a=0). Velocity Point The selected point is defined as a velocity point (boundary condition: a=0). Reversal Point The selected point is defined as a reversal point (boundary condition: v=0). Movement Point The selected point is defined as a movement point (no boundary conditions).Delete Slide Point The slide point is deleted and the sections are joined together as they were previously.31 0Chapter: CammingSlide Point The starting position of the following section or the end position of the previous section is set at the cursor position, without changing the selected section. The point can then be moved on to the section using horizontal shift.40. Cam Table Scaling a. OverviewAs required by the application the scale of the Cam Table can be adjusted. Master and Slave offsets can also be given to provide more flexibility to the programmer.b. MC_CamScalingA cam plate coupling can be scaled with the function block MC_CamScaling. The raw table data of the cam plate are not affected, the scaling refers to an existing master/slave coupling. The following parameters can be modified, scaling factors for master and slave, and offsets for the cam plate within the coordinate system. Optionally, the modification will only take effect from a certain master position, enabling precise scaling during the motion. Caution when scaling during motion! The slave position at the time of scaling should only be affected slightly by the change. The status flag Axis.Status.CamcalingPending can be used to check whether a scaling procedure is queued. Inputs VAR_INPUT Execute : BOOL; ActivationMode : MC_CamActivationMode; ActivationPosition : LREAL; MasterScalingMode : MC_CamScalingMode; SlaveScalingMode : MC_CamScalingMode; MasterOffset : LREAL; SlaveOffset : LREAL; MasterScaling : LREAL := 1.0; SlaveScaling : LREAL := 1.0; END_VAR Execute: The command is executed with a rising edge at input Execute31 1Chapter: CammingActivationMode: ActivationMode specifies the scaling time and position.ActivationPosition: Master position at which a cam plate is scaled, depending on the ActivationMode If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used; the position refers to the nonscaled cam plate. If the position in the application refers to the scaled cam plate, it can be divided by the MasterScaling value before the function block is called. MasterScalingMode: Optional scaling mode for the master position of the cam plate SlaveScalingMode: Optional scaling mode for the slave position of the cam plate MasterOffset: Offset to the master position of the cam plate SlaveOffset: Offset to the slave position of the cam plate MasterScaling: Scaling of the master position of the cam plate SlaveScaling: Scaling of the slave position of the cam plate Outputs VAR_OUTPUT Done : Busy : Error : ErrorID : UDINT; END_VARBOOL; BOOL; BOOL;Done: becomes TRUE, if the cam plate was created successfully. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done or Error, is set. Error: Becomes TRUE, as soon as an error occurs. ErrorID: If the error output is set, this parameter supplies the error number. Inputs/outputs VAR_IN_OUT Master : AXIS_REF; Slave : AXIS_REF; END_VAR31 2Chapter: Cammingc. MC_CamScalingModeTYPE MC_CamScalingMode : ( MC_CAMSCALING_USERDEFINED, (* user defines scaling parameters - scaling and offset *) MC_CAMSCALING_AUTOOFFSET, (* offset is calculated automatically for best result *) MC_CAMSCALING_OFF (* no modification accepted *) ); END_TYPE Type and scope of the scaling of a cam plate coupling via function block MC_CamScaling. MC_CAMSCALING_USERDEFINED: The scaling and offset are retained unchanged. The user has to calculate the scaling and offset such that a jump in the position is avoided. MC_CAMSCALING_AUTOOFFSET: The scaling takes effect and the system adjusts the offset such that a jump in the position is avoided. Scaling should nevertheless occur during a phase with slave velocity 0, since otherwise a jump in velocity cannot be avoided. MC_CAMSCALING_OFF: The scaling and offset are ignored. This mode is used when only slave scaling (i.e. without master scaling) is to be implemented. Autooffset Autooffset mode ensures automatic adaptation of a cam plate offset. Autooffset can be used independently for the master or slave axis of a cam plate and affects both switchover and scaling of cam plates. The function operates based on the rules described below. Master-Autooffset Master-Autooffset Prevents discontinuity of the master position of the cam plate in the axis coordinate system during switching of cam plates with different master cycle or scaling of cam plates (master scaling). This function is required because the relative position of a cam plate in the axis coordinate system depends on the master cycle. If the master cycle is changed, e.g. through scaling, the position would change. Master-Autooffset determines the master offset of the cam plate such that the master position within the cam plate is maintained. For scaling or switchover to a cam plate with a different master cycle this means that the relative (percentage) position before and after the switchover is identical.31 3Chapter: Cammingi. Example:A cam plate has master cycle of 360 and is scaled by a factor of 2 to 720. Scaling takes place at the 90 position within the cam plate, i.e. at 25% of the start of a cycle. After the scaling the relative master position in the cam plate at 180 is therefore also 25% of the start of a cycle.During a switchover at the edges of a cam plate (see MC_CamActivationMode MC_CAMACTIVATION_NEXTCYCLE), Master-Autooffset ensures a seamless sequence of cam plates, both for cyclic and linear cam plates.31 4Chapter: CammingMaster-Autooffset cannot be used for a cam plate with relative coupling or switching, since these functions are mutually exclusive. Further restrictions apply to initial coupling. These are shown in the following table.Slave-Autooffset Slave-Autooffset calculates a slave offset such that discontinuities in the slave position are avoided during cam plate switching or scaling. The slave offset is adjusted to ensure that the slave position is identical before and after the action. If both Master Autooffset and Slave-Autooffset are used for cam plate switching or scaling, the master offset is calculated first, followed by the slave offset. Slave-Autooffset can be used with any MC_StartMode and will always adjust the cam plate such that the slave position doesn't jump.31 5Chapter: Cammingii. 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_IF31 6Chapter: Camming41. Cyclic Cam Plates with LiftPlease 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.31 7Chapter: CammingThe 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.31 8Chapter: Camminga. MC_StartModeTYPE 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.31 9Chapter: CammingAs 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.32 0Chapter: Camming42. Cam Out and Restarting a. OverviewMC_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.32 1Chapter: Cammingb. MC_CamOutThe 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 bestopped 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_VARBOOL; BOOL; BOOL;Done: Becomes TRUE, if the axis was successfully uncoupled. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done or Error, is set. Error: Becomes TRUE, as soon as an error occurs. ErrorID: If the error output is set, this parameter supplies the error number. Inputs/Outputs VAR_IN_OUT Slave END_VAR:AXIS_REF;Slave: Slave axis data structure. The axis data structure of type AXIS_REF addresses an axis uniquely within the system. Among other parameters it contains the current axis status, including position, velocity or error status.32 2Chapter: Cammingc. MC_HaltMC_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. Chapter: Camming32 3Outputs VAR_OUTPUT Done Busy Active CommandAborted Error ErrorID END_VAR: BOOL; : BOOL; : BOOL; : BOOL; : BOOL; : UDINT;Done: The Done output becomes TRUE, if the axis was stopped and has come to a standstill. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. When Busy becomes FALSE again, the function block is ready for a new command. At the same time one of the outputs, Done, CommandAborted or Error, is set. Active: Active indicates that the command is executed If the command was queued, it becomes active once a running command is completed. CommandAborted: Becomes TRUE, if the command could not be fully executed. The running command may have been followed by a Move command. Error: Becomes TRUE if an error occurs. ErrorID: If the error output is set, this parameter supplies the error number. Inputs/outputs VAR_IN_OUT Axis END_VAR: AXIS_REF;Axis: Axis data structure The axis data structure of type AXIS_REF addresses an axis uniquely within the system. Among other parameters it contains the current axis status, including position, velocity or error status.32 4Chapter: Camming43. MC_CamIn AppendixTwinCAT PLC Library: MC (Version 2)a. Axis coupling with cam platesThe function block MC_CamIn can be used to establish a cam plate coupling (or table coupling) between a master axis and a slave axis. Note that prior to the coupling the slave axis has to be at a position defined by the cam plate. After the coupling and once the master has been started, the slave position is calculated directly from the cam plate. The slave axis is therefore not slowly synchronized with the cam plate, but it will jump if it is not already at the table position. In practice the question arises; what position the slave should be in prior to the coupling, and how this is calculated. The following figures illustrate the procedure. Notes: For all subsequent calculations only axis set positions are used. The actual positions are not used in the calculations, since they would lead to calculation errors, particularly with cyclic cam plates. Only absolute table couplings are considered. For relative couplings, the coupling position of the master or slave axis is considered in the calculations as an additional offset.b. Linear cam platesA linear cam plate is only defined via a limited master position range. Outside this range the slave position is defined by the first or last table position. The slave therefore stops at the table edges as soon as the master leaves the defined range.The diagram shows that the absolute axis coordinate system (blue) does not have to be identical to the cam plate coordinate system (red). The cam plate coordinate system may be offset by a master offset or a slave offset. Scaling is also possible.32 5Chapter: CammingThe slave position relating to a certain master position can be determined via the function block MC_ReadCamTableSlaveDynamics . The block refers to the raw table data, which means that offsets and scaling factors have to be considered via the PLC program itself. Initially, the master offset is added to the current master position. If the cam plate is to be scaled, it is divided by this scaling factor. MasterCamTablePosition := (MasterPosition + MasterOffset) / MasterScaling; The master table position is used as an input parameter for the function block MC_ReadCamTableSlaveDynamics. The result is converted to an absolute slave position with slave offset and scaling, if necessary. SlaveCamTablePosition := ReadSlaveDynamics.SlavePosition; SlavePosition := (SlaveCamTablePosition * SlaveScaling) + SlaveOffset; The slave is moved to this position prior to the coupling. Alternatively, the master may be moved to a position that corresponds to the current slave position. However, generally this position cannot be determined from the cam plate, since the cam plate may be ambiguous. Note: Since the master offset is added in the first formula, a positive offset leads to the cam plate coordinate system being shifted to the left in negative direction. Accordingly, the master offset in the diagram is negative. A positive slave offset leads to the cam plate coordinate system being shifted upwards in positive direction.32 6Chapter: Cammingc. Cyclic cam plates without liftA cyclic cam plate without lift is characterized by the fact that the slave start and end positions in the table are identical. The slave therefore moves cyclically within a defined range, without changing its position permanently in a particular direction.For these cam plate types, master/slave coupling requires the same preparation as for a linear cam plate. The starting position of the slave can therefore be calculated as described above. It is not necessary to use the modulo position of the master for the calculation, since the absolute position is already correctly taken into account via the coupling command.32 7Chapter: Cammingd. Cyclic cam plates with liftThe lift of a cyclic cam plate is the difference between the last and the first table position of the slave.Such a cam plate is continued cyclically at the end of the table. The slave position does not jump back to the initial table value. Instead, the motion continues steadily. With each new cycle, the lift is therefore added as an additional internal slave offset or subtracted if the motion is reversed.32 8Chapter: Camminge. Uncoupling and re-coupling for cyclic cam plates with liftIf a slave is coupled to a cam plate with lift, the coupling is always done in the basic cycle (red coordinate system), i.e. without added lifting distances. If the slave is uncoupled after a few cycles and then recoupled, the slave position returns to the basic cycle. If necessary, this behavior has to be taken into account and compensated by re-calculating the slave offset.MasterCamTablePos := (MasterPosition + MasterOffset) / MasterScaling; The master table position is used as input parameter for the function block MC_ReadCamTableSlaveDynamics. The result is converted to an absolute slave position with slave offset and scaling, if necessary. In addition, the number of pending lifts must be calculated and added to the slave position. SlaveCamTablePosition := ReadSlaveDynamics.SlavePosition; Lift number := MODTURNS( (SlavePosition - SlaveOffset), SlaveHub ); NewSlaveOffset := SlaveOffset + (SlaveHub * lift number); SlavePosition := (SlaveCamTablePosition * SlaveScaling) + NewSlaveOffset; The Autooffset function can simplify the calculation of offsets, particularly for switching of cam plates. Chapter: Camming32 944. Diagnostics a. OverviewThe following covers the error codes as provided by either the function blocks or the TwinCAT System Manager. The error codes provided by the system; although complete, are sometimes not easily understood by new users. The explanations of the error codes provided are based solely on the experience of my self and others. The added descriptions are only relevant for helping to find a problem within TwinCAT, this document will not suffice if your problem is within your .NET or other 3rd party application.b. Error FormatThe error codes within TwinCAT are given in accordance with the following structure. All errors are generated in hexadecimal. The errors range from 0x0000 to 0xFFFF. The most significant byte 0xn000 can be considered as the grouping for the errors. When needed a sub subgroup will be identified by the second byte 0x0n00. The remaining bytes are used to give the exact error code. The errors between 0x0000 and 0x0FFF refer to the TwinCAT System itself. These errors indicate that something is fundamentally wrong with your system. The cause of the errors can vary greatly; it can be anything from a corrupted file to forgetting to start the PLC, or an incorrect linking in the system manager. Remember that just because TwinCAT allows you to do something, that doesnt mean that thats what you wanted to do.33 0Chapter: CammingError 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_PRJSPECIFICGlobal Error Codes 0x0000 0x6 0x7 target port not found target machine not foundThese errors commonly occur when setting up a system for the first time, and the frequency increases when switching between development, simulation, and machine. This error is trying to tell you that there is a communication problem, and is commonly an ADS communication problem. If all communication is local, then make sure TwinCAT is running the correct System Manager file, and that the correct PLC program is loading and running. If you are unsure of what system manager file is running, the red folder in the system manager will Open from Target. If communication is remote then check the AMS router on both PCs to make sure the info is valid. Ping the IP of address of one PC from the other to make sure cabling and network configuration is correct. General ADS Error Codes 0x0700 The common errors in this group are fairly self-explanatory. These normally occur because of something not being configured correctly. It could be an incorrect or missing link in the system manager or the PLC code that is calling the ADS service has an invalid parameter.33 1Chapter: CammingNC Errors 0x4000 The NC error group is comprised of 9 sub-groups. These sub groups cover all things motion, from Overtemp errors to syntax errors in G-Code to bad PLC commands. NC Error Sub Groups 0x40nn 0x41nn 0x42nn 0x43nn 0x44nn 0x45nn 0x46nn 0x4Ann 0x4Bnn General NC Errors Channel Errors Group Errors Axis Errors Encoder Errors Controller Errors Drive Errors Table Errors NC-PLC ErrorsGeneral NC Errors 0x40nn 0x4016 used, 'Table identifier not allowed' Either an unacceptable value (not 1...255) has been or a table that does not exist in the system has been named. Check your value of your TableID0x4052 for'Axis not ready for operation' The axis is not complete, and is therefore not ready operation. This is usually a consequence of problems at system start-up. If the Ready Status of the Axis is not TRUE and the axis receives a command then this error will be given. This value is held in the NCDRIVESTRUCT_IN2 of the Axis 1_Drive and is linked to the Drive Status Word of the drive under the I/O Configuration.fromFor an AX5000 the first place to check is on the Configuration Tab of the axis. Look at the ErrorID, it must be at D013: Axis Op. A value less than 13 or an F value will prevent the axis being ready. The R button on the right side of the ErrorID display will issue an IDN99 reset command to the drive. Chapter: Camming33 2Channel Errors 0x41nn These errors are for NC-I and are not within the scope of this document. Group Errors 0x42nn These errors are for NC-I also. However there is one here that should be covered. 0x4208 'Single step mode not allowed' The flag for the activation or deactivation of single step mode is not allowed. Value 0: Passive (buffered operation) Value 1: Active (single-block operation). Prior to MC2 if an axis was given a command while the Status bit Has Job was TRUE this error would be given. This error does not stop the axis; it just appears in the Log window of the System Manager. With the new Buffered Moves in MC2 this shouldnt be an issue any more. However keep in mind that if you issue a second move before the first one is complete, where previously would ignore the command, it will now Abort the previous command and Execute new one.it theAxis Errors 0x43nn These Errors relate to the parameterization and monitoring of an axis. The majority of these errors are for incorrect (out of range) parameters or monitoring the control of the axes. Encoder Errors 0x44nn These Errors relate to the parameterization and monitoring of an encoder. The majority of these errors are for incorrect (out of range) parameters or monitoring the encoder of the axes.Controller Errors 0x45nn These Errors relate to the parameterization and monitoring of the axis controller. The majority of these errors are for incorrect (out of range) parameters or monitoring the control of the axis position. Drive Errors 0x46nn These Errors relate to the parameterization and monitoring of the drive and motor. The majority of these errors are for incorrect (out of range) parameters or monitoring the state of the drive and motor.33 3Chapter: CammingTable Errors 0x4Ann These Errors relate to the parameterization and initialization of a cam table. The majority of these errors are for incorrect (out of range) parameters or invalid cam table data. The Flying Saw function blocks will generate these errors as well as Cam Table function blocks. 0x4A06 'Table is not monotonic' The value for the step size is not allowed, because, for example, it is less than or equal to zero. When generating a Cam Table from the PLC or from the Flying Saw this error can happen. The most common cause from the Flying Saw is the Master SetPos is within 1E-12 of the Master Sync position when the Execute turns TRUE. This can also happen for a Cam Table generated by the PLC when the position would require the Master Axis to move backwards.PLC Errors 0x4Bnn The majority of these errors are well described within the Information System. NC-PLC Errors TwinCAT NC I TcMcCam TcNc TcRemoteSync TcMC2 0x4B00..0x4B0F 0x4B10..0x4B2F 0x4B30..0x4B3F 0x4B40..0x4B4F 0x4B50..0x4B5F 0x4B60..0x4B6FTcPlcInterpolation 0x4B70..0x4B7F33 4Chapter: CammingVIII.Remote Connections45. Embedded Controllers The TwinCAT AMS Router allows for TwinCAT to communicate between computersConfiguring your local IP address Establishing a Route to the Target Opening the active system manager of the Target Chapter: Remote Connections33 5Click Start Expand Connect To Click Show all connectionsThe network card you are going to use should be the only one with a Status of Connected. If the other cards are connected TwinCAT may try to one of scan these networks for devices and not scan the correct network.Right-Click on the Network Card and select Properties Chapter: Remote Connections33 6Scroll to the bottom of the list. Select Internet Protocol (TCP/IP) Click on Properties33 7Chapter: Remote ConnectionsSelect Use the following IP address Enter the following IP address. 192.168.0.2 Enter your Subnet mask Click OK33 8Chapter: Remote Connections Click OK33 9Chapter: Remote ConnectionsIf the below window appears click on STOP Installation. If you click on Continue Anyway windows will install the Real-Time Ethernet driver for your network card. You can do this if you like, but it is not needed for connecting to remote devices.Click on the TwinCAT icon in the Windows System Tray, and select System Manager.34 0Chapter: Remote ConnectionsOpen a new System Manger file. Select File, then NewSet/Reset TwinCAT to Config mode.Click Ok34 1Chapter: Remote ConnectionsSelect SYSTEM Configuration, then Choose TargetClick Search (Ethernet)34 2Chapter: Remote ConnectionsIf you know the IP address of the remote device it can be entered. Click Enter Host Name / IP: It is also possible to use the Broadcast Search button to look for computers on the local network that are running TwinCAT, however a broadcast search will not go through a network router.Select the computer form the list and select Add Route34 3Chapter: Remote ConnectionsIf the computer you are connecting to is using DHCP then the Address info should be set to Host Name, if a static IP address is being used then set Address Info to IP AddressEnter User name and password of an Administrator account on the Target PC Not required for Windows CE Click OKVerify the X appears in the Connected column. Click on Close.34 4Chapter: Remote ConnectionsSelect BasePLC Click OK34 5Chapter: Remote ConnectionsVerify connection to BasePLC the red background indicates you are connected to a remote device. Verify the device status. A green background indicates that TwinCAT is running on the remote device. A blue background indicates the remote device is in config mode. A yellow background indicates a Timeout. Click on the red folder to Open from TargetIf the below window appears click on Yes34 6Chapter: Remote ConnectionsFile name of the System Manager *.tsm file Name of remote device List of hardware connected to the device34 7Chapter: Remote ConnectionsIX.Appendix I Variable Naming Convention46. ScopeThe 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 componentsThese guidelines are based on a history of experience in software development by Beckhoff and our customers. The programming guidelines must be used for the development of new programs, unless the customer has specified other guidelines for the project. The programmer can judge the extent to which the guidelines can be applied to existing programs.34 8Chapter: Appendix I Variable Naming Convention47. Programming System SettingsThe TwinCat project options must be defined uniformly to achieve identical notation for individual editors and for documentation. This is especially true in multi-user projects.a. FontA non-proportional font is recommended with the following settings: This can be adjusted under 'Project -> Options -> Editor -> Font'.Font: Tahoma Font style: Regular Size: 12 Character set: Westernb. Tab WidthA tab width of 4 is recommended. This can be adjusted under 'Project -> Options -> Editor'.34 9Chapter: Appendix I Variable Naming Convention48. Naming a. GeneralThis naming convention applies to variables, constants, and program organization units (POU). Choose a relevant, short, description for each designator name and the designator should be self-explanatory. The first letter of each word in the designator is capitalized (example: FileSize). Please limit the name to 20 characters, the fewer the better.Prefixes are included with the designator name to indicate scope, property, and type as will be explained below.b. Case SensitivityPay close attention to case sensitivity, especially for prefixes, to improve readability.NOTE: The TwinCat IEC compiler is not case sensitive.Names should contain the following letters, numbers, and special characters only:0...9, A...Z, a...z Underscore Designators always begin with a letter.The underscore is used to display prefixes more clearly. The syntax is explained in the respective prefix section. Because data type designators are usually formed from capital letters, the individual words are put together with an underscore as a separator to increase readability. The underscore should not be used otherwise.35 0Chapter: Appendix I Variable Naming Conventionc. Valid Charactersd. Prefix TypesPrefixes are used to quickly identify a designators function. The prefix types are as follows:Type designator type such as Boolean or integer Scope designator scope as either local or global Property designator property such as retained or VAR_IN_OUT POU POU type such as function or function blockThe general syntax for variables and constants is as follows:[Scope][Property] _ [Type][Name]g_diFirstUserFault xEnable c_iNumberOfAxes gc_sMyGlobalStringConstantThe general syntax for POUs is as follows: Chapter: Appendix I Variable Naming Convention[POU] _ [Name]FB_AxisController FB_HeatGun P_Main F_GetLeftString35 1e. Scope PrefixScope prefix indicates the scope of variables and constants. You can see if it is a local or a global variable or a constant from the scope prefix.Global variables are indicated by a lower case 'g'. A lower case 'c' is added to global constants.VAR_GLOBAL CONSTANT gc_diMaxFaults : DINT := 100; (* Maximum Quantity of Active Faults *)gc_diMaxEvents : DINT := 100; END_VAR(* Maximum Quantity of Events *)VAR_GLOBAL g_stMasterFaultList g_stMasterEventList g_xReset END_VAR : ST_FAULTLIST; : ST_EVENTLIST; : BOOL;Scope Prefix No prefix g_ gc_Type VAR VAR_GLOBAL VAR_GLOBAL CONSTANTUse Local variable Global variable Global constantExample xEnable g_xRunning gc_iCurrentRecipeTable 3.5 Scope Prefix35 2Chapter: Appendix I Variable Naming Conventionf. Type PrefixType prefixes identify the data type of variables and constants. The IEC 61131-3 standard data type prefixes are listed in the following table.Type Prefix x b w dw si i di usi ui udi r lr date tod dt t s p a eType BOOL BYTE WORD DWORD SINT INT DINT USINT UINT UDINT REAL LREAL DATE TOD DT TIME STRING POINTER ARRAY ENUMUse (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 TypeExample xName bName wName dwName siName iName diName usiName uiName udiName Chapter: Appendix I Variable Naming Convention rName lrName dateName todName dtName tName sName pxName adiName eMotorType35 3Type Prefix st fbType STRUCT FUNCTION BLOCKUse (Bytes) Structure Function BlockExample stRecipe fbTriggerTable 3.6 Standard Date Type PrefixesThe type prefix can also be composites, for example, for pointers and arrays. The pointer or array is listed first, followed by the prefix of the pointer type or array type as the following examples show:piCounter aiCounter paiRefCount astList : POINTER TO INT; : ARRAY [0..10] OF INT; : POINTER TO ARRAY [1..10] OF INT; : ARRAY[0..gc_diMaxFaults] OF ST_FAULT;35 4Chapter: Appendix I Variable Naming Conventiong. Property PrefixProperty 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 RETAINUse Local constant Remnant variable type retain Remnant variable type persistent Input variable of POU Output variable of POU In/out variable of POUExample c_xName r_xNamep_ i_ q_ iq_VAR PERSISTENT VAR_INPUT VAR_OUTPUT VAR_IN_OUT AT %IX AT %IBp_diName i_xEnable q_xError iq_stParametersati_ AT %IW AT %ID AT %QX AT %QB atq_ AT %QW AT %QD AT %MX AT %MB atm_ AT %MW AT %MDDirect access to input memoryati_bNameDirect access to output memoryatq_bNameDirect access to memory locationatm_bName35 5Chapter: Appendix I Variable Naming ConventionTable 3.7 Property PrefixNOTE: Do not declare constants as RETAIN or PERSISTENT.The name of the AT-declared variable also contains the type of the target variable. It is used like the type prefix:atm_rMyVar1 atm_rMyVar2AT %MW0 : REAL; AT %MW4 : REAL;35 6Chapter: Appendix I Variable Naming Conventionh. POU PrefixThe program organization units defined in IEC 61131-3 are:Function Function block Program ActionThe designator is composed of a POU prefix and as short a name as possible (e.g. FB_GetResult). Just like a variable, the first letter of each word in the POU name is capitalized. We recommend that you form a composite POU name from a verb and a noun. The prefix comes with an underscore before the name and identifies the type of POU on the basis of the following table:POU Prefix P_ FB_ F_ A_Type PROGRAM FUNCTION_BLOCK FUNCTION ACTIONUse Program Function block declaration Functions ActionExample P_RecipeManagement FB_AxisController F_GetLrealString A_GetCommand Chapter: Appendix I Variable Naming ConventionTable 3.8 POU Prefix35 7i. StructuresThe name of each structure data type consists of a prefix ST_ and a short, meaningful description in upper case (e.g. ST_STATION_NUMBER). If several words have been put together, they are separated by an underscore. Each component of the structure must be identified with a type prefix.TYPE ST_FEED_PARAMETERS : (* Parameters for MC_MoveVelocity FB *) STRUCT lrVel lrAcc lrDecel lrJerk eDirection lrStopPos END_STRUCT END_TYPE : LREAL := 100.0; : LREAL := 2000.0; : LREAL := 2000.0; : LREAL := 10000.0; : MC_Direction := MC_Positive_Direction; : LREAL := 0.0;Declaration example:stAxis1Feed: ST_FEED_PARAMETERS;35 8Chapter: Appendix I Variable Naming Conventionj. List TypesThe name of a list type consists of a prefix ET_ and a short, meaningful description in upper case (e.g. ET_WORKING_DAY). If several words have been put together, they are separated by an underscore. The individual elements of list types are identified with the prefix E_.TYPE ET_EVENT_TYPES : ( E_EVENT_NO_EVENT := 0, E_EVENT_FAULT_ACTIVE := 1, E_EVENT_FAULT_RESET := 2, E_EVENT_FAULT_ACK := 3, E_EVENT_USER_1 := 10 ); END_TYPE (* Fault Just Occurred *) (* Fault Is Gone and Acknowledged By AutoReset *) (* Fault Is Are Gone and Ack By Reset Input *) (* User Event *)Variables and constants declared as a list type are prefixed with a lower case: Chapter: Appendix I Variable Naming ConventioneMyEvent: ET_EVENT_TYPES;NOTE: 2 bytes of memory are reserved for each list variable.35 9k. LibrariesDesignators contained within a library and the library name itself is prefixed with a code to quickly identify the source and to match the designator with the library.MyLib_gc_diMaxConvCount MyLib_ConveyorControl.lib36 0Chapter: Appendix I Variable Naming Convention49. Good Programming Practices a. CommentsComments are essential for understanding source code; however, each individual line of code does not need to be commented. Limit your comments to the necessary minimum. It is more important to keep code clear and understandable. This minimizes the amount of comments required. If all POUs and variables have meaningful names, comments can be shorter. However, if the code is difficult to understand and there are no comments, even the programmer will have trouble understanding it after a short time. If variables have been given unusual values, for example, it is extremely important to explain the reason for this to prevent future misunderstandings. Write your comments so that they are not only notes for the programmer but can also be understood by third parties.b. Array IndexingArray should always be index starting at zero to prevent range errors. This typically occurs when the variable used to index an array is not initialized properly as shown below. iCurrentRecipe astRecipes : INT; : ARRAY[1..10] OF ST_RECIPE;The problem is corrected as follows: astRecipes : ARRAY[0..10] OF ST_RECIPE;The first element of the array, 0, is either not used or used as a default.c. Program CallsParenthesis should be used when calling programs and actions as shown below: P_SearchData();36 1Chapter:II.Appendix II Truth Tables and Boolean AlgebraBy using Boolean algebra we can see how the Truth Table can be converted into code. First look at the Truth Table for the 2 PE conveyor.In this table the only situation where the Motor Starter is true, is when the EntryPE is TRUE and the ExitPE is false. The Boolean equation for this would be as follows MotorStarter = EntryPE AND NOT ExitPE As another Example consider an XOR function. The Exclusive OR (XOR) function only provides a TRUE output if there are an odd number of TRUE inputs. The Truth Table is below: Appendix II Truth Tables and Boolean AlgebraTo find the Boolean equation for this table we look at the conditions that result in Z being TRUE. The first one is NOT A AND B, the second one is A AND NOT B. The other conditions result in Z being false, so we ignore them.Z = ( NOT A AND B) OR (A AND NOT B) To represent this as Boolean algebra the ^ will be used for the AND symbol, the v will be used for the OR symbol, and the will be used for the NOT symbol.36 2Chapter: II.We then OR these two conditions togetherZ = ( NOT A AND B) OR (A and NOT B) now becomes Z = (-A ^ B) v (A ^ -B) The Truth Table for the 3 PE conveyor is as follows:Notice that A,B,C, and Z labels were added above the PE names and the Motor Starter Appendix II Truth Tables and Boolean Algebra Looking at the first condition that sets the Motor Starter to TRUE we get the following -A ^ B ^ -C The second condition is: A ^ -B ^ -C The third condition is: A ^ B ^ -CIf we then OR these three conditions together we will have the Boolean Equation for our Truth Table Z = ( -A ^ B ^ -C ) v ( A ^ -B ^ -C ) v ( A ^ B ^ -C ) You could simply convert the letters and symbols back to their appropriate variable names and be done, however the purpose of this example is to be efficient, so we will reduce the equation as far as possible. Z = ( -A ^ B ^ -C ) v ( A ^ -B ^ -C ) v ( A ^ B ^ -C ) Z = -C ^ [( -A ^ B ) v ( A ^ B ) v ( A ^ -B )]36 3Chapter: II.Z = -C ^ {[ B ^ ( -A v A )] v ( A ^ -B )} Z = -C ^ [( B ^ 1 ) v ( A ^ -B )] Z = -C ^ [ B v ( A ^ -B )] Z = -C ^ [( B v A ) ^ ( B v -B )] Z = -C ^ [( B v A ) ^ 1 ] Z = -C ^ [( B v A )] Z = -C ^ ( B v A ) If we now convert this back we get the following MotorStarter := NOT ExitPE AND (MiddlePE OR EntryPE) The above is the simplest description possible for our Truth Table and matches what was done in the CASE statement.36 4Chapter: II.Appendix II Truth Tables and Boolean AlgebraX.Appendix III De-bouncing an InputThe below sample will monitor the value of the input and once the input has not changed for a given period of time then the output will follow the input. Imagine the input sample looks like the following 00000 11111 00000 11111 00000 11111 00000 11111 00000 11111 00000 This input has no issues; it is obvious when it is intended to be ON or OFF. Now imagine the input looks like this 01000 11011 00100 11011 00100 11111 00000 11111 00000 11111 00000 Without looking at every number, just sit back and look and the two groups, you can see the first half of the bottom one is not as clean as the top one. Here they are again next to each other 0000011111000001111100000111110000011111000001111100000 0100011011001001101100100111110000011111000001111100000 In a perfect world the top line would represent both the input and the output. However, many times the bottom line would represent the input and the desired output would be the top line. Chapter: Appendix III De-bouncing an Input To use the bottom line as the input to create the top line as an output we will need to monitor the input value and determine when to change the output value. This will cause a delay in the output changing states. Real Input Desired Output 01000 11011 00100 11011 00100 11111 00000 11111 00000 11111 00000 00000 11111 00000 11111 00000 11111 00000 11111 00000 11111 00000Notice there is only one sample within a group that is incorrect. The below code will filter out this incorrect value.36 5Lines 1-7 If the input is 0 and the integrator is greater than 0 then decrease the integrator by 1. Else if the integrator is less than samples then increase the integrator by 1. Lines 10-15 If the integrator is 0 then the output is 0. Else if the integrator is less than or equal to samples then the output will be equal to 1. Line 14 is to ensure that the integrator never increases to far. When the input changes the output will be delayed by the PLC scans, but this is the tradeoff that must be made for de-bouncing an input.36 6Chapter: Appendix III De-bouncing an InputThe integrator will count up or down as the value of the input changes. Once the integrator has reached a value equal to samples then the output will be changed.Real Input Normal Output01000 11011 00100 11011 00100 11111 00000 11111 00000 11111 00000 01000 11011 00100 11011 00100 11111 00000 11111 00000 11111 00000De-bounced Output 00000 00000 00000 00000 00000 00111 11000 00111 11000 00111 11000 First, notice that in the first half of the Real Input the value was never True 3 times in a row, therefore the De-Bounced output never changed to True. Also notice that when the Input was True three times in a row it was on this third check of the input that the output was set to True. The same is true for when the input changed from True to False. A few more examples Real Input Normal Output De-bounced Output 0000 0000 0000Real Input Normal Output De-bounced Output0010 0010 0000Real Input Normal Output De-bounced Output0111 0111 0001 Chapter: Appendix III De-bouncing an InputReal Input Normal Output De-bounced Output1111 1111 0011Real Input Normal Output De-bounced Output1110 1110 001136 7XI.Appendix IV Quick StartOverviewConnecting to and configuring your hardware network. Writing basic PLC program to turn on a digital output when an input goes to a value of 1.Click the TwinCAT icon in your system tray. Open TwinCAT System Manager.36 8Chapter: Appendix IV Quick StartPut TwinCAT in Config Mode by clicking blue TwinCAT icon on the toolbar in the System Manager.Click Ok.Look in the lower right corner of your System Manager and make sure you see the blue Config Mode symbol.Click File -> New36 9Chapter: Appendix IV Quick StartRight click IO devices and click Scan Devices.Check the box for the EtherCAT device and unselect all other boxes and click OK.Click Yes37 0Chapter: Appendix IV Quick StartClick YesThe tree will now give a representation of your hardware network.37 1Chapter: Appendix IV Quick StartClick the TwinCAT icon in your system tray. Open TwinCAT PLC Control.37 2Chapter: Appendix IV Quick StartType bOut := bIn; in the code editing window. Press Enter.Make sure all fields are filled out. Addressing the variable at %Q* allows us to later link the variable to a piece of hardware (Digital output terminal).bIn should be addressed at %I*. This will allow us to link to a digital input terminal.37 3Chapter: Appendix IV Quick StartNOTE: To manually bring up the Declare Variable dialog box, highlight the variable and press Shift + F2.Your PLC project should look like whats pictured below.37 4Chapter: Appendix IV Quick StartCompile Code.Make sure you have no errors.Save the ProjectDo ANOTHER Rebuild all.37 5Chapter: Appendix IV Quick StartNavigate to where you saved the PLC project. Confirm there is a file named the same as your PLC with a tpy file extension. NOTE: If you do not see the .tpy file go back to your PLC project and do another file Save and Project Rebuild All. If you get errors in your PLC then a .tpy will not be generated.Open the System Manager we previously configured. Right Click on PLC Configuration and click Append PLC Project. Then locate the .tpy file and open.37 6Chapter: Appendix IV Quick StartExpand your .tpy file and you will see the variables that you created in your PLC Project.Highlight bIn Variable, select Variable tab and click the Linked to button.Select the digital input terminal you want the variable connected to. Click OK.37 7Chapter: Appendix IV Quick StartHighlight bOut Variable, select Variable tab and click the Linked to button.Select the digital output terminal you want the variable connected to. Click OK.37 8Chapter: Appendix IV Quick StartNote: You can easily see where the variable is linked to by right clicking on the variable and selecting Goto Link Variable.It will bring you to the IO terminal that this variable is linked to.37 9Chapter: Appendix IV Quick StartNote: To determine if a variable is linked or not you can look at the icon next to the variable.Once your links are established you can now activate the configuration. In the SystemManager click the Activate configuration icon on the toolbar. Follow steps 1-3.38 0Chapter: Appendix IV Quick StartVerify that TwinCAT has gone into Run Mode by looking in the lower right corner of your System Manager.Go back to your saved TwinCAT PLC Control. Follow steps 1-3.38 1Chapter: Appendix IV Quick StartThe PLC project should now look like what is below. You are now online with the PLC and running.Apply 24 VDC to the input terminal you linked bIn to and the digital output will come on. In your PLC you should see the state of bIn and bOut change to true.38 2Chapter: Appendix IV Quick StartIndexAActions AMS Array 25, 94 17, 18, 161, 162, 340, 344 101, 102, 104, 276, 364, 371257, 258, 264, 267, 269, 273, 274, 277, 279, 282, 289, 290, 298, 333, 334, 339, 340, 341, 343 Priorities 32RRegistration Remote 20, 47, 55, 60, 61 18, 35, 55, 57, 344FFBD 9, 77, 79, 82, 153S IIL 9, 10, 77 Instruction List 370 SFC 9, 77, 80, 116 ST 9, 10, 77, 81, 116, 146, 171, 286, 330, 331, 362, 364, 367, 368, 371LLD 9, 77, 78TTwinCAT 1, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 21, 23, 26, 27, 28, 29, 35, 43, 44, 45, 46, 47, 54, 55, 56, 57, 58, 60, 61, 63, 67, 68, 75, 76, 82, 85, 86, 104, 107, 109, 112, 113, 115, 121, 151, 153, 154, 155, 158, 160, 161, 220, 225, 248, 256, 257, 263,265, 268, 269, 270, 277, 279, 295, 298, 301, 333, 338, 339, 340, 343, 344, 345, 350, 351, 353, 356PPLC 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 19, 21, 23, 26, 39, 40, 42, 54, 56, 63, 64, 65, 67, 70, 72, 74, 75, 76, 83, 86, 104, 105, 107, 108, 109, 112, 113, 121, 122, 126, 136, 138, 139, 148, 151, 183, 185, 186, 189, 190, 193, 201, 202, 203, 206, 207, 208, 213, 216, 217, 219, 220, 224, 226, 227, 228, 229, 231, 233, 238, 241, 242, 248, 255, 256,38 3Chapter: Appendix IV Quick Start
My mentor is asking me to start to learn the Beckhoff PLC so that I can hopefully control the speed and orientation of a simple brushed motor. Form what I get from your post you suggest that I download the TwinCat 2.x. I would do this but I have noticed that when I turn on my work computer a little startup window pops up with the TwinCat logo. Training Training Schedule. Training is held on the second full week of each month at the Beckhoff Technology Centre in Huntingdon, Cambridgeshire and the third week in Glasgow. These venues alternate between TwinCAT 2 and TwinCAT 3 training each month. The TwinCAT PLC training course runs over 2 days, with a 3.