You are on page 1of 383

Beckhoff New Automation Technology

TwinCAT 2

Revised: October 18, 2012 Brian McClure



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


Revision Notes V3.0.0 Added – Chapter Digital I/O This chapter covers the first section of “The Inspection Conveyor” utilizing Digital Inputs and Outputs to control the conveyor. Index Added Table of Contents and Page numbering modified



10 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 225





25. 26. 27. 28.


230 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 283





283 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 330



9 .

If this threshold is exceeded. independently of other processor tasks. etc. compatible PC hardware embedded IEC 61131-3 software PLC. can access TwinCAT data via Microsoft interfaces.II. NC axis control. NT/XP Embedded. TwinCAT indicates the system load for programs that are running.)     Architecture  TwinCAT consists of run-time systems that execute control programs in real-time and the development environments for programming. Any Windows programs. Overview The Windows Control and Automation Technology  The Beckhoff TwinCAT software system turns any compatible PC into a real-time controller with a multi-PLC system. a system message is generated. for instance. Windows 7. The real-time load on a PC is set with TwinCAT. programming environment and operating station. or can execute commands. OCX. TwinCAT replaces conventional PLC and NC/CNC controllers as well as operating devices with:   open. diagnostics and configuration. 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. TwinCAT Overview 1. 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. DLL. defined operating behavior is achieved in this way. software NC and software CNC in Windows NT/2000/XP/Vista. A practical oriented software solution  TwinCAT offers a precise time base in which programs are executed with the highest deterministic features. 10 Chapter: TwinCAT Overview . visualization programs or MS Office programs.

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

The fieldbus cards can be configured and diagnosed conveniently via the TwinCAT System Manager. It is possible to operate more than one fieldbus card per PC. Master and slave functionality is supported. on one PC. each running up to four user tasks. Chapter: TwinCAT Overview 12 . only TwinCAT run-time is available. The PLC program can be written in one or more of the languages provided for in the IEC 61131-3 standard:       IL (Instruction List). ander the CE operating system and the embedded operating systems for the series BX and BC controllers. TwinCAT PLC allows up to four virtual “PLC CPUs”. SFC (Sequential Function Chart) and ST (Structured Text). LD (Ladder Diagram). Programming can be done    locally. via TCP/IP or via the fieldbus (BXxxxx and BCxxxx). FBD/CFC (Function Block Diagram). Program modifications are implemented via network-capable powerful communication with the run-time system. TwinCAT PLC – the central pillar of automation software  Conceived as a pure software PLC. so that an additional programming device is not required. TwinCAT I/O includes the TwinCAT real-time system for operating the fieldbuses and a DLL interface to application programs. depending on the selected fieldbus card.PLC and Motion Control on the PC TwinCAT I/O – universal I/O interface for all common fieldbuses  Many PC fieldbus cards from various manufacturers are supported. TwinCAT PLC running under the Windows NT/2000/XP/Vista operating systems includes both the programming environment and the run-time system.

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

TwinCAT enables a PC to process the operating programs.           14 .Helpful practice tools  Extensive fault finding functions in TwinCAT PLC facilitate the solution of problems either on site or via remote maintenance. 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 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. It exchanges data cyclically with drives and measurement systems via the fieldbus. the TwinCAT ScopeView (a software oscilloscope) can be used to record one or several variables simultaneously. The division of the system load is supported by TwinCAT with appropriate functions. the position controller is calculated on the PC processor as standard. the PLC and the NC at the same time. In addition. 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. For this purpose.

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

enabling even the most difficult motion tasks to be solved. set value generation and position controller. The interpreter interprets the code described in DIN 66025. In a CNC channel. The system includes interpreter. can be loaded directly from the PLC program into the interpreter. as is the connection of the axes with the fieldbus. NC programs. PLC functionality is integrated. Comprehensive PLC libraries enable interaction between NC and PLC. Parts programming is carried out according to DIN 66025 using high-level language extensions. 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. up to 32 axes can be interpolated simultaneously. 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. for example.  16 Chapter: TwinCAT Overview .TwinCAT NC I – axis interpolation in three dimensions  TwinCAT NC I (interpolation) is the NC system for linear and circular interpolated path movements of axis groups each involving two or three drives.

2.  The TwinCAT System Service can be accessed through the TwinCAT icon in the windows system tray (Right-Click and Left-Click provides the same menu)  From this menu the other parts of the TwinCAT system can be accessed and the TwinCAT System Properties can be changed 17 Chapter: TwinCAT Overview . System Service  The TwinCAT System Service is represented by the TwinCAT icon in the Windows system tray.

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

19 . 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.  The upper half of the System Tab shows which TwinCAT servers are installed The lower half provides settings for how TwinCAT will act when windows boots up  Auto Boot:   Disable – The TwinCAT System Service will boot in Stop Mode Enable – The TwinCAT System Service will boot in Run Mode   This would be the preferred setting on a running machine Config Mode – The TwinCAT System Service will boot in Config Mode  ADS services are running. remote communication is possible Chapter: TwinCAT Overview  Auto Logon:  Enabling this option and providing a User Name and Password will allow for the Windows Logon screen to be bypassed. represents the external address and other values are used internally Chapter: TwinCAT Overview   20 .xxx.1 added to the end The first four octets of the address can be changed to any number between 0 and 255.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 . They do not have to match the IP address The last two octets should not be changed as .1. AMS Router – Automation Machine Specification  AMS Router – Automation Machine Specification   The AMS Router is the communication router for TwinCAT Every piece of information that travels from one piece of software to another must go through the AMS Router  AMS NetID xxx.1.

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

 PLC    Up to 4 PLC Run-Times can be configured The path of the Boot Project can be changed The selection to enable the Boot Project and Retain Data can be made 22 Chapter: TwinCAT Overview .

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

 The System Manager and PLC Control can be also be accessed through this menu or the Windows Start menu Additionally the local TwinCAT System can be placed into its different modes  Stop Mode   The system is not capable of communication and no services are running  Config Mode    The ADS Router is running and communication is possible Scanning of hardware is done is this mode only I/O values are updated at the hardware level  Run Mode (Requires License beyond 30 Trial)  All services are enabled and running if configured to do so (i. Boot Project) 24 Chapter: TwinCAT Overview .e.

Cam Tables. Interpolation Channels System Configuration – Properties of the Target System and Real-Time Usage 25 Chapter: TwinCAT Overview . 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).3.

 Additionally provides a way to open the CurrentConfig.Menus and Controls  File Menu – Allows for creating a new file or opening a saved file. by using ‘Open from Target’ also referred to as ‘The Red Folder’. 26 Chapter: TwinCAT Overview .tsm file from the Boot folder.

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

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

29 Chapter: TwinCAT Overview .General – The TwinCAT version is provided here in bold The ‘Choose Target…’ button can be used to access a remote TwinCAT system.

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

no task can be set to a faster interval than the base time. Real-Time Settings   Settings – Here the Base Time is set. The CPU limit of 80% means that TwinCAT will consume no more than 80% to run all of its tasks. 31 Chapter: TwinCAT Overview .

32 Chapter: TwinCAT Overview . both of these create latency problems. Online – The ‘Real Time Usage’ is graphed and the limit from the ‘Settings’ tab is indicated by the thick green line System Latency should be no more than 5 micro seconds   Note: Image taken from a laptop with power save features and CPU throttling enabled.

 Priorities – The list of tasks and their priorities can be seen here 33 Chapter: TwinCAT Overview .

 Additional Tasks    Task 1 (added by ‘Right-Clicking’ on ‘Additional Tasks’) These additional tasks are used by C++ code to talk to variables that are linked to hardware I/O They can also be used for simulation 34 Chapter: TwinCAT Overview .

When used for simulation the ‘Auto start’ must be checked 35 Chapter: TwinCAT Overview .

36 Chapter: TwinCAT Overview . Route Settings  Current Routes – The Remote Computers shown in this list are the same as in the ‘Properties’ of the TwinCAT icon.

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

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


Chapter: TwinCAT Overview

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


Chapter: TwinCAT Overview

 

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


Chapter: TwinCAT Overview

PLC Configuration

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


Chapter: TwinCAT Overview

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

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


Chapter: TwinCAT Overview

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


Chapter: TwinCAT Overview

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


Chapter: TwinCAT Overview

9 TwinCAT 2.10  TcMC2.6 Build 315 August 2. TwinCAT Versions There are several builds within each version New builds are released primarily to accommodate new hardware New versions are released when features are added A Brief History    TwinCAT 2.8      Change from wsm to tsm Use of XML for system configuration Config Mode for scanning hardware TwinCAT 2.lib   TwinCAT 2. 1999 TwinCAT 2.11 R2   Change in preparation for TwinCAT 3 Chapter: TwinCAT Software Installation Required for CX5000  TwinCAT 2.7 TwinCAT 2. TwinCAT Software Installation 5.11 Build 1552 TwinCAT 2.11 R3 44 .III.

10 to 2.11 TwinCAT Base System         Integration of MDP (Modular Device Profile – a generic interface for device information) Integration of configuration tool for AX5xxx drives Optimized behavior for use with Windows Vista and Windows 7 Optimization for TwinCAT running on Quad-core and Octo-core CPUs Time synchronization with EL6692 (EtherCAT bridge) Time synchronization with EL6688 (IEEE 1588/Precision Time Protocol) New modular structure of I/O drivers Base for new supplement products like TwinCAT Kinematic Transformation In addition to the features available in 2.11 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 R3):     CX50xx.11. the following new features were implemented in Release 2 (2.Release Notes: Changes from 2.11 R2. the following new features were implemented in Release 3 (2. additional interfaces like EtherCAT Slave EL7201 support (NC PTP) Supports new PCIe fieldbus adapters New Phasing functionality for NC PTP 45 Chapter: TwinCAT Software Installation . Select ‘Download’ from the top of the page 46 Chapter: TwinCAT Software Installation . Download & Installation   The TwinCAT software can be downloaded from www.6.

 Scroll down to the Software section and select TwinCAT 30 days version  Select TwinCAT 47 Chapter: TwinCAT Software Installation .

   The form must be filled in with a valid email address Below the form you can select the version and build of TwinCAT you would like to download After selecting the “Registration” button an email will be sent. to the address provided. containing a link to download the software 48 Chapter: TwinCAT Software Installation .

 Selecting the link in the email will start the download   Double-Click the exe file to start the installation process The file name will match the version number and build that you selected during the registration process 49 Chapter: TwinCAT Software Installation .

 If you receive the following warning select Run  Select your preferred language and then select next 50 Chapter: TwinCAT Software Installation .

 The InstallShield Wizard will begin the install process 51 Chapter: TwinCAT Software Installation .

 When prompted select next 52 Chapter: TwinCAT Software Installation .

 Accept the license agreement and select next 53 Chapter: TwinCAT Software Installation .

  Fill in the User Name and Company Name (This information will be viewable in the software) Use ‘DEMO’ for the serial number 54 Chapter: TwinCAT Software Installation .

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

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

 Select the additional features to install with TwinCAT  The desired features should be selected here. 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. afterwards select Next to continue  TwinCAT I/O – Allows the direct access to IO via a DLL. 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. has never been sold in North America.       57 .

 Specify the path for the TwinCAT installation  The default path is highly recommended. project files that the user creates can be stored in any desired location 58 Chapter: TwinCAT Software Installation .

 Specify the Program Folder for the TwinCAT installation  The default path is highly recommended. project files that the user creates can be stored in any desired location  The installer will now install the needed components Chapter: TwinCAT Software Installation 59 .

 You must reboot the PC after the installer has completed   After rebooting the PC you will see the TwinCAT icon in the Windows System Tray TwinCAT is in ‘Stop Mode’ by default 60 Chapter: TwinCAT Software Installation .

7. Licensing and Registration Single left click the TwinCAT Icon in the system tray. and select properties 61 Chapter: TwinCAT Software Installation .

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

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

and Functions Data Types – Here the programmer can create Structures and Enumerations to be used in the PLC code Visualizations – Interface screens for use by Maintenance personnel or Operators can be created.POUs – Program Organizational Units – This will contain the code written by the programmer. Function Blocks. Programs. 64 Chapter: PLC Overview .

and Task Configuration are all accessible from this tab. 65 Chapter: PLC Overview . The Global Variable Lists.Resources – The resources tab contains several items. Library Manager. A POU is opened by double-clicking on it. PLC Configuration.

the variables that are local to this POU are defined between the Keywords VAR and END_VAR. Additionally there is a Message Window at the bottom.The POU contains 2 parts. The first line of the declaration section defines the type of POU and the name of the POU. from the ‘Window’ menu select ‘Messages’ or the keyboard shortcut ‘Ctrl + ESC’ . the Declaration section. 66 Chapter: PLC Overview The Message Window can be hidden or shown. and compile information. this part of the window will contain the PLC code of the POU. The Message window will show Errors. and the Code section. Below the Declaration section is the Code section. Following this is the local variable declaration. Warnings.

a Standard Task is created that calls the Program MAIN. from MAIN all other POUs are called. Programs A program is a POU which returns several values during operation. and if thereby values of the program are changed. for example is the variable bStart is defined with an address as a local variable in MAIN. Programs can call all types of POUs. Because Programs are recognized globally. they can call Functions. whereas a variable defined globally will only show the name of the variable. then these changes are retained the next time the program is called. in the PLC-Configuration of the TwinCAT System Manager the variable will be MAIN. Function Blocks. Programs are recognized globally throughout the project. and other Programs.9. By default when a new Project is started. separated by a dot ‘. the local variables declared inside of them will referenced by first using the name of the program and then the name of the variable. 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. 67 Chapter: PLC Overview . even if the program has been called from within a different program.’. If a one program calls another program.bStart.

10. Data Types and Conversions Elementary data types form the foundation of the programmer’s tools to represent and use information. 68 Chapter: PLC Overview . The elementary data types within TwinCAT Plc Control are below.

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

As such. TIME for. The necessary data type is selected depending on scope of measurement. say. the maximum size is 255 bytes + one byte for a null terminating character.The STRING data type is utilized to define and use ASCII character strings. DATE_TIME for a time stamp vs. Declaration Example: VariableName : STRING { := ‘StringValue’ } . is assigned to this converted value. The Standard attempts to remove a major source of errors compared to conventional Ladder-Language PLC programming errors with a mandate of Strong Data Types. The conversion operation is defined as a function. For example. (* Declares STRING-type variable MyString with initialized value of “This is my string” *) MyString : STRING := ‘This is my string’ . A STRING always occupies a memory size equal to the string size plus one byte for a null termination character. For example. The general scheme is defined as DataType1_TO_DataType2 ( VariableToConvert ) Where DataType1 is the data type of the variable being converted and DataType2 is the desired data type. for example. TIME_OF_DAY. MyReturnedInt. DATE_TIME} data set supports duration measurement and/or time stamping. The {TIME. MyReturnedInt := WORD_TO_INT(MyWordVariable) . the duration of a timer. WORD_TO_INT(MyWordVariable) The variable. the code snippet converts MyWordVariable from WORD to INT (integer). Conversion Functions are integrated within Plc Control to provide explicit conversion from one elementary data type to another. 70 Chapter: PLC Overview . The Plc Program Compiler should be able to detect when a programmer. attempts to assign a WORD variable to another variable of type TIME. DATE. converted data type. The function returns the argument’s value as the desired. The default size for a STRING is 80 bytes + one byte for a null terminating character.

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

bStart : BOOL .The use of abbreviated data types in the name of the variable help in the understanding of what the variable is. Additionally using a Capital letter at the beginning of each word in the variable name will aid in understanding For example: bStartConveyor is much easier to read and understand than bstartconveyor Declaration        All variables must be defined between VAR and END_VAR Place the name of the variable to the left of the colon Place the data type to the right of the colon VariableName : VariableType . By placing a lower case b in front of all BOOLEAN variables the person reading the program will know that this variable is of type BOOL without having to refer to the variables declaration. (*bStart is of type BOOL*) iProductNumber : INT. (*iProduct Number is of type INT*) lrPressure : LREAL . (*lrPressure is of type LREAL*) Variable Scope    Global Variables can be read and written to from anywhere in the PLC program Local Variables can only be written to from within the POU where they are defined The local variable of any POU can be read by first accessing the POU instance that the variable is defined in and then using the ‘.’ to access the local variables defined within that POU Local variables cannot be written to from another POU  72 Chapter: PLC Overview .

3*)    It is also possible to assign an initial value to a variable in an instance of a function block  fbTON1 : TON := (PT := T#1s) . (*fbTON1 is of type TON and the PT input has an initial value of 1 second*) Constants    Variables defined as Constants cannot be written to by the PLC Constants are declared similar to initial values Use of the keyword ‘Constant’ at the beginning of the declaration section signals the compiler that the variable is a constant. 73 Chapter: PLC Overview .Initial Values   All Variables have the option of assigning an initial value This value will be written to memory when the PLC starts. (*iProduct Number is of type INT and has an initial value of 1*) lrPressure : LREAL := 2.3 . after which the code of the PLC will control the value bStart : BOOL := FALSE . (*lrPressure is of type LREAL and has an initial value of 2. (*bStart is of type BOOL and has an initial value of FALSE*) iProductNumber : INT := 1 .

To initialize the PERSISTENT variables choose Reset all. This file contains the old values of the persistent variables and is read on a TwinCAT start.Remnant Variables  Remnant variables can retain their value throughout the usual program run period. Therefore symbol generation must be selected.   Persistent Data  These variables are stored with the complete symbol. 74 Chapter: PLC Overview . With a “Reset all” RETAIN variables are initialized. These include Retain variables and Persistent variables. Persistent variables conserve their old values after a "Rebuild all" of the PLC program. On a TwinCAT shutdown the persistent variables are written in a special file. Retained Data  These variables maintain their value even after an uncontrolled shutdown of the controller as well as after a normal switching off and on of the controller or at the command 'Online'. 'Reset‘. Variables stored with RETAIN are initialized after a "Rebuild all" of the PLC program. the stored values will be processed further. Retain-Variables are reinitialized at a new download of the program unlike persistent variables. When the program is run again. A concrete example would be a piece-counter in a production line that recommences counting after a power failure.

For example the following will increase the variable Speed by a value of 5    75 Chapter: PLC Overview . The command is then followed by a variable or a literal value.12. TwinCAT provides these plus 1 extra       IL – Instruction List LD – Ladder Diagram FBD – Function Block Diagram SFC – Sequential Function Chart ST – Structured Text CFC – Continuous Function Chart (Non-IEC) IL – Instruction List  IL has a similar structure to assembly language and is comparable to the statement list language provided by Siemens. In IL only 1 command can be processed per line of code. Languages The IEC 61131-3 specifies 5 languages for writing PLC code.

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

FBD – Function Block Diagram   FBD is a graphical language that is similar to an electronic circuit diagram The below example has the same functionality as the above latching circuit 77 Chapter: PLC Overview .

is better thought of as a way to organize code and control the sequence of operation Each Step and Transition in SFC has code inside of it that can be written in any of the other languages including SFC  78 Chapter: PLC Overview .SFC – Sequential Function Chart  SFC. although defined as a language.

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

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

GT.     Declaration       The Declaration of a Function contains 4 parts The Name of the Function The Return type of the Function The Variables to be passed into the Function The local variables used by the Function The Name of the Function    Following the Beckhoff coding convention. Each function starts new each PLC scan. OR. the name of the Function starts with F_ The same IEC rules for naming of variables apply to the naming of Functions Following the Name of the Function is the Return Type  A Function can only Return one variable 81 Chapter: PLC Overview .13. but are only capable of calling other functions Note: Functions have no memory space and therefore they do not retain any values from one PLC scan to the next. SQRT. Functions  A Function is a re-useable piece of code that will process the defined inputs and return a single result AND. SIN. LE are all examples of Functions The programmer can also create their own Functions that normally involve more complicated tasks. COS. such as converting a temperature value from Celsius to Fahrenheit or scaling an analog input value from 0-32767 to 0-10 Functions can be called from any other POU type.

 The Variables to be passed into the Function  In the below example iTempInCelsius is the Variable that is being passed into the function 82 Chapter: PLC Overview .

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

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

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

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

Time On.  The Variables to be passed into the Function Block Below the Enable. and Time Off values are being passed into the Function Block 87 Chapter: PLC Overview .

  The Variables to be passed out of the Function Block Below the Output variable has been added 88 Chapter: PLC Overview .

    The Variables that are internal to the Function Block Below the two timers to be used have been instantiated fbTON is of type TON fbTOF is of type TOF 89 Chapter: PLC Overview .

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

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

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

The line of code that calls the instance name and uses the parentheses is the line of code that updates the values inside of the Function Block. It is coded differently but works exactly the same. followed by a call of the Function Block instance on line 6. In the above example of fbPulse2 the input variables are first assigned. 93 Chapter: PLC Overview . if line 6 was removed from the code then the Function Block would never run. This is extremely important to understand.Implementation      fbPulse1 is of type FB_Pulse fbPulse1 is an instance of FB_Pulse bSwitch is passed into the bEnable input of fbPulse1 tTimeOn and tTimeOff are assigned literal values in the proper TIME format bPulse is passed out of fbPulse1 into bLight1 fbPulse2 is a second instance of FB_Pulse.

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

Structures  Structures are used to define elements of a larger item and are commonly referred to as custom data types A temperature sensor. is more than just the temperature value The status of the Analog input card. for example. the scaling parameters. and the offset are all possible elements that are directly related to the temperature sensor In order to keep these elements together and make the code more re-useable a structure of these elements can be created    Declaration    The structure is created with its element names and data types Initial values can be given A structure can also contain other structures 95 Chapter: PLC Overview .16.

’ immediately after it and the intellisense window will appear. showing what elements exist inside of the structure  The elements in a structure can be written to and/or read from 96 Chapter: PLC Overview .Implementation   A structure must be instantiated just like a Function Block After typing the instance name of the structure place a ‘.

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

  

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

  


Chapter: PLC Overview

    

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

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

  


Chapter: PLC Overview

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


Chapter: PLC Overview

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

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

 

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

10 0

Chapter: PLC Overview

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

3 Dimensional Array

10 1

Chapter: PLC Overview

Initializing each index of an array

 

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

The above 2 examples can be mixed together

10 2

Chapter: PLC Overview

  

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

10 3

Chapter: PLC Overview

19. The Boot Project must be enabled and also created. Boot Project  The TwinCAT Boot Project is used on a production machine as the PLC code to be run when TwinCAT starts.  Enabling    Enabling the Boot Project is done through the TwinCAT System Service Right Click on the TwinCAT icon in the Windows system tray and select properties Click on the PLC tab and place a check mark in the Run-Time 10 4 Chapter: PLC Overview .

Creation  To create the Boot Project: login with the PLC and select ‘Create Boot Project’ from the ‘Online’ menu 10 5 Chapter: PLC Overview .

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

 To open the Source Code Download file. Select Open from the File Menu  On the Open file dialog select the ‘PLC’ button 10 7 Chapter: PLC Overview .  The Source Code file will be created in the C:\TwinCAT\Boot folder The name of the file will be TCPLC_S_x.wbp where x will be a number from 1 to 4 which represents the runtime number.

 Select the correct Target System Type  Select the Run-Time on the Target 10 8 Chapter: PLC Overview .

   The files will be copied in to your local Upload folder C:\TwinCAT\PLC\Upload If any of the files already exist you will be asked if you would to overwrite these files  The code will then open  If the source code download has not been performed you will get the following error message 10 9 Chapter: PLC Overview .

The machine will process product based on the conditions of the I/O with minimal operator intervention. For the purpose of this document I have chosen to use a state machine that best serves the purpose of learning to use the TwinCAT software. As the saying goes “Prior proper planning. The machine will have the following States: Undefined: When no State is defined by the PLC this will be the default State. Chapter: PLC Programming “The Inspection Conveyor” 11 0 . The first conveyor module will be for adding product to the system using only digital Input and Outputs. prevents poor performance”. Requires operator intervention for all functions of the machine.V. This State will be used when the machine is first powered on and when a problem in the PLC code occurs. or to shut down the machine after Automatic operation. Access to this mode will be restricted. The second module will use an analog input to measure the size of the product. Next an analog output will be added to control the conveyor speed using a Variable Frequency Drive (VFD). Machine Control with Top-Down Programming Intro This section is going to cover the design and programming of a modular conveyor. Machine Control/State Machine There are many ways to do overall machine control and to implement a state machine. With that in mind the first topic will cover the overall machine control and the use of a state machine for automatic or manual operation. With each module a new concept and/or topic will be introduced. Manual: Used to start up the machine and prepare for operation. both of which are outside the scope of this document. This state is not allowed to be set by the operator. Operations will be allowed in this mode that could be harmful to the equipment. The overall machine control will be handled in a CASE statement. PLC Programming “The Inspection Conveyor” 21. Automatic: Used for routine production. Maintenance: Used for making adjustments to the machine or for troubleshooting individual components.

For the programming of this system each conveyor module will be a Function Block. Additionally. if multiples of a module are needed they can be easily instantiated. including information about the previous and following module. Using a photo eye at each end of the conveyor will aid in this process. Creating the program Open the PLC Control by selecting the TwinCAT icon in the Windows System Tray and the select PLC Control 11 1 Chapter: PLC Programming “The Inspection Conveyor” . Module data Structure: contains information about the configuration of the module. therefore. standard data Structures for all conveyor modules will be used by each of the Function Blocks to aid in communication between modules. Machine data Structure: contains status information for the overall machine including the current State.Modular Conveyor System Each conveyor module will need to work as a standalone piece and also in conjunction with other modules in front of and/or after it.

then click on ‘OK’ Chapter: PLC Programming “The Inspection Conveyor” 11 2 . select ‘New’ For most of this project we will not be connecting to hardware. Therefore everything will run in simulation on the computer you are using. Note: The TwinCAT 2 Run-Time is only available on Windows 32-bit Operating Systems In the ‘Choose Target System Type’ window.From the ‘File’ menu. select ‘PC or CX (x86).

Additionally I would advise that the MAIN program never be done in SFC. if not impossible. Chapter: PLC Programming “The Inspection Conveyor” 11 3 . it is my recommendation that when starting a new project the MAIN program should always be done in ST.In the ‘New POU’ window the Type of POU should be a ‘Program’ The ‘Name of the new POU:’ should be ‘MAIN’ The ‘Language of the POU’ should be set to ‘ST’ for Structured Text Note: Even if you are an experienced programmer in one of the other languages. This will allow the programmer to easily call other programs and also easily comment out large parts of the program. doing so will make using the special SFC flags much more difficult.

You should now have the following Place a semicolon on Line 1 of MAIN. 11 4 Chapter: PLC Programming “The Inspection Conveyor” .

select ‘Rebuild All’ 11 5 Chapter: PLC Programming “The Inspection Conveyor” .From the ‘Project Menu’.

In the ‘Message Window’ at the bottom. The Warning is because we have not saved the file with a name. you should receive 0 Errors and 1 Warning. 11 6 Chapter: PLC Programming “The Inspection Conveyor” .

the PLC Control will also create other supporting files that will clutter your desktop quickly. I would recommend against saving it on the desktop. Chapter: PLC Programming “The Inspection Conveyor” 11 7 . I have created a folder called ‘TwinCAT 2 Manual Samples’ directly on the root of my C:\ drive. Give your project a name and press the ‘Save’ button.From the ‘File Menu’. select ‘Save As’ The file can be saved anywhere you would like. I would recommend that you use the same file name that I have used.

You will now see that the file name of the project is placed across the top of the PLC Control Before writing any real code we will first declare all known variables that will later be connected to hardware.Adding a version number to your project name is an easy way to have multiple versions of the program. so that you can go back to a previous version later on. Select the ‘Resources’ tab at the bottom of the left column 11 8 Chapter: PLC Programming “The Inspection Conveyor” .

select ‘Add Object’ 11 9 . Therefore. Chapter: PLC Programming “The Inspection Conveyor” The ‘Global_Variables’ list is included by default. on large machines it is good practice to create multiple lists to help organize the variables into smaller more manageable lists. The ‘Global_Variables’ and the ‘Variable_Configuration’ The ‘Variable_Configuration’ list is only used for the BC line of controllers. however. Right Click on the ‘Global Variables’ folder.Expand the ‘Global Variables’ folder by clicking on the + sign In the ‘Global Variables’ folder there are two lists by default. we are going to start by creating a couple of Global Variable Lists.

Chapter: PLC Programming “The Inspection Conveyor” 12 0 . the same as variable names. or the name has already been used the ‘OK’ button will be grayed out. If it does not. and then click on ‘OK’ Note: The name of this list must follow the IEC 61131-3 naming rules. Double-Click on ‘Global_Variables_IO’ This will open the Global Variable list.Change the name of the list by adding ‘_IO’ to the end of the name. Place the cursor at the end of line 1 and press the enter key a couple of times.

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

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

Next we will create an Enumeration that will be used to represent the possible States of the State Machine. Select the ‘Data Types’ tab at the bottom of the left column 12 3 Chapter: PLC Programming “The Inspection Conveyor” .

and click ‘OK’ You should now have the following Chapter: PLC Programming “The Inspection Conveyor” 12 4 .Right-Click on the ‘Data Types’ folder and select ‘Add Object’ Type in ‘E_MachineState’ as the ‘Name of the new data type’.

The variables of the Enumeration must be placed between ( and ) and each one separated by a comma ‘.Data Types always default to a ‘STRUCT’. 12 5 Chapter: PLC Programming “The Inspection Conveyor” . this can be changed to an Enumeration by simply removing ‘STRUCT’ and ‘END_STRUCT’ from lines 2 and 3 and replacing them with (). each value after that will be incremented by one. When creating an Enumeration the first Variable will receive a value of zero by default.’.

From the ‘File’ menu. select ‘Save’. To check the Enumeration and the Global Variables for any possible typing errors go to the ‘Project’ menu. Or simply press and hold the ‘Ctrl’ key and the press the ‘S’ key. and select ‘Rebuild All’ If you have any errors. they should be fixed before moving on. When preforming a ‘Rebuild All’ this generates 2 errors. The asterisk is there to indicate that changes have been made but not saved. which can be seen in the ‘Message Window’ 12 6 Chapter: PLC Programming “The Inspection Conveyor” .Now would be a good time to save the changes that have been made. As an example I have removed the semicolon from the end of one of the Global Variable declarations. Notice that the asterisk * and the end of the file name disappears.

Place your mouse at the top of the ‘Message Window’ Click and Drag the bar upwards to see more of the ‘Message Window’ It is best to start with the first error in the list. Repeatedly pressing ‘F4’ will go to the next error in the list. The easiest way to find the first error in the list is to press the ‘F4’ key. many times one problem will create others for the compiler. You could also scroll through the error list and Double-Click on the error. 12 7 Chapter: PLC Programming “The Inspection Conveyor” .

The warning simply states that the VAR_CONFIG file has not been created for these variables. To the compiler the problem occurred on line 9. and the line of code that has the problem will be highlighted. These 7 warnings are created by the use of %I* and %Q* variables. Chapter: PLC Programming “The Inspection Conveyor” After fixing any errors you may have had. you have zero errors. Generally speaking warnings can be ignored. Now would be a good time to ‘Save’ your project. the location of the error will be shown. Repeatedly pressing ‘F4’ will go to the next error in the list. Ignore them for now and continue on.When the error is selected. ‘F4’ will scroll through the warnings. The full error message states that the complier is ‘Expecting the end of line character or an assignment before seeing a new variable name. 12 8 . the appropriate way to fix the problem is to find the variable declared before line 9 and place the semicolon at the end of the line. Once. you will get 7 warnings. preform another ‘Rebuild All’ from the ‘Project’ menu.

Finally. Click on the POUs tab at the bottom of the left column. 12 9 Chapter: PLC Programming “The Inspection Conveyor” . it is time to write some code.

then press the F2 key which opens the Input assistant.Double-Click on the MAIN program. then place a colon after it. . This blue arrow simply indicates that changes have been made to this POU that have not been downloaded into the running PLC. Note: You may or may not have the small blue arrow next to the icon for MAIN. In the local declaration section of MAIN define a variable called eStep as of type E_MachineState 13 0 Chapter: PLC Programming “The Inspection Conveyor” The best way to do this is to first type in the new variable name eStep.

eStep will be used as the condition variable of the CASE statement that will control the State Machine. By declaring eStep to be of type E_MachineState the value of the variable eStep will be the text in the Enumeration. place a semicolon at the end of the line. 13 1 Chapter: PLC Programming “The Inspection Conveyor” . press ‘OK’ This will bring you back to the declaration section.Select ‘User defined Types’ from the left column and then E_MachineState.

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

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

The ‘Declare Variable’ window will open Place a zero in the ‘Initial Value’ box. The first thing we will setup is the control of the value of eStep. With the initial value of eStep being 0 the case statement will be in E_Undefined.Press and hold the ‘Shift’ key then press ‘F2’. We have a Selector Switch for Manual or Auto and a pushbutton for Maintenance. 13 4 Chapter: PLC Programming “The Inspection Conveyor” . Inside this step we will set eStep to go to E_Manual. and click ‘OK’ The declaration of eStep now has an initial value of 0.

The input is negated with the NOT command because the switch being in the ON position is for Auto.However. Remember to use ‘F2’ for the Input Assistant to select gati_xMan_Auto_ss from the Global Variables 13 5 Chapter: PLC Programming “The Inspection Conveyor” . we should also look at the condition of the Selector Switch.

We now are able to put the machine into Manual Operation. Chapter: PLC Programming “The Inspection Conveyor” It would also be a good time to check for errors. Go to the ‘Project’ Menu and select ‘Rebuild All’ You should get one error. Now would be a good time to ‘Save’ your project. 13 6 . From Manual. there needs to be a way to go into either Maintenance or Auto. Press ‘F4’ to go to the error.

When the complier sees two values for eStep with no code in between them it causes an error. but if you forget it won’t hurt anything. It should be removed later.Each value for the CASE statement must have some code in it. please address them before moving on. 13 7 Chapter: PLC Programming “The Inspection Conveyor” . The easy way to avoid this is to place a semicolon after the colon. You will also need to do this after E_Auto and ELSE If you have any other errors.

The selector switch will place the machine into the Manual state.As the programmer it is your duty to ensure that all possible conditions are accounted for. This is the same code that was used to go from E_Undefined to E_Manual. pressing the Maintenance push button will place the machine back into Manual. From the Maintenance mode. In the ELSE command eStep will be set to E_Undefined. Currently it is possible to get into the Auto state but it is not possible to get out of it. 13 8 Chapter: PLC Programming “The Inspection Conveyor” .

Later in the section on ‘Fault Handling’ we will add to the state machine for what needs to be done when a fault occurs.The entire body of MAIN. and save your project. we will create the code that is going to call the function blocks. Before creating the function blocks. now looks like the following Now would be a good time to check for errors using ‘Rebuild All’ from the ‘Project’ menu. At this point the control for the state machine is finished. Therefore the machine state will be passed into the function block. The plan is to have a function block for each conveyor module. 13 9 Chapter: PLC Programming “The Inspection Conveyor” . Each function block will be capable of controlling the conveyor module in each possible machine state.

In the ‘POU’ column right click and select ‘Add Object’. Then click on ‘OK’ 14 0 Chapter: PLC Programming “The Inspection Conveyor” . Leave the Type as a Program and set the Language to ‘ST’ for Structured Text. Name the POU ‘P_MachineControl’.

Below the code for the CASE statement. In the ‘Input Assistant’ select ‘User defined Programs’ from the column on the left. 14 1 Chapter: PLC Programming “The Inspection Conveyor” . Double-click on ‘MAIN’ to open it. The open and close parenthesis are not required but should be used to indicate that it is a POU call. This will call the new program every PLC scan.Before writing any code in the new program we should call the program from ‘MAIN’. then press ‘OK’. place the cursor and press ‘F2’. select ‘P_MachineControl’ from the window on the right.

For now add a semicolon to prevent any build errors.Now double-click on ‘P_MachineControl’ in the ‘POU’ column. to monitor things going on in the background. Later we will add code to this program for calling the Function Blocks that will control the machine. add another program by right-clicking in the POU column and selecting ‘Add Object’ Name the new Program ‘P_MachineMonitoring’ In the Machine Monitoring program we will add some function blocks from a couple of libraries. 14 2 Chapter: PLC Programming “The Inspection Conveyor” . Next.

Lib is always included in every project by default. From the ‘Window’ menu. select ‘Library Manager’. The Standard library contains timers. triggers. The STANDARD. counters.First we will add the new library. and other basic function blocks. 14 3 Chapter: PLC Programming “The Inspection Conveyor” .

Under the ‘STANDARD. The ‘Open’ dialog box will open to the default location of C:\TwinCAT\PLC\Lib In this folder are all of the libraries that are included with the level of TwinCAT that you installed.Lib’ right click and select ‘Additional Library’. 14 4 Chapter: PLC Programming “The Inspection Conveyor” .

if you choose to type in the name. you will notice that windows filters the results of possible options as you type.lib’ press the ‘Open’ button.lib’ by either scrolling to the right or typing the name into the ‘File name:’ box. therefore these libraries are included as well. TcUtilities requires the use of TcBase and TcSystem.Add the ‘TcUtilities. After selecting ‘TcUtilities. 14 5 Chapter: PLC Programming “The Inspection Conveyor” .

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

.In the POU column double click on ‘P_MachineMonitoring’. Now place the cursor on line 0001 in the code window and press ‘F2’ to open the ‘Input Assistant’ 14 7 Chapter: PLC Programming “The Inspection Conveyor” The Tc_CpuUsage Function Block will monitor the percentage of the CPU that TwinCAT is using.

Scroll down to ‘TwinCAT System’ and expand that folder Chapter: PLC Programming “The Inspection Conveyor” 14 8 .From the ‘Input Assistant’ select ‘Standard Function Blocks’ from the left column and then expand TcUtilities in the window on the right.

Select ‘Tc_CpuUsage’ and click ‘OK’. This will add a generic version of the Function Block to the code. Chapter: PLC Programming “The Inspection Conveyor” 14 9 .

When using large function blocks in Structured Text the variables are each placed on their own line to make them easier to view. Each use of a Function Block will receive its own memory space. The ‘Class’ drop down list will allow for the selection of where the variable is to be declared. each Function Block must be given a unique instance name. the output assignment => is used to indicate that the variable is of type VAR_OUTPUT. Each variable is followed by either an input or output symbol and then a comma. leave this on VAR to declare it in the local variable declaration section. therefore. 15 0 Chapter: PLC Programming “The Inspection Conveyor” .The name on line 1 is the ‘Implementation’ name of the Function Block’. The assignment statement := is used to indicate that the variable is of type VAR_INPUT. everything between the open and close parenthesis are variables that are defined inside of the Function Block. Add ‘fb’ to the beginning of the implementation name TC_CpuUsage. When you click on any line other than line 1 the ‘Declare Variable’ window will appear.

this can be done by either typing in the type or pressing the ‘Ellipse’ button. finally select TC_CpuUsage and click ‘OK’. then ‘TwinCAT System’. then expand ‘TcUtilites’. When you press the ‘Ellipse’ button the ‘Input Assistant’ will open and allow you to select the type from the list. Select ‘Standard Function Blocks’ from the column on the left.Change the ‘Type’ from BOOL to TC_CpuUsage. 15 1 Chapter: PLC Programming “The Inspection Conveyor” .

Next the variables to be passed into the Function Block need to be added. and notice that the instance of the Function Block has been declared in the local variable section. which is of type string with a length of 23 bytes. The ‘NETID’ is the AMSNETID of the TwinCAT Run-Time that is to be read.The ‘Declare Variable” window should look like the following. Press ‘OK’. According to the Documentation the variable type is ‘T_AmsNetID’. 15 2 Chapter: PLC Programming “The Inspection Conveyor” .

therefore the local AmsNetID can be provided. the select ‘Properties’. Select the ‘AMS Router’ tab The AMS Net ID can be copied from here. 15 3 Chapter: PLC Programming “The Inspection Conveyor” . Click on your TwinCAT Icon in the windows system tray.In this example we are going to read the local CPU Usage.

then paste the AMS Net ID in between the quotes. For now add the variable ‘xReadCpuUsage’ to the ‘START’ input. When the ‘START’ input variable rises from False to True. Each rising edge that is seen on the ‘START’ input will cause another read of the CPU usage.In the code place an empty string after the assignment statement of NETID. internally the Function Block will execute an ADSREAD one time. 15 4 Chapter: PLC Programming “The Inspection Conveyor” . internally the Function Block will read the local AMS Net ID in this case. When using the local AMS Net ID it is also possible to just use an empty string ‘’.

If the input is left empty the default time of 5 seconds will be used. We will now create local variables that the Function Block will write to. before throwing a TimeOut error. Place a time value of 500 milliseconds in the ‘TMOUT’ variable. 15 5 Chapter: PLC Programming “The Inspection Conveyor” . Time values always start with T# and must end with time unit being used. The ‘TMOUT’ variable is the amount of time to wait for a response. Leave it defined as a Local variable and a BOOL.When you click away from line 3 the ‘Declare Variable’ window will appear.

Use the following variable names for the outputs and declare them as shown below. This Function Block will read the Windows Clock each time the ‘START’ input is triggered. save your project. Chapter: PLC Programming “The Inspection Conveyor” A commonly used Function Block is NT_GetTime. 15 6 . Now would be a good time to compile the code and check for errors. When there are no errors. The time value can then be added to log information. by selecting ‘Rebuild all’ from the ‘Project’ menu.

Select ‘Standard Function Blocks’ from the left column. 15 7 Chapter: PLC Programming “The Inspection Conveyor” . W2K. CE Operating System’ folder. expand the ‘NT.Place the cursor on line 11 and press ‘F2’. XP. XPe.

15 8 Chapter: PLC Programming “The Inspection Conveyor” .Select the NT_GetTime Function Block and press ‘OK’ The generic Function Block has now been added to the code.

Click away from line 11 and declare the Function Block as a type NT_GetTime. Set the NETID to local by using an empty string. with no space between them.Change the name to fbNT_GetTime. 15 9 Chapter: PLC Programming “The Inspection Conveyor” . (Two single quotes.

The local declaration section should have the following Notice that ‘stGetTimeValue’ is of Type ‘TIMESTRUCT’. Set the ‘TMOUT’ to 500ms. and contains the following information. This structure is defined inside of the TcUtilities library. Set the output variables and declare them as they are below. 16 0 Chapter: PLC Programming “The Inspection Conveyor” .Set the ‘START’ variable to xGetTimeStart and declare it as ‘Type’ BOOL.

wDay : Specifies the day of the month: 1 ~ 31. . In order to get regular updates of the CPU Usage the ‘START’ input of the TC_CpuUsage Function Block needs to toggle between TRUE and FALSE repeatedly. wDayOfWeek : Specifies the day of the week: 0 ~ 6 (Sunday = 0.wYear : Specifies the year: 1970 ~ 2106. February = 2 and so on). wHour : Specifies the hour: 0 ~ 23. wSecond : Specifies the second: 0 ~ 59. Monday = 1 and so on ). From the POU column right-click and select ‘Add Object’ 16 1 Chapter: PLC Programming “The Inspection Conveyor” The previous two Function Blocks were provided by Beckhoff. It is also possible to create your own. wMilliseconds : Specifies the millisecond: 0 ~ 999. To do this we will create a Function Block that pulses its output at a regular interval. wMinute : Specifies the minute: 0 ~ 59. The out ‘stGetTimeValue’ will hold values similar to the following. wMonth : Specifies the month: 1 ~ 12 (January = 1.

The Type of POU should be ‘Function Block’. The VAR section will declare values that are only used internally within the Function Block. At the top of the declaration section you will see on line 1 that this is a Function Block not a Program or Function. the name of the Function Block is also included on this line.In the ‘New POU’ window. In the VAR_INPUT section variables will be declared that have values passed into them from the calling code. Following line 1 is the VAR_INPUT. VAR_OUTPUT. name the POU ‘FB_Pulse’. the VAR_OUPUT section will declare variables that have their values passed out to the calling code. Chapter: PLC Programming “The Inspection Conveyor” 16 2 . and VAR sections. The language will be ‘ST’ for structured text. Click ‘OK’ to create the Function Block.

(*When TRUE the Function Block is Running. They are in the STANDARD library. i_tTimeOff : TIME.In the VAR_INPUT section declare the following variables i_xEnable :BOOL. 16 3 Chapter: PLC Programming “The Inspection Conveyor” . In the VAR_OUTPUT section declare the following variable q_xPulse : BOOL. In the VAR section declare the following variables These are the two timers that will be used to control the output. When FALSE the Function Block is stopped all values a reset and the outputs are FALSE*) (*Length of TIME for the Output to be TRUE*) (*Length of TIME for the Output to be FALSE*) i_tTimeOn : TIME.

window use ‘F2’ to place the two timers in the Function Block.In the code. 16 4 Chapter: PLC Programming “The Inspection Conveyor” .

The i_xEnable variable can be added by placing the cursor between the := and the . 16 5 Chapter: PLC Programming “The Inspection Conveyor” Now change the name of the TON and TOF to match the declaration section. .The TON will start when the i_xEnable input is TRUE and the TOF output is FALSE.

and Purple icons are for VAR. notice that once you have added the dot ( . Next. Red icons indicate VAR_OUTPUT. add the code to monitor the output of fbTOF If you type in the code. 16 6 Chapter: PLC Programming “The Inspection Conveyor” .Then press ‘F2’. ) after fbTOF a drop list will appear that contains all of the variables declared inside of the TOF. Yellow icons are for VAR_INPUT. in the left column of the Input Assistant select ‘Local Variables’. then select i_xEnable from the right window.

press the ‘i’ key. 16 7 . If you know the beginning of the variable name this can be an easy way to access it and still guarantee that typos are not made. add the TIME variable to PT:= Note: this is the tTimeOff variable Again. ) key This list includes every variable in the project. If you use the arrow keys. The input for fbTOF will be the output of fbTON This time to add the i_tTimeOn variable do not use the ‘F2’ key. You code should now look like the following Next. use ‘F2’ and select the variable from the ‘Local Variable’ list. including libraries.When the drop down list appears you can either continue typing to filter the list or use the arrow keys to move the cursor up and down. instead place the cursor after the := and before thecomma ( . ) Chapter: PLC Programming “The Inspection Conveyor” Now press the dot ( . After pressing the . both the ENTER key and the space bar will select the variable and add it to the code.

the . With i_tTimeOn highlighted. that the comment from the declaration section appears as a tool tip. is not removed as it was on the input variable. Next add the output q_xPulse to the Q output of the fbTOF If you use the .Pressing the down arrow will show the next variable in the list. must be removed or the compiler will throw an error. and select the variable from the list. which is the one we want to use. press the ‘Enter’ key. 16 8 Chapter: PLC Programming “The Inspection Conveyor” . Also notice that if you hover the mouse over the variable name in the list. when selecting an output the .

this allows the person viewing the code to easily see the beginning of each Function Block. The easiest way to do this. fbTOF. the left side shows the code as it appears offline. the right side show each variable and its value. The common practice is to place the instance name of the Function Block and the open parentheses on the first line. The width of the displayed variables in the right window can be adjusted by single clicking on the variable and then grabbing the right edge of the box click and drag to adjust the size. Using the above as an example i_xEnable. 16 9 Chapter: PLC Programming “The Inspection Conveyor” .Note: The following code would provide the exact same result Now would be a good time to compile the code by selecting ‘Rebuild all’ from the ‘Project’ Menu and then save the file.Q. then on each following line place one variable leaving the comma at the end of the line. resulting in the following Using the ‘TAB’ key to indent the lines of code that are part of the Function Block helps in reading the code. and i_tTimeOff will all be listed on the same line In order to make the code easier to read it is possible to place each variable on its own line. is place the cursor after each comma and press the ‘Enter’ key. When viewing code online that was written in Structured Text the code window is split.

17 0 Chapter: PLC Programming “The Inspection Conveyor” . then set the ‘Distance of two variables value.It is also possible to select ‘Monitoring Options’ from the ‘Extras’ menu.

We will now add the new Function Block to the Machine Monitoring code and use the pulsing output to trigger the TC_CpuUsage Function Block. 17 1 Chapter: PLC Programming “The Inspection Conveyor” . From the ‘Input Assistant’ select ‘User defined Function Blocks’ from the left column and the ‘FB_Pulse’ from the window on the right. or triggering a function block to start repeatedly. flashing stack lights or other indicator lights. In the POU column double-click on P_MachineMonitoring.A pulsing output can be used for many different things. Place the cursor on line 20 and press ‘F2’. Then press ‘OK’ This will add the generic code for the Function Block to the program.

Replace the name FB_Pulse with a specific instance name of fbPulseCpuUsage. After clicking away from line 20 the ‘Declare Variable’ Window will appear. Add the following values to the inputs of the Function Block. Change the ‘Type’ to FB_Pulse by either typing it in or using the ‘Ellipse’ button and selecting it from the list of ‘User defined Function Blocks’. 17 2 Chapter: PLC Programming “The Inspection Conveyor” . Click ‘OK’ The declaration section should now contain the following Before assigning variable name to the inputs and outputs format the code for easier reading.

there is also Database and XML supplements for working with those file types. By writing to xReadCpuUsage the fbTC_CpuUsage ‘START’ input will toggle and read the CPU Usage every other second. Beckhoff also provides the possibility to write logging information to the Windows Application Log. Now when the code is running the output will toggle on and off at a rate of 1 second. Using the ADSLOGSTR Function it is possible to write custom string values from the PLC into the Windows Application Log. There is a File Read and Write Function Block in the TcSystem library for interacting with a text file. Start by adding a new Function and name it FB_LogStateMachine 17 3 Chapter: PLC Programming “The Inspection Conveyor” . We will be creating a Function Block to monitor the variable eStep which holds the current value of the State Machine. When the value changes the code needs to create the message to be logged. and then log that message.For the output use the variable that was used on the TC_CpuUsage ‘START’ input. For this example we will create a log message every time the Machine State changes based on the value of E_MachineState. Creating logging information can be done in several ways.

the R_TRIG Function Block monitors its CLK input and when it changes from FALSE to TRUE the Q output will be on for one PLC scan sStateLog will be the STRING representation of the State Machine 17 4 Chapter: PLC Programming “The Inspection Conveyor” .Declare the following in the local variable declaration section i_eState will be the current value of the State Machine control by the ‘MAIN’ POU q_udiErrID will be the output result of the ADSLOGSTR Function ePreviousState will be updated at the end of the code and hold the value of i_eState from the previous PLC scan fbRT_StateChange is a Rising Trigger.

Note: The Function on Line 8 (F_StateMachineLookup) does not yet exist. The ‘IF’ statement on line 1 uses the not equal to <> operator to compare the previous state to the current state If they are not equal then the CLK input of the Rising Trigger is set to true (Line 2). code must be added to set that variable to FALSE. Line 8 passes the value of i_eState into the F_StateMachineLookup Function. When the ‘Declare Variable’ window appears press the ‘Cancel’ button. Note: Any time a variable is set to TRUE inside an ‘IF’ statement. else it is set to false (Line 4). When using a Rising Trigger Function Block the input must see the transition from FALSE to TRUE.Add the below code to the Function Block. if lines 3 and 4 were not included the Function Block would only work once. This code could also be done by using the following instead of lines 1 through 5 The ‘IF’ statement on line 7 monitors the Q output of the Rising Trigger when the output is TRUE lines 8 through 14 will be executed when the Q output is false line 16 will be executed. Lines 10 calls the ADSLOGSTR Function in the TcSystem library. 17 5 Chapter: PLC Programming “The Inspection Conveyor” .

17 6 . DIVIDE. each of these are a function and return a single result. for example adding two numbers together would be done in the following manner The + sign represents the ADD Function Functions that are not common Math Functions are called in a different manner. The variable ‘a’ is assigned a value of Chapter: PLC Programming “The Inspection Conveyor” Call the ADD function and pass in the value of the variables b and c The single result of the ADD Function will be stored in the variable a The ADSLOGSTR Function returns a UDINT (Unsigned Double Integer) ADSLOGSTR has three inputs msgCtrlMask : DWORD. The most basic Functions are the Math Operators: ADD. MULTIPLY. A Function does not have an instance name and does not have its own space in memory. strArg : T_MaxString. For Example a Timer or Counter must be a Function Block and not a Function.Calling a Function is different from calling a Function Block. The following line of code does not compile however for the sake of explanation let us assume that it would. msgFmtStr : T_MaxString. SUBTRACT. Functions do not retain any values from one PLC scan to the next. When calling a function the result of that function must be stored into another variable. Additionally Functions only return a single result. A Function Block requires an instance name and is assigned its own memory space. etc.

and ERROR are the type of Message LOG will write the message to the Windows Application Log MSGBOX will display a pop up box that shows the message msgFmtStr is a string that contains the text of the message and ends with %s Chapter: PLC Programming “The Inspection Conveyor” Note: the text in the sample code and the %s are inside of single quotes strArg is also a string. the value that is passed into the Function will replace the %s in msgFmtStr The code sets the Control Mask to Hint and Log 17 7 . WARN .msgCtrlMask is used to define the parameters of the logged event HINT .

17 8 Chapter: PLC Programming “The Inspection Conveyor” . Line 19 copies the value of i_eState into ePreviousState so that on the next PLC scan the two values can be compared and a change can be detected. otherwise it will create a log message every PLC scan.The message in the log will be a value of Auto Machine State Changed to: Auto if sStateLog has Note: The ADSLOGSTR should always be called conditionally using a Rising Trigger Function Block. these values are ADS Return Codes. any value other than 0 is an error. q_udiErrID will hold the value of the result of the ADSLOGSTR Function.

Let’s now add the code for F_StateMachineLookup. To prevent this and check the code place comment markers around the code on Line 8 Now.Now would be a good time to ‘Rebuild’ the code and save the file. The Purpose of this Function will be to pass in the current value of the machine state and then convert that to a string value. However the call to F_StateMachineLookup is going to throw an error. Right-Click in the POU column and select ‘Add Object’ 17 9 Chapter: PLC Programming “The Inspection Conveyor” . ‘Rebuild all’ and save the project.

The Name of the Function is the output variable. .Define the Function as below. 18 0 Chapter: PLC Programming “The Inspection Conveyor” Note: Because Functions only have one output there is no VAR_OUTPUT section. and its type is defined on line 1 of the declaration section. it can be changed on line 1. In the declaration section add the Input Variable The Input Variable eState holds the STRING representation of the Enumeration. This Function will convert this value to an actual STRING that can be passed into the ADSLOGSTR Function. the most common way would be to create nested IF statements as below. If you forget to change the type in the ‘New POU’ window. There are several ways to do this.

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

and a CASE statement takes one PLC scan to change to the next step. In the below code eState is passed into the Function eState is then evaluated by the CASE statement to determine which part of the CASE statement to run Chapter: PLC Programming “The Inspection Conveyor” 18 2 . However if the variable to be evaluated is the variable that is passed into the Function as a VAR_INPUT then the one step that is equal to the value of the variable that was passed in. that one step will run. Remember that a Function does not hold any data from one PLC scan to the next. The traditional use of a case statement would not work correctly inside of a function. Even in this very simple example it would be on the 4th PLC scan that iStep would have a value of 3.The use of a CASE statement will allow for only the minimum amount of code to be run. This code would never work inside of a Function.

the amount of code to be processed is less than the above example of IF and ELSIF statements. therefore the amount of CPU usage is reduced. 18 3 Chapter: PLC Programming “The Inspection Conveyor” . Place the code for the CASE statement into the body of the Function Now would be a good time to ‘Rebuild all’ and ‘Save’ your project.When the Function is called and eState has a value of 2 Line 1 will evaluate the value of eState and determine that it is 2 The code will then go to line 7 where it finds 2: and then run the code until it finds the next number that is followed by a : and then jump the END_CASE on line 12. By using a CASE statement in this way.

After the ‘Rebuild all’ F_StateMachineLookup should now be in black Chapter: PLC Programming “The Inspection Conveyor” 18 4 . The comment markers need to be removed from the FB_LogStateMachine. This is because the Function is not being used.You might notice that F_StateMachineLookup is grayed out in the POU column. Do another ‘Rebuild all’ and then ‘Save’.

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

We will start by adding a call to the P_MachineControl program from MAIN. The cursor is now on line 35 Press the ‘F2’ key to open the ‘Input Assistant’ In the left column select ‘User Defined Programs’. Chapter: PLC Programming “The Inspection Conveyor” 18 6 . We will be adding code to the program that allows the conveyor to be loaded and material to enter the system. Left click at the end of line 33 in MAIN. and then we will convert this PROGRAM to a FUNCTION BLOCK so that we can create multiple instances of it. select ‘P_MachineControl’. in the window on the right.22. This will place the cursor on that line. Then press the ‘Enter’ key twice. The first conveyor will be manually loaded by an operator and then index the box along the conveyor. We will start by creating a PROGRAM to control a single conveyor. Then press ‘OK’. Digital I/O The purpose of this section is to introduce the first mechanical part of the Inspection Conveyor.

For now let us create the ‘Infeed Conveyor’.‘P_MachineControl’ will now be called and scanned after ‘P_MachineMonitoring’. Eventually there will be several specialized conveyors in our conveyor system. . 18 7 Chapter: PLC Programming “The Inspection Conveyor” From ‘P_MachineControl’ we will be adding code to call the control program of the conveyor. Double-click on P_MachineControl in the POUs column. Right-Click in the POUs column and select ‘Add Object’.

By placing (* at the beginning and *) at the end. 18 8 Chapter: PLC Programming “The Inspection Conveyor” . Double-Click on P_MachineControl and use the ‘F2’ key to call the ‘P_InFeedConveyor’ program from ‘P_MachineControl’. In keeping with ‘Top-Down’ programming principles we will add some ‘code’ that is more descriptive than functional.Create a ‘Program’ and ‘Name’ the ‘POU’ ‘P_InFeedConveyor’. all text in between is ignored by the compiler. To prevent the ‘Declare Variable’ window from popping up we will create all of this as comments The first comment will be a general overview of what the code in this POU does.

therefore.The next thing to do is add comments for what we expect to need the program to do. 18 9 . we could set up a selection statement and write code for what to do when in each mode or each command (output) could monitor each mode and decide what to do. Manual. These are not in any specific order and more might be added later. and Maintenance. As a simple example let us consider the following: When in Auto a light should flash at 1Hz. when in Manual the same light should flash at 2Hz. Chapter: PLC Programming “The Inspection Conveyor” It is best to only write to an output in one location. the Function Block fbPulseAuto always has control of the output. If you attempt to control an output from more than one location then the last one to write to the outputs will determine its final state. We could try the following: Note: (eMode = E_Manual) in the code will compare the two values and return either a TRUE or FALSE value. both of these Function Blocks are writing to the same output (bLight) every PLC Scan. This program will control this conveyor in all modes of operation. However. There are several ways to do this. Auto. but this gives us a place to start.

the code just stops calling the Function Block. When eMode changes back to E_Manual the elapsed time (ET) will jump. For a light this probably will not cause a problem. Therefore. The value of all of the variables have been ‘frozen’. 19 0 . however. therefore. however. The light has changed from a 1Hz pulse to a 2Hz pulse. after a period of time eMode changes to E_Auto. only one of them will be attempting to control the value of bLight. however. However in the code shown there is nothing to reset the fbPulseManual Function Block. Because we are writing to the same output from two different Function Blocks when the transition happens the value of the output might not be what we expect. either the TON or t he TOF was in the process of timing. they record the start time and compare that to the current time to calculate the elapsed time. if the output is something more critical it could be a serious issue.The following ‘IF’ statement could be used to properly select which Function Block to call Only one of the two Function Blocks will be called at a time. it is not possible to ‘Pause’ a timer. With only two possibilities (Auto or Manual) an ‘IF’ statement works well. Internally the TON and TOF Function Blocks do not need to increment each PLC scan. Chapter: PLC Programming “The Inspection Conveyor” Let us assume the current value of eMode is E_Manual. The following provides the same functionality as above: Both of these examples have an inherent issue. a ‘CASE’ statement is more efficient.

The difference between them is how the output reacts on the PLC scan where the value of eMode changes. With the exception of the first example. 19 1 Chapter: PLC Programming “The Inspection Conveyor” .In order to remove this problem we can use one Function Block to write to the output. The time value will be loaded into the TON and TOF inside of fbPulseLight on the same PLC scan. If eMode has a value of E_Auto and the active timer has an ET of greater than 500ms then when eMode changes to E_Manual that timer will instantly be done and the Q output of the timer will be TRUE. but adjust the time value based on eMode: In the above example the value of tTime will change based on the value of eMode. it is ultimately up to the programmer to choose the implementation that best fits the specific implementation. all of these samples do the same thing. In the below example the Pulse Function Block is called and the Enable input is set to FALSE when the value of eMode Changes In this scenario both the TON and TOF will be restarted when the value of eMode changes.

When writing a PLC program the above situation can cause many problems for new programmers. but instead being used as an input to a Rising Edge or Falling Edge trigger. The small changes that can happen in one PLC scan can create unexpected results that are difficult to detect and troubleshoot. the Entry PE is blocked which causes the Motor Starter to energize and the conveyor moves forward. the R_Trig and F_Trig Function blocks will see this transition but you may never see it simply by visually looking at the code. I would like to explore some options for how to write this control code before moving on to our slightly more complex example with a Middle PE. If the output was not controlling a Light. To fix this problem. when a box is placed on the conveyor. the conveyor would continue to run. however. and try to optimize the code we could also do the following. this would achieve the desired result. The below code uses the EntryPE to start the conveyor and the ExitPE to stop the conveyor. the box has reached the Exit PE the Motor Starter is de-energized and the conveyor will stop. if both Photo Eyes are blocked. If the two ‘IF’ statements were reversed and both PEs were blocked. If we look at a simple conveyor that has an Entry and Exit Photo Eye (PE). Once. 19 2 Chapter: PLC Programming “The Inspection Conveyor” . This is where a program like Scope View can be used to detect these short pulses. and one Motor Starter. what happens? In this case the ExitPE is looked at last and therefore the MotorStarter would be set to FALSE.

remember that at some point in the future. Each of the two inputs can only be either TRUE or FALSE. The Truth Table for our conveyor would look like the following. In the Motor Starter column is the state of the output that we would like. This makes the code more CPU friendly and also ensures that any time the ExitPE is blocked (TRUE) the conveyor will stop. readability decreases and vice versa. it will provide the most flexibility.This does a couple of things. Normally as efficiency increases. 19 3 Chapter: PLC Programming “The Inspection Conveyor” . Therefore anytime a box is present at the ExitPE the nested ‘IF’ statement to look at the EntryPE will not be executed. Although as a programmer it is good to optimize your code. you or someone else is going to have to read your code. Truth Tables are used to describe a Boolean function that has multiple inputs and one output. Finding a balance between efficiency and readability is always a difficult task. The last option I want to explain will be the most difficult to understand. notice that the numbers under the Input conditions are the binary equivalent to these decimal numbers. the fourth line shows that both inputs are TRUE. Notice that the only situation where the Motor Starter will be TURE is when the Entry PE is true and the ExitPE is FALSE. and as PEs or other conditions are added to the system it will be the easiest to manage and change. Our conveyor has two PEs and one Motor Starter. however. This covers all possible input situations. The first line shows them both being FALSE. The ExitPE will have a value of FALSE when there is not a box blocking the PE. based on the input conditions. the second line shows that the EntryPE is FALSE and the ExitPE is TRUE. The numbers on the far left are decimal numbers starting at 0. the third line shows the EntryPE is TRUE and the ExitPE is FALSE.

iStep will represent the decimal equivalent of the status. Let us assume that iStep is declared in the PLC as an integer.1.To translate this into code we will start by converting the Boolean inputs and combining them into an integer number. or 3 the Motor Starter is False. We can then control the output based on the value of iStep.2. If we then assign the ExitPE to the first bit of iStep and the EntryPE to the second bit of iStep. of the two PEs. iStep has four possible values 0. and 3 When iStep is 0. 1. We can now use a ‘CASE’ statement to control this: 19 4 Chapter: PLC Programming “The Inspection Conveyor” . When iStep is 2 the Motor Starter is True.

but if all three PEs are on then the PLC is writing to the output in two places. however. 19 5 Chapter: PLC Programming “The Inspection Conveyor” . If the value of iStep was to change. Adding the MiddlePE to the system will be simple in the ‘CASE’ statement. I would first like to repeat the first two ‘IF’ statements to show why and how this method becomes more complicated. If you wanted to start a timer when the ExitPE was blocked and the EntryPE was not. you could simple add that code to ‘CASE’ 1. within the same PLC scan. Although we are writing to the variable in multiple places.It is also possible to combine the CASES where the code is the same. it will be the next PLC scan before the ‘CASE’ would change. because they are inside of a ‘CASE’ statement only one of them will be written to in a given PLC scan. which would be much easier than trying to add it to the ‘IF’ statements in the first examples. This also gives us the flexibility to easily add more functionality based on the status of the inputs. simply separate the values with a comma. The below could be used.

19 6 Chapter: PLC Programming “The Inspection Conveyor” . copy and adjust which inputs are copied to which bits. and therefore more difficult to debug. Previously there were two PEs. simply add a third bit. If the ‘CASE’ statement is used then we will see how flexible it really is. but it is more complicated to follow.In the next example the code has been made more efficient and the PLC is only writing to the output once during the PLC scan. to add a third PE.

4.Expand the ‘Truth Table’ to include the new possible combinations From the ‘Truth Table’ we now see that the Motor Starter will be energized when iStep is equal to 2. or 6 19 7 Chapter: PLC Programming “The Inspection Conveyor” .

19 8 Chapter: PLC Programming “The Inspection Conveyor” . For this program we will use the ‘CASE’ statement as it is easier to make changes to. xConvRunEnable is defined as a local BOOLEAN. each Photo Eye will provide a stop command. Therefore we need to monitor the PE and select when it will have an effect on the conveyor. because any time the middle PE is blocked the Conveyor cannot move. This variable will be used to know when the Photo Eyes are in the correct states to start the conveyor. The xConvRunEnable will provide one of the start commands.This can be reduced to: For an example of how to use a Truth Table and Boolean Algebra for the most efficient coding of this example please refer to Appendix II – Truth Tables and Boolean Algebra. I have changed the variables names to match the naming convention. It will not be used to directly start and stop the conveyor. If we start with the following code we will see that the code gets locked up.

because they will not be used on this line of code. the simplest is to use a Rising Edge Trigger ‘R_Trig’ from the ‘Standard’ libray. If the IN goes FALSE then the timer will reset and start again with an ET (Elapsed Time) of zero. When a box reaches a PE the conveyor should stop. 19 9 Chapter: PLC Programming “The Inspection Conveyor” . The PE will provide the input and the output will be TRUE for one PLC scan. This sequence of steps is easily handled in a ‘CASE’ statement. Using each PE to stop the conveyor. Add the three R_Trig functions blocks to the code below the CASE statement. The Q outputs of the function blocks were removed. then a 5 second timer to pause the conveyor. In order to start the conveyor the enable needs to be TRUE and we are also going to pause the conveyor for 5 seconds each time a PE is blocked. It will be used later to stop the conveyor.There are several ways to do this. this will allow the operator to place a new box at the Entry PE. 5 seconds later the conveyor should start again. The timer needs a condition that will stay TRUE for the duration of the PT (Preset Time). then monitoring the xConvRunEnable will give us everything we need. This will allow the program to know that a new boxed has arrived. and the Q output of the ‘R_Trig’ can be monitored for stopping the conveyor while the PE itself is ignored.

Each step number also increases by a value of 10.The basic framework of the ‘CASE’ statement will look like the following. most ‘CASE’ statements are going to need to use it. As an example we will be adding a TON (Timer On) in step 20. The ‘Init’ step is there because it is a good habit to start. this allows for steps to be added without having to change all of the step numbers. Chapter: PLC Programming “The Inspection Conveyor” 20 0 . therefore. Each step has a comment that describes what will happen in that step. I always include it. this timer will be reset in the ‘Init’ step.

20 1 Chapter: PLC Programming “The Inspection Conveyor” .Below is the entire ‘CASE’ statement.

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

if it can go wrong it will.Also notice how the code is indented using the ‘TAB’ key. Over time you will start to learn the most common problems. Let us assume that a fly is in the building and it crosses in front of the path of the PE. however. One of them is the possibility of a glitch in the Photo Eye. If we look at step numbers. Compare the two pictures below to see the difference this makes. all of them deal with timing. If nothing ever went wrong our conveyor would be mostly complete at this point. When using a very sensitive PE it is possible that the PE will transition from FALSE to TRUE at times other than when a box appears in front of it on the conveyor. it is easy to move downward and find the next step number. 20 3 Chapter: PLC Programming “The Inspection Conveyor” . and not bouncing between TURE and FALSE. Also the IF and END_IF have nothing in between them. depending on the hardware of the PE it may or may not be detected. There are a couple of ways to do this. If it is detected then the conveyor is going to stop as if a box was present. To prevent this type of problem we can add a ‘De-bounce circuit’ to the code. This is done to help make the code more readable. It is unlikely that you as a programmer will think of every possible situation that could cause a problem. which makes the END_IF easy to locate. The idea of a ‘De-bounce circuit’ is to detect that a BOOLEAN condition has changed and stayed at its new state.

D=R*T Distance = Rate of travel * Time If the box is 10 inches long and we want to limit it so that no more than 25% of the box moves past the PE then our Distance will be 2. If the PLC scan is 10ms then after 100ms (iCount >= 10) xInputDebounced will be set to TRUE. If there is a way to know the velocity of the conveyor then we can calculate the precise time we need to ensure a box is present and still stop the conveyor before it falls off. If the conveyor is moving extremely slow then the code could wait for the PE to be True for 1 second before stopping the conveyor. We would then have to monitor xInputDebounced in our code and possibly look at other conditions for setting it to FALSE and set iCount back to 0. but also should not allow boxes to fall into the floor. This would be another reason not to use the above counter and rely on it to work in all situations. However as the conveyor increases in speed the 1 second wait might cause the box to move to far before stopping the conveyor. . In the above example when the PE is TRUE iCount will increase by a value of 1 each PLC scan. If this was done on the machine and then for some other reason the PLC task time needed to change. In my opinion using the PLC scan to control your code is never a good idea. Imagine we have a simple conveyor with a PE on the end of the conveyor. The box should stop at the end of the conveyor without stopping erroneously.5 inches 20 4 Chapter: PLC Programming “The Inspection Conveyor” When de-bouncing an input that involves motion the speed at which the product is moving needs to be considered. please refer to Appendix III – De-bouncing and Input. For another version of the above. The above example inherently uses the PLC cycle time as the timer. then all of the places in the code where we de-bounced an input would need to change.We will start with an obscure example because it makes for good sample code.

Add a Function Block with a name of FB_DebounceInputFalseToTrue 20 5 Chapter: PLC Programming “The Inspection Conveyor” . Our reaction is now Time = Distance / Rate of travel Time = 2.5 inches / 1fps Time = 2. We will assume that out conveyor is moving at 1 foot per second (fps). To make this more flexible and reusable we will place this into a Function Block and allow the values of Distance and Rate to adjusted by a variable. The output will turn False immediately when input turns False. Distance / Rate will return a LREAL value which cannot be stored in a variable of type TIME When the input is True for tTime (2.5 seconds Therefore we could implement the following code with a simple timer Note: The above sample will not compile.The Rate of travel will be the speed of the conveyor.5 seconds) the output will then be True.

Declare the follow in the Function Block Add the following code to the body of the Function Block The LREAL_TO_TIME conversion will convert the 2. multiplying by 1000.5ms.5s Open P_InFeedConveyor and use the Function Block to de-bounce the 3 PEs on the Conveyor.0 before converting will result in tTime having a value of T#2. 20 6 Chapter: PLC Programming “The Inspection Conveyor” .5 into T#2.

20 7 Chapter: PLC Programming “The Inspection Conveyor” .xExitPE. these must be replaced by our new de-bounced inputs. and xEntryPE are declared as local variables of type BOOL. xMiddlePE. In the Check if clear to advance and the Conveyor Advance sections we are using the real inputs in the code.

The jam detector on this conveyor will detect when a box leaves either the Entry or Middle PE and does not reach the next PE.In review of where we started We see that the following sections of code have been completed. and Conveyor Advance The On/Off delay was built into the CASE Statement for Conveyor Advance. If the timer completes within the given amount of time then this will indicate that the Box is stuck on the conveyor. This basic idea for the code is as follows Chapter: PLC Programming “The Inspection Conveyor” If both PEs are False then start a Timer. Because there will be two Jam Detectors we will implement this as a Function Block. so it can be removed. Check if clear to Advance. The next thing to implement is Jam Detection. A few things to consider: We don’t want the Jam Detector to cause an error if there are no boxes on the conveyor. De-bounce. 20 8 .

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

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

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

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

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

Create actions for the other possible Modes of E_StateMachine. Preform a Project-> Rebuild All to compile the code. It only has a code window. Then click ‘OK’. and E_Undefined. Double-click on the error and look at the code 21 4 Chapter: PLC Programming “The Inspection Conveyor” . Place a semicolon . E_Maintenance. Notice tha P_InfeedConveyor is now expandable. Actions will use the same local variable list from the POU in which it is contained. You should get 1 error. E_Manual. in each of the Actions. you will notice that it does not have a local variable declaration section.Name the ‘Action’ A_Auto. and set the language to ‘ST’. If you Double-Click on the Action. and the Action is shown when it is expanded.

In P_MachineMonitoring we were looking at the status of eStep. and Faults are not mode dependent and will stay in P_InfeedConveyor. Since we have now moved eStep to a Global Variable we need to correct this line of code. Jam Detection. and then Save your program. Copy and Paste the ‘Check if clear to advance’ and ‘Conveyor advance’ code from P_InfeedConveyor to A_Auto. and the code for Manual will be different. which was previously declared in MAIN. Preform another Project -> Rebuild All. Starting at line 40 Ending at Line 97 21 5 Chapter: PLC Programming “The Inspection Conveyor” . Simply remove ‘MAIN.’ In front of eStep. ‘Check if clear to advance’ and ‘Conveyor advance’ could happen in both Manual and Auto. We now need to move parts of the code from P_InfeedConveyor into the A_Auto Action De-bouncing the Input PEs. but the code was written for Auto.

21 6 Chapter: PLC Programming “The Inspection Conveyor” . We will create a new CASE statement that selectively calls the Actions based on the value of eStep.We must now call the Action A_Auto (and the other Actions) from P_InfeedConveyor. The code in A_Auto is complete for now.

Declare gatq_xJogConveyor as a Global Input For now A_Maintenance and A_Undefined have no use. in them. Chapter: PLC Programming “The Inspection Conveyor” 21 7 . Leave them with only a semicolon .In A_Manual we will add code for Jogging the Conveyor.

We will create some faults for the most obvious conditions that could happen in our program. create a fault for each of the two Function Blocks Create a new Global Variable list called Global_Variables_Faults In the Fault section of P_InFeedConveyor place the following code. 21 8 Chapter: PLC Programming “The Inspection Conveyor” Declare the two new Fault Variables . This code will turn on the two fault variables when a Jam is detected. Starting with Jam Detection.Fault Handling Creating faults for every possible situation is a never ending task.

giConveyorAutoSequenceErrID. gxConveyorAutoSequenceErr. and gsConveyorAutoSequenceErrMsg are defined in the Global_Variables_Faults list Chapter: PLC Programming “The Inspection Conveyor” When the variable iErrStepNumber has a value other than zero three types of faults will happen. In the CASE statement that handles the conveyor in Auto we created an Err Step Number variable called iErrStepNumber. 21 9 . Add the following code to create a fault when this error happens. then the fault variable will set back to True. gxConveyorAutoSequenceErr is a BOOL that will be set to TRUE. if the fault condition still exists. gsConveyorAutoSequenceErrMsg will hold a STRING that gives a description of the error and the Error Step number. Note: This reset code will only reset the fault variable. giConveyorAutoSequenceErrID is an INT that will hold the value of the Error Step.Add the following code to reset the faults.

The core of the program we just created could be summed up in 1 line of code However. The more efficient the code is. the more difficult it is to read. Not IF. Comparing the above line of code with the program that we created gives the impression that we wrote a bunch of code for no reason. However the easier it is to read the harder it is to program when changes have to be made. and resetting them. I would like to remind you of a point I made earlier. the power of this modular approach using Functions and Function Blocks will become very obvious. Instead we will set it back to zero when the Reset button is pressed. but there could potentially be a problem caused by the PLC scan. Add the following code As we expand upon our Faults in further chapters we will explore more efficient was to handle Faults. However as we expand the machine. this program is not flexible. 22 0 Chapter: PLC Programming “The Inspection Conveyor” At this point our conveyor is complete. However. there is currently no code to change iErrSStepNumber back to 0. but WHEN someone decides that the machine needs to be modified it will be more difficult to do. We could do this somewhere in the CASE statement. .These Erros should be Reset by use of the variable gati_xReset.

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

 The below tasks are configured with a ‘SlowTask’ at 50ms and a Priority of 2. and the task ‘FastTask’ has an interval of 1ms and a Priority of 0 The highest Priority ‘0’ should always have the fastest interval time    In this configuration the ‘Standard’ task calls the program ‘MAIN’ ‘MAIN’ will then call its subsequent POUs 22 2 Chapter: Trouble shooting . task ‘Standard’ runs at 10ms with a Priority of 1.

right click on a POU and select ‘Show Call Tree’ 22 3 Chapter: Trouble shooting .     In the below example ‘MAIN’ is calling the other programs The first line of code in ‘MAIN’ calls the program ‘Manual’ ‘Manual’ will run its code from top to bottom and then return to ‘MAIN’ ‘MAIN’ will then call ‘Semi_Auto’ ‘Semi_Auto’ will run its code from top to bottom and then return to ‘MAIN’  Note: To view the Call Tree.

line 6 is the last line of code   22 4 Chapter: Trouble shooting . If a Function Block is called from a program the same process applies  When the last line of code in ‘MAIN’ is reached the PLC will return to the first line and repeat the process Below is an online view of ‘MAIN’ The dark gray lines are code that is running.

but with the PLC running every 10ms you probably won’t make it in time.24. Break Points    WARNING! A Breakpoint will stop the PLC Note: If a breakpoint is set by accident the fastest way to remove it is to ‘Logout’ of the PLC (F12). Breakpoints are enabled and disabled in the Project -> Options menu  22 5 Chapter: Trouble shooting .

  In the left column select ‘TwinCAT’ Select ‘Enable breakpoints’ then click ‘OK’   Breakpoints can be used to aid in debugging the PLC code When the line is selected where the Breakpoint is to happen the PLC code will run until that line of code is reached When the breakpoint is reached the PLC will stop running and the status of variables can be seen in their current state This will allow the checking of the code to determine if the code is executing properly Note: Breakpoints can NOT be set in an instance of a function block they must be set in the implementation of the function block and therefore each instance of that function block will stop when the breakpoint is reached. To set a breakpoint click on the rung or line number where you wish the PLC to stop Chapter: Trouble shooting     22 6 .

 Here the breakpoint has been set on line 4. bSwitch is currently TRUE and therefore the PLC is still running  Also note that the breakpoint indicator is set in the bottom right corner of the PLC Control   When bSwitch turns FALSE the breakpoint on line 4 will stop the PLC The code on line 4 is not executed  We can also see in the status bar that the PLC is no longer running 22 7 Chapter: Trouble shooting .

Chapter: Trouble shooting 22 8 . If only one breakpoint is set then the PLC will run from the breakpoint thru the last line of code.   The Online menu provides the programmer with a list of options The Run (F5) command will start the PLC again and it will run until it hits a breakpoint The Toggle Breakpoint(F9) command will remove or add a Breakpoint at the line where the cursor is currently located Step over (F10) will execute the line of code and go to the next line of code If a call to another POU is on the line of code being executed. Note: Once a breakpoint has been reached the Single Cycle command will still stop at the breakpoint even if the code would not normally execute the line of code where the breakpoint exists. the POU will run in its entirety   Step in (F8) will perform the same action as Step over with the added functionality of opening the called POU and stepping through its code line by line Note: The Step in command will not open a POU inside of a library  Single Cycle (Ctrl+F5) will run the PLC to the next breakpoint. upon the next Single Cycle command the PLC will run from the first line of code up to the breakpoint.

   The Breakpoint Dialog command opens the below window From here you can see a list of all breakpoints that exists in the PLC Breakpoints can also be added and removed from here 22 9 Chapter: Trouble shooting .

25. Flow Control   Flow control allows you to see which lines of code are being executed In the sample lines 1 and 4 are running because 1 is greater than 0 23 0 Chapter: Trouble shooting .

there are 3 possible reasons for this. Flow Control can be turned on thru the ‘Online’ menu or with the keyboard shortcut Ctrl+F11  Flow Control may appear at times to not be working. The program you are monitoring is not being called 3. You must be ‘Logged In’ to the PLC 2. The task that is responsible for calling the program you are monitoring must be set to the ‘Debug Task’ Chapter: Trouble shooting 23 1 . 1.

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

   The debug task can be set in the Task configuration when you are logged in to the PLC Right click on the Task name and set it as the ‘Debug’ task Flow Control is only displayed for the ‘Debug’ task     Warning!!! Flow control should never be used inside of a function block Only use Flow control in a Program If Flow Control is on inside of a Function Block it will display the values and status of the first instance of that Function Block 23 3 Chapter: Trouble shooting .

 In the below picture you see that the second instance of the Function Block indicates that it is running even though it is not being called from ‘MAIN’ 23 4 Chapter: Trouble shooting .

  Notice in this picture that bPulse is blue indicating that it has a value of TRUE However fbPulse2 is not being called from ‘MAIN’ and bPulse in the local delaration has a value of FALSE NEVER use Flow Control inside of a Function Block  23 5 Chapter: Trouble shooting .

26. Global Search  The Global Search tool allows for the search of anything inside of any part of the project or the entire project A Global Search can be started in 3 different ways    Project -> Global Search Ctrl+ Alt + S Tool Bar Icon  23 6 Chapter: Trouble shooting .

    Selecting Global Search from the Project Menu will open the following window Ctrl+Alt+S will open the same window From here the sections of the program to be searched can be selected Holding the Ctrl key will allow for selecting multiple sections Note: Using the Tool Bar icon skips this selection window and will search the entire project. 23 7 Chapter: Trouble shooting .

 Once the sections have been selected press the ‘OK’ button 23 8 Chapter: Trouble shooting .

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

 Searching for the letter ‘a’ will return everywhere the letter ‘a’ is used in the sections selected   The first line shows the search phrase The last line shows how many times the search phrase was found 24 0 Chapter: Trouble shooting .

 The second line below is stating the following   Double Clicking a line in the Message Window will take you to that line of code in the program When using the search tools on a structure remember that the Global Search will search for anything and the Cross Reference needs an exact variable name The Global Search tool can be used to search for an element within a structure. the instance of the structure or both  24 1 Chapter: Trouble shooting .

27. Additionally if a Build has not been done since the last change was made the cross reference could return incorrect results 24 2 Chapter: Trouble shooting . Cross Reference  The Cross Reference tool allows for searching specific items in the PLC     Variable Address POU The tool can be started 2 ways   Project -> Show Cross Reference Ctrl+Alt+C  Note: The code must compile with no errors before a cross reference can be done.

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

 The ‘List of References’ shows the following      The POU and line where the variable was found The name of the variable The address of the variable (if it has one) The scope of the variable Global or Local The Variable access (Read or Write) 24 4 Chapter: Trouble shooting .

  When searching by address the full address must be entered Only the address entered will be searched. overlapping memory addresses will not be found 24 5 Chapter: Trouble shooting .

but when multiple tasks are used this will tell you which task to set as the ‘Debug Task’ for displaying the ‘Flow Control’ 24 6 Chapter: Trouble shooting . The POU search is limited.

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

TwinCAT Scope View  Right click on Scope and select Add Scope View 24 8 Chapter: Trouble shooting . Scope View    Scope View is a software oscilloscope for monitoring variables in the PLC Scope View is an optional component that can be installed when TwinCAT is installed From the Windows Start menu select Programs. TwinCAT System.28.

 Leave the defaults and select OK  Right click on Scope View 1 and select Add Channel 24 9 Chapter: Trouble shooting .

 Give the Channel a descriptive name and press OK  On the Acquisition Tab of the Channel press the Change button 25 0 Chapter: Trouble shooting .

 In the Edit Acquisition window select the correct Server Port and press the Reload Symbols button 25 1 Chapter: Trouble shooting .

 Select MAIN.BSWITCH and press OK 25 2 Chapter: Trouble shooting .

 Press the Start button 25 3 Chapter: Trouble shooting .

 When the PLC variable changes state the change can be seen in the Scope 25 4 Chapter: Trouble shooting .

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

both systems. Compatibility The TcMC2 motion control library contains enhanced and new functions.0 (www. It enables transition of two travel commands with a defined velocity at a certain position. On remote programmable controls.30. Users maintaining existing projects are advised to continue using the original TcMC library for these projects. 25 6 Chapter: Camming . Overview The TcMC2 TwinCAT motion control PLC library includes function blocks for programming machine applications and represents a further development of the TcMC library.10 build 1340.Lib a. Main new features A key feature of TcMC2 compared with TcMC is the so-called buffer mode. must have installed an appropriate version. Move commands can be followed by further Move commands during execution. The function blocks are better adapted to the requirements of the PLCopen specification and are not compatible with the first version (TCMC). Buffer mode enables Move commands to be queued in order to achieve a continuous positioning without intermediate stops. This makes adaptation of target position or travel speed during the movement much easier. TwinCAT Version The TcMC2 library is available from TwinCAT version Windows CE systems must have installed an image from version Windows CE 3. TcMC2 is based on the revised PLCopen specification for motion control function blocks V2. although TcMC2 should be used for new projects or revision of existing projects. the programming PC and the control PC. Intro to TcMC2.

If Execute is triggered more than once while a command is executing. the function block will not execute further commands and will not provide any feedback. jerk [mm/s3]. a falling edge at Execute has no influence on the command execution.General rules for MC function blocks For all MC function blocks the following rules apply. MC_Stop. deceleration [mm/s2]. When the Execute input becomes TRUE. To change the parameters the command has to be triggered again once it is completed or a second instance of the function block must be triggered with new parameters during command execution. the following units are used: Velocity [mm/s]. A meaningful default value is used for the first call. i. for example. the axis is released and Busy as well as Active are reset to FALSE. Position and Distance The Position input denotes a defined value within a coordinate system.g. Input parameters The input parameters are read with rising edge at Execute. ErrorID and CommandAborted are reset with a falling edge at input Execute. Only then are the outputs reset. [mm] or [°]. Dynamic parameters Chapter: Camming The dynamic parameters for Move functions are specified in technical units with second as time base. Error. 25 7 . since the axis is locked. InGear. However. the last value transferred to this block remains valid. while Distance is a relative measure for the distance between two positions. which ensure defined processing through the PLC program. MC_Stop sets Done to TRUE as soon as the axis is in standstill. Acceleration [mm/s2]. e. only one of these outputs can be TRUE at a function block at any one time. only one of the outputs Active. If an axis is scaled in millimeters. InSync. Error. Busy and Active stay TRUE. An exception of this rule is. Initial state The outputs Done. Done and CommandAborted can be TRUE at any one time. After Execute is reset to FALSE. Resetting Execute during command execution ensures that one of the outputs is set at the end of the command for a single PLC cycle. Done. Position and Distance are specified in technical units. according to the axis scaling. if the function block is not active (Busy=FALSE). Error and CommandAborted are mutually exclusive. If an input parameter is not transferred to the function block. one of the outputs must become TRUE. Similarly. InVelocity.e. Exclusivity of the outputs The outputs Busy.

Communication errors usually indicate incorrect configuration or parameterization. Error indicates the error. Communication errors (the function block cannot address the axis. They are reset automatically when the Execute input is reset. system-wide error number. An axis error must be reset through MC_Reset. following error). It depends on the unique. the Enable input results in an action being executed permanently and repeatedly. A function block with an Enable input indicates through the Valid output that the output data is good. as long as Enable is TRUE. an error in the logical NC axis. 25 8 Chapter: Camming . the function block must be called cyclically for the command to be executed. InGear and InSync indicate successful command execution and are not set if Error becomes TRUE. the Active output of each block indicates that the axis executes the command. InVelocity. The outputs Done. MC_ReadStatus cyclically updates the status of an axis. Drive errors (control device) may result in an axis error. Function block errors do not have to be reset explicitly. Errors of different type are signaled at the function block output. Axis errors (logical NC axis) usually occur during the motion (e. Behavior of the Busy output The Busy output indicates that the function block is active. ErrorID contains a supplementary error number. for example). The data is updated continuously while Valid is TRUE.) is set when a command was executed successfully. a separate reset mechanism may be required (e. Busy is immediately set with a rising edge at Execute and is only reset when the command was completed successful or unsuccessfully. A reset is not possible. not the axis (e.Error handling All function blocks have two error outputs for indicating errors during command execution. etc. Enable input and Valid output In contrast to Execute. InGear. Behavior of the Active output If the axis movement is controlled by several functions. InSync. Depending on the drive controller. Behavior of the CommandAborted output CommandAborted is set if a command is interrupted through another block.g. connection of a reset line to the control device). If several function blocks are used for an axis and the running command is interrupted through a further block. the Done output for the first block is not set. As long as Busy is TRUE. The function block can only be triggered again after the configuration was corrected. for example. In many cases axis errors and drive errors can be reset together through MC_Reset.g. as long as Enable is TRUE.e. if Busy is FALSE. They cause the axis to switch to error status. The error type is not specified explicitly.g. Behavior of the Done output The Done output (or alternatively InVelocity. The block can only be triggered with a rising edge at Execute. i. The status Busy=TRUE and Active=FALSE means that the command is not or no longer executed. Error types Function block errors only related to the function block. incorrect parameterization).

This is referred to as Blending. but passes through this position with the velocity of the last command. If more than one command is triggered while a command is running. it becomes active and interrupts the running and an already queued command. In this case just Buffer-Mode Aborting can be used. The following command is started from standstill. In contrast to Buffered the axis does not stop at the previous target. infrequently required options. For example. but passes through this position with the velocity of the first command. the command started last for queuing is rejected with an error. The command is executed immediately and interrupts any other command that may be running. In queued mode a subsequent command waits until a running command is completed. 25 9 Chapter: Camming . BufferMode can specify that a command interrupts another command (nonqueued mode) or that the following command is only executed after the previous command (queued mode). In non-queued mode a subsequent command leads to termination of a running command. In contrast to Buffered the axis does not stop at the previous target. BlendingPrevious: The command is executed after no other command is running on the axis. A motion command will then decouple the axis and move it afterwards. but passes through this position with the lower velocity of two commands. In this case the previous command sets the CommandAborted output. BlendingHigh : The command is executed after no other command is running on the axis. The previous movement continues until it has stopped. so that the input can remain open. For the basic block function these options are often not required. In contrast to Buffered the axis does not stop at the previous target. In queued mode BufferMode can be used to specify the movement transition from one command to the next. In contrast to Buffered the axis does not stop at the previous target. The user only has to populate the Options data structure in cases where the documentation explicitly refers to certain options. Options input Many function blocks have an Options input with a data structure containing additional. Only one command is queued while another command is executed.BufferMode Some function blocks have a BufferMode input for controlling the command flow with several function blocks. If the last command is started in non-queued mode (Aborting). BlendingNext : The command is executed after no other command is running on the axis. Buffered : The command is executed after no other command is running on the axis. which specifies the velocity at the transition point. BlendingLow : The command is executed after no other command is running on the axis. BufferModes Aborting : Default mode without buffering. Slave Axes Motion commands like MC_MoveAbsolute can be passed to slave axes if they are explicitly enabled in the axis parameters. but passes through this position with the higher velocity of two commands.

SetPos Please note that the sub elements for the NcToPlc and PlcToNc structures now have English names in view of the international market.NcToPlc. Example: TcMC : NcToPlc_Axis1.b. An existing project generally accesses the content of the NcToPlc structure. In most function blocks. the current set position for an axis is no longer referred to as fPosSoll. the NCTOPLC_AXLESTRUCT data structure was transferred at the Axis input. For example. including MC_MoveAbsolute. expected an additional PLCTONC_AXLESTRUCT structure. The structure contains the cyclic input and output data for the NC plus additional status information. NcToPlc_Axis1 AT %I* : NCTOPLC_AXLESTRUCT. PlcToNc_Axis1 AT %Q* : PLCTONC_AXLESTRUCT. but as SetPos. Axis1: AXIS_REF. In the TcMC2 environment the axis structure was extended so that all required data are included in a single structure. which is transferred to each MC function block. Migration from TcMC to TcMC2 The main differences and modifications between the TcMC motion control library and the extended TcMC2 library are listed here. Certain function blocks. The data are also available in the Axis1 structure and can be used to adapt the application program.fPosSoll TcMC2 : Axis1. so that the effort for converting an existing project can be estimated. including MC_Power. 26 0 Chapter: Camming . Axis data structure In the past an axis required two data structures for cyclic data exchange with the NC.

The following table contains a list of blocks with more extensive modifications. MC_MoveAbsoluteOrRestart MC_Move. MoveAbsoluteOrRestart can be replaced with two instances of a Move block (see BufferMode). MC_SetActualPosition can be replaced with MC_SetPosition.Function blocks The input and output configuration of the function blocks has changed slightly compared with TcMC.. In this case just Buffer-Mode Aborting can be used. .11). MC_NewPos MC_NewPosAndVelo MC_Move.. A motion command will then decouple the axis and move it afterwards. In addition.. the blocks now also support a Busy and Active output. the block will behave like 26 1 Chapter: Camming MC_GearOutExt MC_Move. TcMC MC_GearInFloat TcMC2 MC_GearIn Remark MC_GearIn now accepts the gear ratio as a floating point value The new BufferMode enables each Move block to be used to assign a new target for the axis or change the velocity. Motion commands like MC_MoveAbsolute can be passed to slave axes if they are explicitly enabled in the axis parameters (from TwinCAT 2. To set an axis position on the fly. The input configuration was adapted accordingly. These modifications generally only require little migration effort. MC_CamIn MC_CamInExt MC_CamIn MC_SetReferenceFlag MC_Home MC_SetPositionOnTheFly MC_SetPosition MC_SetActualPosition MC_SetPosition MC_OrientedStop MC_MoveModulo MC_MoveModulo can be executed from standstill or in motion. If started in motion. The new MC_CamIn function block deals with the function of the extended MC_CamInExt block. Setting and resetting of the reference flag (axis is referenced) can be achieved with the MC_Home block.. MC_SetPosition can be used in relative mode (Mode=TRUE).. actual and set position.. The new function block sets both. The NewPos function blocks are therefore no longer required. The main new feature is support for MC_BufferMode in Move blocks.

so that the TcNC library is no longer required. MC_Stop is only used in a particular condition when the axis must be locked against further motion. The new TcMC2 library no longer has this dependency. the TcNC library can still be used for compatibility reasons. so that this was always integrated in a project. 26 2 Chapter: Camming .MC_OrientedStop MC_Stop MC_Halt. MC_Stop MC_Halt stops the axis in a normal operation cycle. All required declarations and functions are now included in TcMC2 library itself. TcNC library The previous TcMC library required declarations and functions from the TcNC library. Nevertheless.

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

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

26 5 Chapter: Camming . Gearing With a 1:1 gear Ratio the two axes will move the tooling at a 45 degree angle.6:1 gear ratio the axes will move the tooling in a diagonal line as seen below.b. With a 3.

This can be accomplished by having the gear ratio doubled. the mathematics of the cam table allow you to make the transition from one point to the next as smooth as possible while guaranteeing that the slave will be at the specified point when the master reaches its predefined position. For example if at 360 degrees both slave and master must be at 360 degrees. Linear and fixed gear ratios are no problem but determining a position based on adjusting the gear ratio is time dependant and time is not necessarily under the control of the programmer.c. The cam table allows you to specify any point for the slave to be at any position of the master. Linearly Increasing Gear Ratio (Dynamic) Dynamically changing the gear ratio by a fixed increment each PLC cycle will create a curve. but it is Time dependant and if the gear ratio is not changed at exactly the right time for correct length of time the proper position cannot be reached. So gearing works well for linear changes but not arbitrary changes. 26 6 Chapter: Camming . The math for any other curve is long and complicated. The key behind the cam table is that it is used when the slave position relative to the master position is critical. if the ratio is changed too early or too late the target position will not be reached. but when the master reaches 720 the slave must be at 1080.

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

Creating a Cam Table with Function Blocks Prerequisites: TwinCAT NC PTP 2. (* Y'' *) SlaveJerk : LREAL. RelIndexNextPoint : MC_MotionFunctionPoint_ID. b. Overview By the use of the TcMC2_Camming library a cam table can be created. the individual points. A motion function is a one-dimensional list (array) of type MC_MotionFunctionPoint. The mode in which the Cam Table is to be activated is also selectable. Motion Function Points define the points on the table and the associated Motion Function to be used with that point. and used directly from the PLC.10 Build 1340 or Higher TcMC2_Camming. (* Y''' *) END_STRUCT END_TYPE 26 8 Chapter: Camming . on the Cam Table can be adjusted after the coupling has been performed. The reference to the Cam Table by use of a pointer is created to define the starting memory location and size of the Cam Table. The data structure MC_MotionFunctionPoint describes an interpolation point of a motion function. (* Y *) SlaveVelo : LREAL. Defining the Points on the Cam Table i. (* X *) SlavePos : LREAL. This table ID will be used by the programmer to reference the Cam Table when creating and/or selecting it for use. PointType : MC_MotionPointType. The use of the CamIn procedure will couple the slave axis to the master axis with the given TableID as a reference. and the properties of those points. The description includes the point itself. a definition of the function type and a relative pointer to the end point of the motion function segment. (* Y' *) SlaveAcc : LREAL. TYPE MC_MotionFunctionPoint : STRUCT PointIndex : MC_MotionFunctionPoint_ID. Motion Function Point A motion function point describes a start point of a motion function. In order to provide more flexibility. adjusted. FunctionType : MC_MotionFunctionType. Each Cam Table will have a unique TableID from 1 to 255. Additionally the table type must be defined. MasterPos : LREAL. implemented.lib (From the TwinCAT NC Camming Supplement) a.32.

PointIndex: Absolute index of this interpolation point within the motion function. (* Adding of segments *) MOTIONPOINTTYPE_ACTIVATION := 16#2000 (* 1: activation point *)). MC_MotionFunctionPoint_ID is of type UDINT. MOTIONFUNCTYPE_POLYNOM5_MM := 15. All following points in the list add 1 to the PointIndex. TYPE MC_MotionFunctionPoint: ( MOTIONPOINTTYPE_IGNORE. Notes: The first point in a list must start AT any index > 0. MOTIONFUNCTYPE_BESCHLTRAPEZ_RT := 22. (* Turn point *) MOTIONPOINTTYPE_MOTION := 16#0008. (* Motion point *) MOTIONPOINTTYPE_ADD := 16#0F00. TYPE MC_MotionFunctionType : ( MOTIONFUNCTYPE_NOTDEF. Type MC_MotionFunctionType of the mathematical function between this and the subsequent interpolation point. FunctionType: Type definition for motion functions. END_TYPE (* 1: polynom with order 1 *) (* 3: polynom with order 3 (rest <-> rest) *) (* 5: polynom with order 5 (rest <-> rest) *) (* 15: polynom with order 5 (motion <-> motion) *) (* 22: acceleration trapezoid (rest <-> turn) *)). END_TYPE RelIndexNextPoint: Relative reference to the subsequent interpolation point (usually 1). MOTIONFUNCTYPE_POLYNOM5 := 5. MOTIONFUNCTYPE_POLYNOM1 := 1. Notes: The type Automatic motion function type used in the TwinCAT Cam Design Editor corresponds to MOTIONFUNCTYPE_POLYNOM5_MM. PointType: Type MC_MotionPointType of this interpolation point. MOTIONFUNCTYPE_POLYNOM3 := 3. (* Velocity point *) MOTIONPOINTTYPE_TURN := 16#0004. The point index of all interpolation points must increase strictly monotonously and must have no gaps and be greater than 0. (* Rest point *) MOTIONPOINTTYPE_VELOCITY := 16#0002. (* Ignore point *) MOTIONPOINTTYPE_REST := 16#0001. 26 9 Chapter: Camming .

FunctionType VM_MotionFunctionPoints[3].MasterPos := 0. VM_MotionFunctionPoints[1]. 1. 1. 15.PointType VM_MotionFunctionPoints[3]. := := := := := := 3.SlavePos := := := := := := 2.RelIndexNextPoint VM_MotionFunctionPoints[2]. Chapter: Camming := := := := := := 4.RelIndexNextPoint VM_MotionFunctionPoints[4].ii.PointIndex VM_MotionFunctionPoints[3]. (*1 = Increment PointIndex by 1 to get to Next Point.PointType VM_MotionFunctionPoints[4].PointIndex := 1. 27 0 .MasterPos VM_MotionFunctionPoints[2].FunctionType VM_MotionFunctionPoints[2]. 150. (*Point 2*) VM_MotionFunctionPoints[2]. must be 0 for the last point on the table*) VM_MotionFunctionPoints[1]. 1.SlavePos := 0.MasterPos VM_MotionFunctionPoints[4].RelIndexNextPoint := 1. 30.RelIndexNextPoint VM_MotionFunctionPoints[3].SlavePos (*Point 3*) VM_MotionFunctionPoints[3]. (*MOTIONPOINTTYPE_REST*) VM_MotionFunctionPoints[1]. 0. VM_MotionFunctionPoints[1].MasterPos VM_MotionFunctionPoints[3]. 15.PointType VM_MotionFunctionPoints[2]. 60. Sample Code: Below is a really bad graphical representation of the Points on the Cam Table below. Point3 Point4 X--------X / \ / \ / \ / \ ------X--------X Point1 Point2 X-------------X Point5 Point6 (*Point 1*) VM_MotionFunctionPoints[1]. (*MOTIONFUNCTYPE_POLYNOM5_MM*) VM_MotionFunctionPoints[1].FunctionType := 15.PointIndex VM_MotionFunctionPoints[2].FunctionType VM_MotionFunctionPoints[4]. 1.PointType := 1. 1. 45. 15. 150.PointIndex VM_MotionFunctionPoints[4]. 1.SlavePos (*Point 4*) VM_MotionFunctionPoints[4].

1. 15.PointType VM_MotionFunctionPoints[5].RelIndexNextPoint VM_MotionFunctionPoints[6].FunctionType VM_MotionFunctionPoints[5].PointIndex VM_MotionFunctionPoints[6].SlavePos (*Point 6*) VM_MotionFunctionPoints[6].RelIndexNextPoint VM_MotionFunctionPoints[5]. 1.MasterPos VM_MotionFunctionPoints[6].FunctionType VM_MotionFunctionPoints[6]. 0. 75.PointType VM_MotionFunctionPoints[6]. 0. 0. 360.PointIndex VM_MotionFunctionPoints[5].(*Point 5*) VM_MotionFunctionPoints[5]. 1. 15. := := := := := := 6.SlavePos := := := := := := 5. 27 1 Chapter: Camming .MasterPos VM_MotionFunctionPoints[5].

i.. or MC_TABLETYPE_NONEQUIDISTANT it the distance is variable. UDINT. and table type. The number of rows is entered in the component NoOfRows. The first column contains an ascending list of master positions. Example: Table1 : ARRAY[0.360. b. Overview Within the PLC a Cam Table can be defined by providing a starting memory location. UDINT. pArray := ADR( Table1 ). Example: ArraySize := SIZEOF( Table1 ). The address can be assigned with the ADR function. Chapter: Camming 27 2 . The data structure depends on the table type TableType. The second column contains the associated slave positions. TableType: The table type is MC_TABLETYPE_EQUIDISTANT. UDINT. Defining the Cam Table in the PLC a. the number of columns in NoOfCols (usually 1 or 2). if the master positions have the same distance. size. which can be determined with the SIZEOF function. NoOfColumns: The number of columns is 2. 0. MC_TableType. MC_CAM_REF TYPE MC_CAM_REF : STRUCT pArray ArraySize TableType NoOfRows NoOfColumns END_STRUCT END_TYPE : : : : : UDINT. ArraySize : Storage capacity of the two-dimensional array.. Example 1: Position table structure description pArray: Address of a two-dimensional array. The data structure MC_CAM_REF describes the data memory of a cam plate in a further PLC variable (array). NoOfRows: The number or rows corresponds to the number of table points. The first parameter pArray is a pointer to a data structure containing the cam plate data.1] OF LREAL.33.

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

(* n*m tabular with strictly monotone ascending master values (not imperative equidistant) *) MC_TABLETYPE_NONEQUIDISTANT := 11. CamTable_Slave. END_TYPE (* i. (*MC_Cam_Ref contains the location.TableType := MC_TABLETYPE_MOTIONFUNCTION.pArray := ADR(VM_MotionFunctionPoints).ArraySize := SIZEOF(VM_MotionFunctionPoints). CamTable_Slave.. motion function calculated in runtime *) MC_TABLETYPE_MOTIONFUNCTION := 22 ). CamTable_Slave. (*The size of the Array determines the number of points in the Cam Table*) CamTable_Slave : MC_Cam_Ref. 27 4 Chapter: Camming . and type of the Cam Table*) (*Provide MC_Cam_Ref with the data of the CAM Table*) CamTable_Slave.NoOfColumns := 1. size.c. CamTable_Slave. MC_TableType TYPE MC_TableType : ((* n*m tabular with equidistant ascending master values *) MC_TABLETYPE_EQUIDISTANT := 10.6] OF MC_MotionFunctionPoint. Sample Code: (*Cam Table Data*) VM_MotionFunctionPoints : ARRAY [1.NoOfRows := 6.

MC_CamTableSelect does not have to be used. The block creates a new table and simultaneously fills it with data provided by the PLC. Outputs Done: becomes TRUE. simple coupling with MC_CamIn is sufficient. 27 5 .34. Error: Becomes TRUE. if the cam plate was created successfully. the function block is ready for a new command. b. is set. Creating the Cam Table a. if a table created with the TwinCAT cam plate editor is to be used. Done or Error. as soon as an error occurs. a table can be specified and loaded into the NC. ErrorID: If the error output is set. CamTableID: ID of the cam plate used for coupling. Overview The Cam Table Select block enables the programmer to create a Cam Table by providing the Master and Slave axes along with the ID of the Cam Table to be used. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. Periodic: Periodic is TRUE if the cam plate is repeatedly cyclically. Chapter: Camming Input/Outputs Master: Axis data structure of the master Slave: Axis data structure of the slave CamTable: The data structure of type MC_CAM_REF describes the data storage for the cam plate in the PLC. Inputs Execute: The command is executed with a rising edge at input Execute. this parameter supplies the error number. In this case. SlaveAbsolute: Absolute interpretation of slave positions. At the same time one of the outputs. MC_CamTableSelect With the function block MC_CamTableSelect. and the reference to the Cam Table. MasterAbsolute: Absolute interpretation of master positions. When Busy becomes FALSE again.

Periodic:= TRUE. SlaveAbsolute:=TRUE . (*Create the Cam Table*) fbMC_CamTableSelect1( Execute:= bCamTableSel1.i. CamTable:=CamTable_Slave . MasterAbsolute:=TRUE . Done=> . Error=>bErrorCamCreate . (*MC_CamTableSelect*) : : BOOL. fbMC_CamTableSelect1 : MC_CamTableSelect. : BOOL. Slave:=Slave . Axis_Ref. Busy=> . Sample Code: (*Axes*) VM Slave (*Triggers*) bCamTableSel1 (*FB Error Info*) bErrorCamCreate iErrorIDCamCreate : : Axis_Ref. ErrorID=>iErrorIDCamCreate ). CamTableID:=1 . UDINT. 27 6 Chapter: Camming . Master:=VM .

the Cam Table created by the PLC can be viewed but changes will not be saved. 27 7 Chapter: Camming . Once the Cam Table has been uploaded changes can be made to tweak the table. Importing a Cam Table for Verification a. b.35. and then corresponding changes can be made to the PLC code. Overview Without a license for the TwinCAT Cam Design Tool. Creating a Blank Table Under the NC-Configuration. right click on Tables and select Append Table… Leave the defaults and select OK.

If you do not have a license for the Cam Design Tool you will receive the following message. Select OK. 27 8 Chapter: Camming . Right click on Master 1 and select Append Slave… Leave the defaults and select OK.

You should now see an empty Cam Table. 27 9 Chapter: Camming .

c. Importing the Cam Table On the Slave Tab verify that the Table ID matches the Table ID used in the PLC program. 28 0 Chapter: Camming . If it does not match then right click on the Slave and select Change ID.

Leave the defaults and select OK. After verifying the Table ID.Change the ID: and select OK. select Upload. 28 1 Chapter: Camming .

28 2 Chapter: Camming .Your Cam Table should now look like the following.

MasterScaling : LREAL := 1. b. CamTableID : MC_CAM_ID.CamTableQueued can be used to check whether a cam plate is queued for switchover. The switching rules. Options : ST_CamInOptions.0. MC_CamIn The function block MC_CamIn activates master-slave coupling with a certain cam plate. 28 3 Chapter: Camming . the two axes are now ready to be cammed together. END_VAR Execute: The command is executed with a rising edge at input Execute MasterOffset: Offset to the master position of the cam plate SlaveOffset: Offset to the slave position of the cam plate MasterScaling: Scaling of the master position of the cam plate StartMode: StartMode determines whether the cam plate position is interpreted absolute or relative to the coupling position. Camming the two Axes together a. In addition it is possible to switch to a new cam plate in coupled state. MasterOffset : LREAL.0. Overview Once the Cam Table has been defined. in particular the time or position. The status flag Axis. SlaveScaling : LREAL := 1. and created. StartMode : MC_StartMode.36. BufferMode : MC_BufferMode. StartMode can be relative or absolute for master (X coordinate) and slave (Y coordinate). verified. can be specified.Status. SlaveOffset : LREAL. Inputs VAR_INPUT Execute : BOOL.

ActivationPosition: Optional master position at which a cam plate is switched. the function block is ready for a new command. the position refers to the non-scaled cam plate. For cam plate switching Active becomes TRUE. BOOL. it can be divided by the MasterScaling before the function block is called.) If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used. Inputs/outputs VAR_IN_OUT Master Slave END_VAR Chapter: Camming : : AXIS_REF. is set. Error: Becomes TRUE. depending on the ActivationMode. CommandAborted or Error. Active becomes FALSE and InSync is set. Active: Active indicates that the command is executed. InSync: Becomes TRUE. this parameter supplies the error number. 28 4 . as soon as an error occurs. if the coupling was successful and the cam plate is active. ErrorID: If the error output is set. At the same time one of the outputs. Not required for motion functions Outputs VAR_OUTPUT InSync : Busy : Active : CommandAborted : Error : ErrorID : UDINT.CamTableID: ID of the cam plate used for coupling BufferMode: currently not implemented Options: Data structure with further coupling and switching options: ActivationMode: ActivationMode specifies the switching time or position at which cam plate coupling or switchover takes place. (not required for first coupling. When Busy becomes FALSE again. END_VAR BOOL. InSync. if the coupling command was executed successfully but the cam plate is still queued. BOOL. AXIS_REF. BOOL. If the cam plate is activated depending on the ActivationMode. CommandAborted: Becomes TRUE. BOOL. MasterScalingMode: Optional Scaling mode for the master position of the cam plate SlaveScalingMode: Optional Scaling mode for the Slave position of the cam plate InterpolationType: Interpolation type for position tables. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. The axis may have become decoupled during the coupling process (simultaneous command execution). if the command could not be fully executed. If the position in the application refers to the scaled cam plate. ActivationMode can also be specified when a slave is coupled for the first time.

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

b. PointID: Point ID of the first point of the motion function to be read. : MC_MotionFunctionPoint_ID. Outputs VAR_OUTPUT Done Busy Error ErrorID END_VAR : BOOL. : UDINT. ErrorID: If the error output is set. CamTableID: ID of the loaded table.37. if the data were written successfully. Execute: The command is executed with rising edge. this parameter supplies the error number . At the same time one of the outputs. : BOOL. : MC_CAM_ID. MC_WriteMotionFunctionPoint The function block MC_WriteMotionFunctionPoint can be used to write the data of a motion function interpolation point. Changing a table point via the PLC a. as soon as an error occurs. The way the change is to be implemented can also be defined. the function block is ready for a new command. END_VAR 28 6 Chapter: Camming Done: Becomes TRUE. Inputs VAR_INPUT Execute CamTableID PointID END_VAR : BOOL. Inputs/Outputs VAR_IN_OUT Point : MC_MotionFunctionPoint. When Busy becomes FALSE again. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. Overview While the Cam Table is in operation it may be necessary to adjust the location and/or properties of the points. : BOOL. Although the point before and after the current Slave position cannot be adjusted every other point can be. Error: Becomes TRUE. Done or Error. is set.

CamDataQueued can be used to check whether data has been queued (i. : MC_CamScalingMode. the position refers to the non-scaled cam plate. written but not yet activated). If activation of the data is to be delayed until the master reaches a certain position.e. If the position in the application refers to the scaled cam plate. The set mode affects all subsequent write operations. Cam plate can be modified at run time via the PLC (see MC_WriteMotionFunction. : MC_CamActivationMode. the system will initially queue the written data and activate them at the master position. Inputs VAR_INPUT Execute ActivationMode ActivationPosition MasterScalingMode SlaveScalingMode CamTableID END_VAR : BOOL. The status flag Axis. This function specifies the activation mode for modifications but does not affect a change or changeover of cam plates. MC_SetCamOnlineChangeMode The function block MC_SetCamOnlineChangeMode specifies the mode for write access to cam plate data. (MC_CamActivationMode) ActivationPosition: Optional master position at which scaling is carried out (depending on ActivationMode).Point: Data structure containing the data of a motion function interpolation point Motion Function Point: Refer to Creating a Cam Table with Function Blocks c. it can be divided by the MasterScaling before the function block is called. The function block can also be used to specify when the data is read into the cam plate. MC_WriteMotionFunctionPoint).Status. The function block MC_SetCamOnlineChangeMode is used to specify when and how these changes take effect. ActivationMode: Defines when and how scaling takes place. : MC_CAM_ID. : MC_CamScalingMode. It is therefore not necessary to call the block before each write access. If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used. : LREAL. 28 7 . Chapter: Camming Execute: The command is executed with rising edge.

Error: Becomes TRUE. At the same time one of the outputs. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed.MasterScalingMode: Type of master scaling. as soon as an error occurs. : BOOL. this parameter supplies the error number 28 8 Chapter: Camming . is set. (MC_CamScalingMode) SlaveScalingMode: Type of slave scaling. if the data were written successfully. ErrorID: If the error output is set. the function block is ready for a new command. Done: Becomes TRUE. (MC_CamScalingMode) CamTableID: Table ID. : BOOL. Outputs VAR_OUTPUT Done Busy Error ErrorID END_VAR : BOOL. Done or Error. When Busy becomes FALSE again. : UDINT.

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

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

:= := := := := := 5. PointID:=5 . 0. ErrorID=>iErrorIDChangeMode_2nd ). (*Use new Data for Point 5*) fbMC_SetCamOnlineChangeModeTable1_2nd( Execute:= TRUE . Point:=VM_MotionFunctionPoints[5] . Error=>bErrorWritePoint_2nd .FunctionType VM_MotionFunctionPoints[5]. CamTableID:=1 . Busy=> .PointIndex VM_MotionFunctionPoints[5]. Busy=> . Done=> . MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET .PointType VM_MotionFunctionPoints[5]. 1. Error=> bErrorChangeMode_2nd.MasterPos VM_MotionFunctionPoints[5]. ActivationMode:=MC_CAMACTIVATION_ATMASTERAXISPOS . 1. ActivationPosition:=730 . 29 1 Chapter: Camming .(*New data for point 5 of the Cam Table*) VM_MotionFunctionPoints[5].SlavePos (*Buffer the Data for Point 5*) fbMC_WriteMotionFunctionPoint5_2nd( Execute:=TRUE .RelIndexNextPoint VM_MotionFunctionPoints[5]. SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET . ErrorID=>iErrorIDWritePoint_2nd ). Done=> . CamTableID:=1 . 75. 15.

6). Position Tables a. 29 2 Chapter: Camming . There are no separating characters between the data.38. while the second column contains the number of columns (for table-slave tables this is always 2). The first column contains the number of lines (without header). A table consists of a header (the first line) and the table data (the remaining lines). The quantity of data is restricted to 64 KB (TwinCAT Version 2. Motion Functions vs. the table only contains data of type double. The downside of a position table is that the segments between defined points are calculated in a straight line between the points. Position Tables General Table Conventions Tables only contain binary data. 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. (This might be greater in newer versions) A position table is a 2D array that provides a slave position relative to the master position. while the second column contains the associated slave positions (both in mm). The header contains two numbers of type unsigned short. Table can be read from an ASCII file but you have to parse the file. Therefore the more points on the table the shorter the segments and the better the motion. The first column (with the exception of the header line) contains the master positions. There are no separating characters between the data. Apart from the header.

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

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

Because the motion is described in segments (sections). The user therefore does not have to update this information. subsequently corresponds INT32 to 1) REAL64 Master position REAL64 Slave position at this reference point REAL64 Slave velocity at this reference point REAL64 Slave acceleration at this reference point Slave jerk at this reference point or symmetry value of the segments REAL64 for rest in rest motion laws In this structure. such as slide point. Point structure PointIndex FunctionType PointType RelIndexNextPoint MasterPos SlavePos SlaveVelo SlaveAcc SlaveJerk/Symmetry UINT32 Point index UINT16 Function type UINT16 Point type Relative index of the end point (default: 0. In addition. referred to as IGNORE below) at a later stage. The default value of the relative point index may therefore be zero. These requirements lead a description that in addition to the starting point of a segment.c. point type). The possible point types of the cam design tool therefore includes the IGNORE point. a relative index is used to refer to the point index of the end point of this segment. symmetry value). including the point information (velocity. also contains the segment information (function type. d. acceleration. The relative point index is therefore automatically adjusted internally. The more complex point types offered by the cam design tool. 29 5 Chapter: Camming . although for a standard list with simple link the value should be ‘1’. In order to keep the definition simple for motion diagrams with simple interrelationships. for motion diagrams with simple interrelationships the end point of a section is identical to the starting point of the next segment. Definition of a Point The information contained in the cam design tool table is sufficient for defining the motion in the NC. users want to be able to deactivate individual points in a particular motion diagram (MOTIONPOINTTYPE_IGNORE. are not yet implemented. the IGNORE points are indeed ignored completely. However. closer inspection of this MF table reveals the presence of redundant data.

e. a=? At Rest the velocity and acceleration will be 0. Warning: The master position has to be either strictly monotonic rising or falling. A Turn point will have a velocity of 0. A Motion point is the default type in which the velocity and acceleration will be calculated by the Cam Table. a=0 v=0. Since no points can be added while the MF is active. and the acceleration will be calculated by the Cam Table or the user. 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). Point types MOTIONPOINTTYPE_IGNORE MOTIONPOINTTYPE_REST MOTIONPOINTTYPE_VELOCITY MOTIONPOINTTYPE_TURN MOTIONPOINTTYPE_MOTION MOTIONPOINTTYPE_REST MOTIONPOINTTYPE_VELOCITY MOTIONPOINTTYPE_TURN MOTIONPOINTTYPE_MOTION 0x0000 0x0001 0x0002 0x0004 0x0008 Ignore point Restpoint Velocitypoint Turnpoint Motionpoint Ignored point Rest point Velocity point Reversal point Movement point v=0. a=? v=?. 29 6 Chapter: Camming . a=0 v=?. Otherwise it is rejected with an associated error message. A Velocity point will have 0 acceleration and the velocity will be defined by the Cam Table or the user.

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

29 8 Chapter: Camming .b. Creating a Cam Table Right click on Tables and select Append Table… Leave the defaults and select OK.

If you then click the master in the structure tree.Right click on the Master and select Append Slave… Leave the defaults and select OK. but also of the associated slaves. It is possible here to insert additional masters. the property pages can be used to set the properties not only of the master. and to enter corresponding slaves under. 29 9 Chapter: Camming .

30 0 Chapter: Camming .

The user's interface to the cam design editor is graphic.The general procedure for developing a design of a cam is based on VDI (Verein Deutscher Ingenieure) Guideline 2143.the co-ordinate values or their derivatives . The properties of the points .the movement plan . and it is only possible to delete existing points via the graph.defines the starting and end points of the movement section. New points can only be inserted in the graph. however. The editor. they will show the same data. the co-ordinates of the points are displayed in the table window above it.can also be interactively manipulated in the table window. Following interactive graphic entry of the points in the graphic window. does not make a distinction between the movement sketch and the movement diagram containing the detailed description of the movement. The rough design of the movement . 30 1 Chapter: Camming .

The mode of the display can be changed by a right mouse click in the graphic window. but also the velocity. 30 2 Chapter: Camming . which opens the following menu: Thus a separate Graphic Window is opened for each derivative.Not just the position. acceleration and jerk can be displayed in the graphic area.

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

30 3

Chapter: Camming

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

30 4

Chapter: Camming

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

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

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

30 5

Chapter: Camming

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

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

30 6

Chapter: Camming

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

The values can be altered via the keyboard, remember that restrictions are applied arising from the choice of function type or other boundary conditions for the points. Since movement sections are normally continuous; except for Slide Points, the end point and its derivatives at the end of the section are equal to the corresponding values at the start of the following movement section. For this reason it is normally always the initial values that should be manipulated. In addition to this, if any inconsistencies are seen in the graph of a completed movement diagram, the agreement of the initial and end points should be checked. If certain values in the table cannot be changed, consideration should be given to the boundary conditions applying to the points. It may be appropriate to change them. The boundary conditions limit the scope of the functions in sections in accordance with their type. 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 7

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

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

Changing the type of spline at the first point implies that the spline type as a whole is changed, including that of the end point. 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 8

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

All these commands are only applicable to the associated window.

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

30 9

The point can then be moved on to the section using horizontal shift. . 31 0 Chapter: Camming Slide Point The starting position of the following section or the end position of the previous section is set at the cursor position.The following commands only apply in the graphic window for position: Insert Point Inserts a point at the cursor position. Delete Slide Point The slide point is deleted and the sections are joined together as they were previously. 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. Rest Point The selected point is defined as a rest point (boundary condition: v=0. Automatic Function An optimum function is selected automatically for the chosen section including adjustment to the boundary values. Velocity Point The selected point is defined as a velocity point (boundary condition: a=0). This restriction can mean that the end value of a section does not agree with the initial value for the following section. Synchronous Function The chosen section is passed through with a synchronous function. a=0). as is the corresponding section. Movement Point The selected point is defined as a movement point (no boundary conditions). without changing the selected section. Delete Point The selected point is deleted. Reversal Point The selected point is defined as a reversal point (boundary condition: v=0).

The status flag Axis. The raw table data of the cam plate are not affected. MasterOffset : LREAL. MasterScaling : LREAL := 1.0. Master and Slave offsets can also be given to provide more flexibility to the programmer.40. Overview As required by the application the scale of the Cam Table can be adjusted. SlaveScalingMode : MC_CamScalingMode. The following parameters can be modified.CamcalingPending can be used to check whether a scaling procedure is queued. Caution when scaling during motion! The slave position at the time of scaling should only be affected slightly by the change. ActivationMode : MC_CamActivationMode. Cam Table Scaling a. b. END_VAR Execute: The command is executed with a rising edge at input Execute 31 1 Chapter: Camming . SlaveOffset : LREAL. the scaling refers to an existing master/slave coupling. ActivationPosition : LREAL.Status. enabling precise scaling during the motion.0. scaling factors for master and slave. SlaveScaling : LREAL := 1. the modification will only take effect from a certain master position. and offsets for the cam plate within the coordinate system. MC_CamScaling A cam plate coupling can be scaled with the function block MC_CamScaling. Optionally. Inputs VAR_INPUT Execute : BOOL. MasterScalingMode : MC_CamScalingMode.

Error: Becomes TRUE. depending on the ActivationMode If ActivationMode MC_CAMACTIVATION_ATMASTERCAMPOS is used. Inputs/outputs VAR_IN_OUT Master : AXIS_REF. At the same time one of the outputs. as soon as an error occurs. END_VAR 31 2 Chapter: Camming . BOOL. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. ActivationPosition: Master position at which a cam plate is scaled. Slave : AXIS_REF. this parameter supplies the error number. Done or Error. if the cam plate was created successfully. the function block is ready for a new command. ErrorID: If the error output is set.ActivationMode: ActivationMode specifies the scaling time and position. END_VAR BOOL. 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. the position refers to the nonscaled cam plate. BOOL. is set. Done: becomes TRUE. it can be divided by the MasterScaling value before the function block is called. If the position in the application refers to the scaled cam plate. When Busy becomes FALSE again.

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

i.i. After the scaling the relative master position in the cam plate at 180° is therefore also 25% of the start of a cycle. Example: A cam plate has master cycle of 360° and is scaled by a factor of 2 to 720°. both for cyclic and linear cam plates. at 25% of the start of a cycle. Master-Autooffset ensures a seamless sequence of cam plates. During a switchover at the edges of a cam plate (see MC_CamActivationMode MC_CAMACTIVATION_NEXTCYCLE).e. 31 4 Chapter: Camming . Scaling takes place at the 90° position within the cam plate.

Slave-Autooffset Slave-Autooffset calculates a slave offset such that discontinuities in the slave position are avoided during cam plate switching or scaling. followed by the slave offset. the master offset is calculated first. If both Master Autooffset and Slave-Autooffset are used for cam plate switching or scaling. 31 5 Chapter: Camming . Further restrictions apply to initial coupling. The slave offset is adjusted to ensure that the slave position is identical before and after the action. Slave-Autooffset can be used with any MC_StartMode and will always adjust the cam plate such that the slave position doesn't jump.Master-Autooffset cannot be used for a cam plate with relative coupling or switching. since these functions are mutually exclusive. These are shown in the following table.

ActivationMode:=MC_CAMACTIVATION_NEXTCYCLE . ActivationPosition:=721 .5. Slave:=Slave). MasterScaling:= 0. SlaveScaling:=1 . Sample Code: IF VM. SlaveScalingMode:=MC_CAMSCALING_AUTOOFFSET . SlaveOffset:=0 .ActPos > 540 THEN fbMC_CamScaling( Execute:=TRUE . END_IF 31 6 Chapter: Camming .ii.NcToPlc. MasterOffset:=0 . MasterScalingMode:=MC_CAMSCALING_AUTOOFFSET .

Only the configuration needs to be correct to implement this type of Cam Table. 31 7 Chapter: Camming . 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. Cyclic Cam Plates with Lift Please refer to MC_CamIn Appendix in the Information System or at the end of this document.41. Calculations for the Lift are handled internally.

The Master Axis must be set for Rotation. 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. The StartMode of the MC_CamIn FB must be set properly. 31 8 Chapter: Camming .

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. 31 9 Chapter: Camming .a. Note: The modes MC_STARTMODE_RELATIVE and MC_STARTMODE_MASTERREL_SLAVEABS cannot be used in conjunction with automatic master offset calculation (MC_CamScalingMode). With StartMode absolute the cam plate coordinate system is congruent with the axis coordinate system and can be moved through an offset. (* cam table is absolute for master and relative for slave *) MC_STARTMODE_MASTERREL_SLAVEABS (* cam table is relative for master and absolute for slave *) ). MC_StartMode TYPE MC_StartMode : ( MC_STARTMODE_ABSOLUTE := 1. since this would cause a conflict. The mode can be specified as absolute or relative separately for both coordinate axes. (* cam table is relative for master and slave *) MC_STARTMODE_MASTERABS_SLAVEREL. (* cam table is absolute for master and slave *) MC_STARTMODE_RELATIVE. if required (master or slave offset). The cam plate can additionally be moved through an 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.

32 0 Chapter: Camming .As can be seen below. The Red line is the Modulo position of the Master Axis. 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 Green line is the Absolute position of the Slave Axis.

32 1 Chapter: Camming . In the below Scope the Green horizontal line shows the Slave axis not moving because it was decoupled from the Master for 3 revolutions.42. To couple the axis back to the Master via the Cam Table simply call the MC_CamIn FB again. Overview MC_CamOut is used to decouple the Slave axis from the Master axis. 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. and then coupled again. Cam Out and Restarting a. The slave axis must be stopped after it is decoupled.

is set. Done: Becomes TRUE. Inputs/Outputs VAR_IN_OUT Slave END_VAR : AXIS_REF. it is not automatically stopped. BOOL. : ST_CamOutOptions. BOOL. Among other parameters it contains the current axis status. as soon as an error occurs. ErrorID: If the error output is set. At the same time one of the outputs. Error: Becomes TRUE.b. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. Options: Currently not implemented Outputs VAR_OUTPUT Done : Busy : Error : ErrorID : UDINT. velocity or error status. Slave: Slave axis data structure. the function block is ready for a new command. Inputs VAR_INPUT Execute Options END_VAR : BOOL. The axis data structure of type AXIS_REF addresses an axis uniquely within the system. if the axis was successfully uncoupled. Done or Error. but reaches a continuous velocity with which it will continue to travel endlessly. MC_CamOut The function block MC_CamOut deactivates a master-slave coupling. The axis can be stopped with a Stop command. When Busy becomes FALSE again. END_VAR BOOL. Note: If a slave axis is uncoupled during the movement. (*Not Yet Implemented*) Execute: The command is executed with a rising edge at input Execute. including position. 32 2 Chapter: Camming . this parameter supplies the error number.

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

CommandAborted: Becomes TRUE. if the axis was stopped and has come to a standstill. if the command could not be fully executed. including position. Busy: The Busy output becomes TRUE when the command is started with Execute and remains TRUE as long as the command is processed. velocity or error status. : BOOL. : BOOL. Axis: Axis data structure The axis data structure of type AXIS_REF addresses an axis uniquely within the system. CommandAborted or Error.Outputs VAR_OUTPUT Done Busy Active CommandAborted Error ErrorID END_VAR : BOOL. : UDINT. it becomes active once a running command is completed. When Busy becomes FALSE again. Done. Among other parameters it contains the current axis status. this parameter supplies the error number. : BOOL. ErrorID: If the error output is set. Active: Active indicates that the command is executed If the command was queued. At the same time one of the outputs. the function block is ready for a new command. Error: Becomes TRUE if an error occurs. : BOOL. Done: The Done output becomes TRUE. Inputs/outputs VAR_IN_OUT Axis END_VAR : AXIS_REF. The running command may have been followed by a Move command. 32 4 Chapter: Camming . is set.

32 5 Chapter: Camming . Note that prior to the coupling the slave axis has to be at a position defined by the cam plate. The slave axis is therefore not slowly synchronized with the cam plate. The following figures illustrate the procedure. Axis coupling with cam plates The function block MC_CamIn can be used to establish a cam plate coupling (or table coupling) between a master axis and a slave axis. In practice the question arises.43. The slave therefore stops at the table edges as soon as the master leaves the defined range. what position the slave should be in prior to the coupling. but it will jump if it is not already at the table position. MC_CamIn Appendix TwinCAT PLC Library: MC (Version 2) a. Notes: For all subsequent calculations only axis set positions are used. since they would lead to calculation errors. and how this is calculated. the slave position is calculated directly from the cam plate. The actual positions are not used in the calculations. The diagram shows that the absolute axis coordinate system (blue) does not have to be identical to the cam plate coordinate system (red). Linear cam plates A linear cam plate is only defined via a limited master position range. Outside this range the slave position is defined by the first or last table position. After the coupling and once the master has been started. the coupling position of the master or slave axis is considered in the calculations as an additional offset. particularly with cyclic cam plates. For relative couplings. Only absolute table couplings are considered. Scaling is also possible. The cam plate coordinate system may be offset by a master offset or a slave offset. b.

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

For these cam plate types. Cyclic cam plates without lift A cyclic cam plate without lift is characterized by the fact that the slave start and end positions in the table are identical. master/slave coupling requires the same preparation as for a linear cam plate. It is not necessary to use the modulo position of the master for the calculation.c. 32 7 Chapter: Camming . The slave therefore moves cyclically within a defined range. without changing its position permanently in a particular direction. since the absolute position is already correctly taken into account via the coupling command. The starting position of the slave can therefore be calculated as described above.

the motion continues steadily.d. Cyclic cam plates with lift The lift of a cyclic cam plate is the difference between the last and the first table position of the slave. With each new cycle. the lift is therefore added as an additional internal slave offset or subtracted if the motion is reversed. The slave position does not jump back to the initial table value. Such a cam plate is continued cyclically at the end of the table. Instead. 32 8 Chapter: Camming .

e. The Autooffset function can simplify the calculation of offsets. SlaveCamTablePosition := ReadSlaveDynamics. The result is converted to an absolute slave position with slave offset and scaling. MasterCamTablePos := (MasterPosition + MasterOffset) / MasterScaling. without added lifting distances. If necessary. the number of pending lifts must be calculated and added to the slave position. NewSlaveOffset := SlaveOffset + (SlaveHub * lift number). SlavePosition := (SlaveCamTablePosition * SlaveScaling) + NewSlaveOffset. this behavior has to be taken into account and compensated by re-calculating the slave offset. the slave position returns to the basic cycle. i. Uncoupling and re-coupling for cyclic cam plates with lift If a slave is coupled to a cam plate with lift. SlaveHub ). the coupling is always done in the basic cycle (red coordinate system). Lift number := MODTURNS( (SlavePosition . if necessary. Chapter: Camming 32 9 .e.SlavePosition. The master table position is used as input parameter for the function block MC_ReadCamTableSlaveDynamics. If the slave is uncoupled after a few cycles and then recoupled. In addition.SlaveOffset). particularly for switching of cam plates.

this document will not suffice if your problem is within your . These errors indicate that something is fundamentally wrong with your system. it can be anything from a corrupted file to forgetting to start the PLC. The most significant byte 0xn000 can be considered as the grouping for the errors.NET or other 3rd party application. The errors range from 0x0000 to 0xFFFF. The error codes provided by the system. The added descriptions are only relevant for helping to find a problem within TwinCAT. b.44. Overview The following covers the error codes as provided by either the function blocks or the TwinCAT System Manager. Error Format The error codes within TwinCAT are given in accordance with the following structure. The cause of the errors can vary greatly. that doesn’t mean that that’s what you wanted to do. 33 0 Chapter: Camming . The explanations of the error codes provided are based solely on the experience of my self and others. or an incorrect linking in the system manager. Remember that just because TwinCAT allows you to do something. Diagnostics a. although complete. The remaining bytes are used to give the exact error code. When needed a sub subgroup will be identified by the second byte 0x0n00. The errors between 0x0000 and 0x0FFF refer to the TwinCAT System itself. All errors are generated in hexadecimal. are sometimes not easily understood by new users.

Error Groups Offset 0x0000 0x0500 0x0600 0x0700 0x0800 0x1000 0x1900 0x2000 0x3000 0x4000 0x6000 0x7000 0x7800 Description ERR_GLOBAL ERR_ROUTERERRS ERR_TASKERRS ERR_ADSERRS ERR_SYSSMPLERRS ERR_RTIMEERRS ERR_TRACEERRS ERR_IOERRS ERR_SPSERRS ERR_NCERRS ERR_PLCERRS ERR_STRKERRS ERR_PRJSPECIFIC Global Error Codes 0x0000 0x6 0x7 target port not found target machine not found These errors commonly occur when setting up a system for the first time. and machine. simulation. If all communication is local. If you are unsure of what system manager file is running. and that the correct PLC program is loading and running. It could be an incorrect or missing link in the system manager or the PLC code that is calling the ADS service has an invalid parameter. If communication is remote then check the AMS router on both PCs to make sure the info is valid. These normally occur because of something not being configured correctly. the red folder in the system manager will ‘Open from Target’. Ping the IP of address of one PC from the other to make sure cabling and network configuration is correct. This error is trying to tell you that there is a communication problem. and is commonly an ADS communication problem. then make sure TwinCAT is running the correct System Manager file. General ADS Error Codes 0x0700 The common errors in this group are fairly self-explanatory. 33 1 Chapter: Camming . and the frequency increases when switching between development.

"Table identifier not allowed" Either an unacceptable value (not 1. from Overtemp errors to syntax errors in G-Code to bad PLC commands.. These sub groups cover all things motion.NC Errors 0x4000 The NC error group is comprised of 9 sub-groups. If the Ready Status of the Axis is not TRUE and the axis receives a command then this error will be given. The ‘R’ button on the right side of the ErrorID display will issue an IDN99 reset command to the drive. Chapter: Camming 33 2 .. from For an AX5000 the first place to check is on the ‘Configuration’ Tab of the axis. A value less than 13 or an F value will prevent the axis being ready. This value is held in the NCDRIVESTRUCT_IN2 of the Axis 1_Drive and is linked to the ‘Drive Status Word’ of the drive under the I/O Configuration. it must be at D013: Axis Op. Look at the ErrorID. NC Error Sub Groups 0x40nn 0x41nn 0x42nn 0x43nn 0x44nn 0x45nn 0x46nn 0x4Ann 0x4Bnn General NC Errors Channel Errors Group Errors Axis Errors Encoder Errors Controller Errors Drive Errors Table Errors NC-PLC Errors General NC Errors 0x40nn 0x4016 used. Check your value of your TableID 0x4052 for "Axis not ready for operation" The axis is not complete.255) has been or a table that does not exist in the system has been named. and is therefore not ready operation. This is usually a consequence of problems at system start-up.

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

NC-PLC Errors TwinCAT NC I TcMcCam TcNc TcRemoteSync TcMC2 0x4B00.. This can also happen for a Cam Table generated by the PLC when the position would require the Master Axis to move backwards..0x4B2F 0x4B30... 0x4A06 "Table is not monotonic" The value for the step size is not allowed.Table Errors 0x4Ann These Errors relate to the parameterization and initialization of a cam table. The majority of these errors are for incorrect (out of range) parameters or invalid cam table data. The Flying Saw function blocks will generate these errors as well as Cam Table function blocks. PLC Errors 0x4Bnn The majority of these errors are well described within the Information System..0x4B4F 0x4B50. 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.0x4B0F 0x4B10. it is less than or equal to zero.0x4B7F 33 4 Chapter: Camming .0x4B5F 0x4B60.. because.0x4B3F 0x4B40. When generating a Cam Table from the PLC or from the Flying Saw this error can happen. for example..0x4B6F TcPlcInterpolation 0x4B70.

VIII. Remote Connections 45. Embedded Controllers  The TwinCAT AMS Router allows for TwinCAT to communicate between computers    Configuring your local IP address Establishing a Route to the Target Opening the active system manager of the Target Chapter: Remote Connections 33 5 .

 Right-Click on the Network Card and select “Properties” Chapter: Remote Connections 33 6 . If the other cards are connected TwinCAT may try to one of scan these networks for devices and not scan the correct network.   Click “Start” Expand “Connect To” Click “Show all connections”   The network card you are going to use should be the only one with a Status of “Connected”.

   Scroll to the bottom of the list. Select “Internet Protocol (TCP/IP)” Click on “Properties” 33 7 Chapter: Remote Connections .

0.168.2 Enter your Subnet mask Click “OK” 33 8 Chapter: Remote Connections . 192.    Select “Use the following IP address” Enter the following IP address.

 Click “OK” 33 9 Chapter: Remote Connections .

and select System Manager. 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. If the below window appears click on “STOP Installation”. 34 0 Chapter: Remote Connections .  Click on the TwinCAT icon in the Windows System Tray. but it is not needed for connecting to remote devices.

 Click “Ok” 34 1 Chapter: Remote Connections . then New  Set/Reset TwinCAT to Config mode. Open a new System Manger file. Select File.

then “Choose Target”  Click “Search (Ethernet)” 34 2 Chapter: Remote Connections . Select “SYSTEM – Configuration”.

Click “Enter Host Name / IP:” It is also possible to use the ‘Broadcast Search’ button to look for computers on the local network that are running TwinCAT.   If you know the IP address of the remote device it can be entered. if a static IP address is being used then set ‘Address Info’ to ‘IP Address’ . however a broadcast search will not go through a network router.  Select the computer form the list and select ‘Add Route’ 34 3 Chapter: Remote Connections  If the computer you are connecting to is using DHCP then the ‘Address info’ should be set to ‘Host Name’.

Click on “Close”.   Enter User name and password of an Administrator account on the Target PC Not required for Windows CE Click “OK”  Verify the “X” appears in the “Connected” column. 34 4 Chapter: Remote Connections .

 Select “BasePLC” Click “OK” 34 5 Chapter: Remote Connections .

Click on the red folder to “Open from Target”    If the below window appears click on “Yes” 34 6 Chapter: Remote Connections . 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. Verify connection to “BasePLC” the red background indicates you are connected to a remote device. A yellow background indicates a Timeout.

   File name of the System Manager *.tsm file Name of remote device List of hardware connected to the device 34 7 Chapter: Remote Connections .

unless the customer has specified other guidelines for the project.IX. Appendix I – Variable Naming Convention 46. 34 8 Chapter: Appendix I – Variable Naming Convention . The programmer can judge the extent to which the guidelines can be applied to existing programs. Scope The following programming guidelines support the creation and maintenance of consistent programs with the following goals:    Improve readability Speed development Facilitate the incorporation of third-party software components These guidelines are based on a history of experience in software development by Beckhoff and our customers. The programming guidelines must be used for the development of new programs.

Programming System Settings The TwinCat project options must be defined uniformly to achieve identical notation for individual editors and for documentation. 34 9 Chapter: Appendix I – Variable Naming Convention . This can be adjusted under "Project -> Options -> Editor". Font A non-proportional font is recommended with the following settings: This can be adjusted under "Project -> Options -> Editor -> Font".     Font: Tahoma Font style: Regular Size: 12 Character set: Western b. This is especially true in multi-user projects. a. Tab Width A tab width of 4 is recommended.47.

48. Case Sensitivity Pay close attention to case sensitivity. especially for prefixes. Names should contain the following letters. The underscore should not be used otherwise... The first letter of each word in the designator is capitalized (example: FileSize). and program organization units (POU). a. Choose a relevant. and type as will be explained below. Prefixes are included with the designator name to indicate scope. The syntax is explained in the respective prefix section. b. A.9. to improve readability. 35 0 Chapter: Appendix I – Variable Naming Convention c... description for each designator name and the designator should be self-explanatory.. Valid Characters . the individual words are put together with an underscore as a separator to increase readability. numbers. and special characters only:    0. The underscore is used to display prefixes more clearly. Please limit the name to 20 characters.z Underscore Designators always begin with a letter. NOTE: The TwinCat IEC compiler is not case sensitive. General This naming convention applies to variables. the fewer the better. short. Because data type designators are usually formed from capital letters. Naming a. constants. property.Z..

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

   

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

The general syntax for variables and constants is as follows:

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

   

g_diFirstUserFault xEnable c_iNumberOfAxes gc_sMyGlobalStringConstant

The general syntax for POU’s is as follows: Chapter: Appendix I – Variable Naming Convention

[POU] _ [Name]

   

FB_AxisController FB_HeatGun P_Main F_GetLeftString

35 1

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

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

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

gc_diMaxEvents : DINT := 100; END_VAR

(* Maximum Quantity of Events *)

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

Scope Prefix No prefix g_ gc_


Use Local variable Global variable Global constant

Example xEnable g_xRunning gc_iCurrentRecipe

Table 3.5 Scope Prefix

35 2

Chapter: Appendix I – Variable Naming Convention

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

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


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

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

35 3

Type Prefix st fb


Use (Bytes) Structure Function Block

Example stRecipe fbTrigger

Table 3.6 Standard Date Type Prefixes

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

35 4

Chapter: Appendix I – Variable Naming Convention

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

Property Prefix c_ r_


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

Example c_xName r_xName

p_ i_ q_ iq_


p_diName i_xEnable q_xError iq_stParameters

ati_ AT %IW AT %ID AT %QX AT %QB atq_ AT %QW AT %QD AT %MX AT %MB atm_ AT %MW AT %MD

Direct access to input memory


Direct access to output memory


Direct access to memory location


35 5

Chapter: Appendix I – Variable Naming Convention

Table 3.7 Property Prefix

NOTE: Do not declare constants as RETAIN or PERSISTENT.

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

 

atm_rMyVar1 atm_rMyVar2


35 6

Chapter: Appendix I – Variable Naming Convention

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

   

Function Function block Program Action

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

POU Prefix P_ FB_ F_ A_


Use Program Function block declaration Functions Action

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

Table 3.8 POU Prefix

35 7

: MC_Direction := MC_Positive_Direction. Structures The name of each structure data type consists of a prefix ST_ and a short.i. TYPE ST_FEED_PARAMETERS : (* Parameters for MC_MoveVelocity FB *) STRUCT lrVel lrAcc lrDecel lrJerk eDirection lrStopPos END_STRUCT END_TYPE : LREAL := 100.0. they are separated by an underscore. meaningful description in upper case (e.0. ST_STATION_NUMBER).g.0. : LREAL := 2000. Each component of the structure must be identified with a type prefix.0. 35 8 Chapter: Appendix I – Variable Naming Convention . : LREAL := 10000. : LREAL := 2000. Declaration example:  stAxis1Feed : ST_FEED_PARAMETERS. : LREAL := 0. If several words have been put together.0.

E_EVENT_FAULT_ACK := 3. If several words have been put together. E_EVENT_FAULT_RESET := 2. E_EVENT_USER_1 := 10 ).g. 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 Convention  eMyEvent : ET_EVENT_TYPES. NOTE: 2 bytes of memory are reserved for each list variable. TYPE ET_EVENT_TYPES : ( E_EVENT_NO_EVENT := 0. they are separated by an underscore. List Types The name of a list type consists of a prefix ET_ and a short. ET_WORKING_DAY). The individual elements of list types are identified with the prefix E_. meaningful description in upper case (e. 35 9 . E_EVENT_FAULT_ACTIVE := 1.j.

Libraries Designators contained within a library and the library name itself is prefixed with a code to quickly identify the source and to match the designator with the library.lib 36 0 Chapter: Appendix I – Variable Naming Convention .k.   MyLib_gc_diMaxConvCount MyLib_ConveyorControl.

If all POUs and variables have meaningful names. 0. It is more important to keep code clear and understandable. If variables have been given unusual values. Write your comments so that they are not only notes for the programmer but can also be understood by third parties. is either not used or used as a default.   iCurrentRecipe astRecipes : INT.49. However. each individual line of code does not need to be commented. Good Programming Practices a. comments can be shorter. however.. This minimizes the amount of comments required. 36 1 Chapter: . Program Calls Parenthesis should be used when calling programs and actions as shown below:  P_SearchData().. This typically occurs when the variable used to index an array is not initialized properly as shown below.10] OF ST_RECIPE. Comments Comments are essential for understanding source code. Limit your comments to the necessary minimum. The first element of the array. for example. b. even the programmer will have trouble understanding it after a short time. The problem is corrected as follows:  astRecipes : ARRAY[0. Array Indexing Array should always be index starting at zero to prevent range errors. : ARRAY[1. it is extremely important to explain the reason for this to prevent future misunderstandings. if the code is difficult to understand and there are no comments. c.10] OF ST_RECIPE.

and the – will be used for the NOT symbol. the second one is A AND NOT B. 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 Exclusive OR (XOR) function only provides a TRUE output if there are an odd number of TRUE inputs. The other conditions result in Z being false. First look at the ‘Truth Table’ for the 2 PE conveyor. The Boolean equation for this would be as follows MotorStarter = EntryPE AND NOT ExitPE As another Example consider an XOR function. 36 2 Chapter: II. is when the EntryPE is TRUE and the ExitPE is false. The ‘Truth Table’ is below: Appendix II – Truth Tables and Boolean Algebra To find the Boolean equation for this table we look at the conditions that result in ‘Z’ being TRUE. the v will be used for the OR symbol. We then OR these two conditions together . The first one is NOT A AND B. In this table the only situation where the Motor Starter is true.II. Appendix II – Truth Tables and Boolean Algebra By using Boolean algebra we can see how the Truth Table can be converted into code.

Z = ( -A ^ B ^ -C ) v ( A ^ -B ^ -C ) v ( A ^ B ^ -C ) Z = -C ^ [( -A ^ B ) v ( A ^ B ) v ( A ^ -B )] 36 3 Chapter: II. however the purpose of this example is to be efficient.C. . so we will reduce the equation as far as possible.Z = ( 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. 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 ^ -C If 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.

36 4 Chapter: II. Appendix II – Truth Tables and Boolean Algebra .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.

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 00000 Notice there is only one sample within a group that is incorrect. 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. many times the bottom line would represent the input and the desired output would be the top line. Appendix III – De-bouncing an Input The 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. 36 5 . However. Imagine the input sample looks like the following 00000 11111 00000 11111 00000 11111 00000 11111 00000 11111 00000 This input has no issues. just sit back and look and the two groups. 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. you can see the first half of the bottom one is not as clean as the top one. The below code will filter out this incorrect value.X. 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.

Else if the integrator is less than samples then increase the integrator by 1. When the input changes the output will be delayed by the PLC scans. Once the integrator has reached a value equal to samples then the output will be changed. but this is the tradeoff that must be made for de-bouncing an input. . Else if the integrator is less than or equal to samples then the output will be equal to 1. Lines 10-15 If the integrator is 0 then the output is 0.Lines 1-7 If the input is 0 and the integrator is greater than 0 then decrease the integrator by 1. Line 14 is to ensure that the integrator never increases to far. 36 6 Chapter: Appendix III – De-bouncing an Input The integrator will count up or down as the value of the input changes.

notice that in the first half of the Real Input the value was never True 3 times in a row. A few more examples Real Input Normal Output De-bounced Output 0000 0000 0000 Real Input Normal Output De-bounced Output 0010 0010 0000 Real Input Normal Output De-bounced Output 0111 0111 0001 Chapter: Appendix III – De-bouncing an Input Real Input Normal Output De-bounced Output 1111 1111 0011 Real Input Normal Output De-bounced Output 1110 1110 0011 36 7 . therefore the De-Bounced output never changed to True.Real Input Normal Output 01000 11011 00100 11011 00100 11111 00000 11111 00000 11111 00000 01000 11011 00100 11011 00100 11111 00000 11111 00000 11111 00000 De-bounced Output 00000 00000 00000 00000 00000 00111 11000 00111 11000 00111 11000 First. 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.

Appendix IV – Quick Start Overview Connecting 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.XI. 36 8 Chapter: Appendix IV – Quick Start . Click the TwinCAT icon in your system tray. Open TwinCAT System Manager.

Put TwinCAT in Config Mode by clicking blue TwinCAT icon on the toolbar in the System Manager. Click Ok. Click File -> New 36 9 Chapter: Appendix IV – Quick Start . Look in the lower right corner of your System Manager and make sure you see the blue Config Mode symbol.

Check the box for the EtherCAT device and unselect all other boxes and click OK. Click Yes 37 0 Chapter: Appendix IV – Quick Start .Right click IO devices and click Scan Devices.

37 1 Chapter: Appendix IV – Quick Start .Click Yes The tree will now give a representation of your hardware network.

Click the TwinCAT icon in your system tray. Open TwinCAT PLC Control. 37 2 Chapter: Appendix IV – Quick Start .

bIn should be addressed at %I*. This will allow us to link to a digital input terminal. Make sure all fields are filled out. in the code editing window. 37 3 Chapter: Appendix IV – Quick Start .Type bOut := bIn. Addressing the variable at %Q* allows us to later link the variable to a piece of hardware (Digital output terminal). Press Enter.

highlight the variable and press Shift + F2. Your PLC project should look like what’s pictured below. 37 4 Chapter: Appendix IV – Quick Start .NOTE: To manually bring up the Declare Variable dialog box.

Compile Code. 37 5 Chapter: Appendix IV – Quick Start . Save the Project Do ANOTHER Rebuild all. Make sure you have no errors.

tpy file and open. Open the System Manager we previously configured. If you get errors in your PLC then a . NOTE: If you do not see the .tpy file go back to your PLC project and do another file Save and Project Rebuild All. Confirm there is a file named the same as your PLC with a tpy file extension. 37 6 Chapter: Appendix IV – Quick Start .tpy will not be generated. Right Click on PLC – Configuration and click Append PLC Project.Navigate to where you saved the PLC project. Then locate the .

tpy file and you will see the variables that you created in your PLC Project. 37 7 Chapter: Appendix IV – Quick Start . Select the digital input terminal you want the variable connected to. Click OK.Expand your . select Variable tab and click the Linked to… button. Highlight bIn Variable.

37 8 Chapter: Appendix IV – Quick Start . Click OK. Select the digital output terminal you want the variable connected to.Highlight bOut Variable. select Variable tab and click the Linked to… button.

37 9 Chapter: Appendix IV – Quick Start . It will bring you to the IO terminal that this variable is linked to.Note: You can easily see where the variable is linked to by right clicking on the variable and selecting Goto Link Variable.

In the System Manager click the Activate configuration icon on the toolbar . 38 0 Chapter: Appendix IV – Quick Start .Note: 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. Follow steps 1-3.

Follow steps 1-3. Go back to your saved TwinCAT PLC Control. 38 1 Chapter: Appendix IV – Quick Start .Verify that TwinCAT has gone into Run Mode by looking in the lower right corner of your System Manager.

You are now online with the PLC and running. 38 2 Chapter: Appendix IV – Quick Start . In your PLC you should see the state of bIn and bOut change to true. Apply 24 VDC to the input terminal you linked bIn to and the digital output will come on.The PLC project should now look like what is below.

113. 227. 122. 63. 257. 269. 207. 77. 5. 28. 356 P PLC 3. 70. 105. 298. 75. 10. 161. 13. 38 3 Chapter: Appendix IV – Quick Start . 263. 341. 344. 40. 12. 345. 13. 161. 160. 56. 295. 202. 256. 80. 102. 183. 290. 231. 67. 138. 61. 79. 11. 12. 364. 75. 217. 371 257. 153. 68. 273. 279. 362. 77 Instruction List 370 SFC 9. 10. 286. 258. 270. 63. 83.Index A Actions AMS Array 25. 4. 219. 47. 229. 14. 27. 340. 136. 54. 186. 151. 11. 113. 338. 86. 9. 46. 151. 18. 61 18. 115. 203. 255. 86. 226. 333. 139. 238. 241. 330. 277. 7. 268. 8. 153 S I IL 9. 228. 26. 77. 269. 21. 208. 121. 116. 339.265. 213. 8. 109. 298. 274. 43. 158. 42. 44. 64. 242. 29. 367. 77. 55. 248. 225. 10. 301. 56. 10. 81. 54. 193. 264. 276. 331. 85. 201. 248. 104. 65. 39. 185. 76. 72. 155. 233. 60. 289. 371 L LD 9. 146. 18. 67. 104. 279. 126. 35. 55. 224. 108. 15. 334. 162. 23. 216. 35. 256. 340. 350. 277. 343. 154. 23. 57. 220. 148. 107. 190. 16. 353. 7. 58. 45. 344 F FBD 9. 368. 19. 220. 344 101. 189. 339. 77. 76. 116 ST 9. 112. 109. 17. 333. 57. 82. 9. 47. 171. 340. 55. 21. 78 T TwinCAT 1. 107. 351. 104. 364. 112. 26. 94 17. 82. 121. 282. 60. 267. 343 Priorities 32 R Registration Remote 20. 74. 206.