Notes on the documentation

This description is only intended for the use of trained specialists in control and automation engineering who are familiar with the applicable national standards.
It is essential that the following notes and explanations are followed when installing and commissioning these components.

The responsible staff must ensure that the application or use of the products described satisfy all the requirements for safety, including all the relevant laws, regulations, guidelines and standards.

Disclaimer

The documentation has been prepared with care. The products described are, however, constantly under development.
For that reason the documentation is not in every case checked for consistency with performance data, standards or other characteristics.
In the event that it contains technical or editorial errors, we retain the right to make alterations at any time and without warning.
No claims for the modification of products that have already been supplied may be made on the basis of the data, diagrams and descriptions in this documentation.

Trademarks

Beckhoff®, TwinCAT®, EtherCAT®, Safety over EtherCAT®, TwinSAFE® and XFC® are registered trademarks of and licensed by Beckhoff Automation GmbH.
Other designations used in this publication may be trademarks whose use by third parties for their own purposes could violate the rights of the owners.

Patent Pending

The TwinCAT Technology is covered, including but not limited to the following patent applications and patents:
EP0851348, US6167425 with corresponding applications or registrations in various other countries.

Copyright

© Beckhoff Automation GmbH & Co. KG, Germany.
The reproduction, distribution and utilization of this document as well as the communication of its contents to others without express authorization are prohibited.
Offenders will be held liable for the payment of damages. All rights reserved in the event of the grant of a patent, utility model or design.


Overview

The TwinCAT PLC library COMlibV2 supplies function blocks and data structures for serial data communication. The library supports the serial Beckhoff KL6xxx bus terminals, EL60xx EtherCAT terminals, the standard PC COMx interfaces and virtual COM ports.

The library offers blocks for the following functions:

  • Sending and receiving byte by byte
  • Sending and receiving strings
  • Sending and receiving transparent data
  • Configuration of the KL6xxx serial bus terminals (baud rate, handshake etc.)
  • Operation of the KL6xxx serial bus terminals
  • Operation of the EL60xx EtherCAT terminals

All blocks support multiple instances, so that, depending on the processing capacity of the PC, any number of serial interfaces can be operated in parallel.

Note: The pre-product of the TwinCAT PLC library COMlibV2 was the TwinCAT PLC library COMlib.

System requirements for usage with virtual COM ports

with installation >= v2.2.4 available

The installation of the TwinCAT PLC Serial Communication product gives the optional possibility to install an Ads server. This is only needed if virtual COM ports should be used. Otherwise the server should not be installed.

Special system requirements for the usage of the PLC library with virtual COM ports in windows:

  • Programming environment:
    • XP, XPe, WES, Win7, WES7
    • TwinCAT installation level: TwinCAT PLC or higher
    • TwinCAT system version 2.11 Build 1544 or higher
    • COMlibV2.lib This PLC library must be integrated in the PLC project.
      (The libraries Standard.lib; TcBase.lib; TcSystem.lib are integrated automatically.)
      Note: Up to version < v2.3.0 of the library COMlibV2.lib only the library Standard.lib was necessary. Now you have to ensure that all three libraries are available !
  • Target platform:
    • PC or CX (x86, x64): XP, XPe, WES, Win7, WES7, CE 6.0
    • TwinCAT runtime system version 2.10 Build 1340 or higher
  • Installation:
    • The product installation gives the optional possibility to install the TcAdsSerialCommServer.
    • The Ads server has to be installed on the system where the virtual COM port is located.
    • If you have CE version, please do the following steps:
      • Install the product on your programming PC.
      • The folder ...\TwinCAT\CE\TcPLCSerialComm\ contains a Cabinet-File for the CE runtime system
      • Copy the Cabinet-File in a folder of the CE runtime system.
      • On CE system: Install (double click to Cabinet-File) CE components to '\Hard Disk\System'.
      • Please reboot/suspend the CE device once after installation. The TcAdsSerialCommServer starts automatically with CE operating system. (If the server don't start automatically, please check the version of the "StartUp.exe". Version 1.0.0.47 or later is necessary for the automatic start. )

Documentation last updated: 11.04.2012


Supported Hardware

Serial Bus Terminal

KL6xxx in 3-Byte Mode

The standard version, as supplied, of the Beckhoff serial bus terminal is operated in 3-byte mode. In other words, a bus telegram can transmit or receive 3 data bytes to or from the terminal. Since every data exchange between the PLC and the bus terminal requires 3 PLC cycles, the effective transfer rate is one byte per cycle.

The maximum effective data transfer rate in bits per second (Bps) depends on the cycle time, T, of the PLC, and on the number of useful bits in each data byte transferred, LB:

Bps = LB / T

LB = 1 start bit n data bits p parity bits m stop bits

The maximum effective data transmission rate is limited by the physical baud rate programmed into the terminal.

Note: Pay attention to the K-Bus update time if bus terminals KL6xxx and bus couplers BKxxxx are used (Task Configuration).

KL6xxx in 5-Byte Mode

The serial bus terminal can be reprogrammed offline by means of a configuration program (Beckhoff KS2000), so that, in 5-byte mode, 5 data bytes at a time can be transferred to or from the terminal. 3 PLC cycles are still necessary for each exchange. The effective data rate for a given cycle time is thus 5/3 greater than in 3-byte mode.

Bps = (LB * 5/3) / T

The bus terminals cannot be re-programmed while the PLC is running, since the 3-byte and 5-byte modes differ in the register mapping and in the TwinCAT System Manager configuration. For this reason, the required re-programming means that 5-byte operation is only recommended for time-critical applications.

Note: Pay attention to the K-Bus update time if bus terminals KL6xxx and bus couplers BKxxxx are used (Task Configuration).

KL6xxx in 22-Byte Mode

The serial bus terminal can be reprogrammed offline by means of a configuration program (Beckhoff KS2000), so that, in 22-byte mode, 22 data bytes at a time can be transferred to or from the terminal. 3 PLC cycles are still necessary for each exchange. The effective data rate for a given cycle time is thus 22/3 greater than in 3-byte mode.

Bps = (LB * 22/3) / T

Note: Pay attention to the K-Bus update time if bus terminals KL6xxx and bus couplers BKxxxx are used (Task Configuration).

Serial EtherCAT Terminal

EL60xx in 22-Byte Mode

The serial EtherCAT terminal is operated in 22-byte mode, so that 22 data bytes at a time can be transferred to or from the terminal. 3 PLC cycles are still necessary for each exchange.

Bps = (LB * 22/3) / T

Terminals' parameterization will be conducted by the CoE-Online tab in the TwinCAT System Manager (double-click on the referring object).

Serial PC Interface

The serial PC interface (COM1, COM2 etc.) is handled by the TwinCAT system similarly to the serial bus terminal, but use larger data transfer buffers than the serial bus terminal. The library uses a 64 byte buffer, so up to 64 data bytes are transferred at once between the PLC and the interface driver. 3 PLC cycles are again needed for the exchange of a data block with the serial PC interface.

Bps = (LB * 64/3) / T

Virtual Serial COM Port

A virtual serial COM port (COM1, ..., COM255) which is available in Windows is also supported by the TwinCAT system. No configuration in the TwinCAT System Manager is needed.
The parameterization is done directly in the PLC with the given function blocks.

The communication interface is not real-time capable.

Communication baud rates are available from 150 baud up to 115200 baud.

Note: The product is devoloped for applications with one virtual COM port per target system. The usage of more than one virtual COM port is with function test generally possible.


Communication Principle

Background Communication

As described in the section on Supported Hardware, the maximum effective data transfer rate depends in part on the PLC cycle time. So, for example, for communication with the serial bus terminal at an effective rate of 9600 bps, a cycle time of 1 ms is required. In many larger applications such a short cycle time for the whole PLC would heavily load the control computer.

Since for most applications longer cycle times of, for instance, 10 ms are more than adequate, it is possible with the aid of this library to decouple the data traffic between the PLC and the hardware from the rest of the PLC application. Two tasks are created in the PLC program for this purpose. The standard task runs with the conveniently long PLC cycle time of, for example, 10 ms, while a second communication task runs with a faster cycle taking, for example, 2 ms.

Data buffers of type ComBuffer are used to decouple the different speeds of the fast communication task and the standard task. They are written and read asynchronously.

The function blocks described later for receiving and sending data (SendByte, SendString, SendData etc.) make use of only an additional data buffer for data exchange, and are thus independent of the hardware being used. In all cases, a communication block SerialLineControl is called in the fast task, as well as the send and receive blocks. This handles the data traffic between the data buffer and the hardware with maximum speed in the background. If a COM port or terminal with 22 byte data interface is used a second task is not needed for low baud rates. Then the communication block SerialLineControl can be called in the standard task.

The communication with virtual COM ports via SerialLineControlADS uses an ADS server. Data exchange is handled asynchronously via ADS and is managed in intermediate buffers. The server itselfs receives the incoming data of the virtual COM port independent of the PLC. So the maximal effective data transfer don't depend on the PLC task cycle time.
Only the reaction time for incoming data would be decreased by a faster task cycle time. The full delay can't be defined because the virtual-com-port-drivers and the ADS server do not run in realtime.
The communication block SerialLineControlADS usually is called in the standard task. A second task is not needed.


ReceiveByte

Interface

VAR_OUTPUT
    ByteReceived: BOOL;
    ReceivedByte: BYTE;
    Error: ComError_t;
END_VAR
VAR_IN_OUT
    RxBuffer : ComBuffer;
END_VAR

Description

The ReceiveByte block receives a single character from the interface corresponding to the input variable RxBuffer. If ByteReceived=TRUE after the call, then the data byte received is available in the output variable ReceivedByte. Otherwise no data has been received.

Note

Whenever a the ReceiveByte block is processed in a PLC task that is running slower than the communication with the hardware, it must be remembered that more than one character can be made available in each PLC cycle. The characters received should therefore be read out within a loop:

REPEAT
    Receive(RXbuffer:=RXbuffer);
    IF Receive.ByteReceived THEN
        (* evaluate character*)
    END_IF
UNTIL NOT Receive.ByteReceived
END_REPEAT

The number of passes through the loop is inevitably limited by the size of the receive data buffer (presently 300 bytes), so that an endless loop need not be feared.


SendByte

Interface

VAR_INPUT
    SendByte: BYTE;
END_VAR
VAR_OUTPUT
    Busy : BOOL;
    Error: ComError_t;
END_VAR
VAR_IN_OUT
    TxBuffer: ComBuffer;
END_VAR

Description

SendByte sends a single character to the interface corresponding to the input variable TxBuffer. For as long as Busy=TRUE, the transmission is not completed. The character was successfully sent when Busy=FALSE and Error=0.

Note

As long as the send data buffer can still accept data, more than one character can be sent in a single PLC cycle. This is, however, only worthwhile if the buffered characters will be transmitted to the hardware by a faster communication task.


ReceiveString

Interface

VAR_INPUT
    Prefix : STRING;
    Suffix : STRING;
    Timeout : TIME;
    Reset :BOOL;
END_VAR
VAR_OUTPUT
    StringReceived: BOOL;
    busy : BOOL;
    Error: ComError_t;
    RxTimeout : BOOL;
END_VAR
VAR_IN_OUT
    ReceivedString : STRING;
    RXbuffer : ComBuffer;
END_VAR

Description

ReceiveString receives a string of characters from the interface corresponding to the input variable RxBuffer, storing it in the output variable ReceivedString. The start and end of the string are recognised by various mechanisms, which can be combined with one another:

  • Prefix If a string is supplied to the input variable prefix, the first characters must be the same as this prefix. Other characters are disallowed. If no prefix is supplied (an empty string), the received string starts with the first received character.
  • Suffix If a string is supplied to the input variable suffix, the input data is read until the end of the received string agrees with the suffix. If during this process the received data reach the maximum length of the receive string, a COMERROR_STRINGOVERRUN error is generated. If an empty string is supplied as the suffix, a timeout must be defined instead, since otherwise the end of the character string cannot be recognised.
  • Timeout If a timeout is supplied to the block, then characters will be received until a correspondingly long interval has elapsed after reception of a character. The received string consists of the characters received up to that point. Suffix and timeout may be combined. If a suffix is supplied, the timeout may be 0.

As soon as the output StringReceived becomes TRUE, the received data are ready in the ReceivedString variable.

Reset

Setting the Reset input will reset the block from the receive state into the initial state. Reset is only necessary in exceptional cases, such as when the expected string can not be received.

Note

The string ReceivedString has a standard length of 80 characters which may be to short for some applications. In this case the library ComLib255.lib can be used instead of ComLib.lib. The only difference is the string length of 255 characters for ReceivedString.


SendString

Interface

VAR_INPUT
    SendString: STRING;
END_VAR
VAR_OUTPUT
    Busy : BOOL;
    Error: ComError_t;
END_VAR
VAR_IN_OUT
    TXbuffer: ComBuffer;
END_VAR

Description

SendString sends a string of characters to the interface corresponding to the input variable TxBuffer. For as long as Busy=TRUE, the transmission is not completed. The data has successfully been sent when Busy=FALSE and Error=0.

Note

The string SendString has a standard length of 80 characters. For some applications a longer string is desirable. In this case the function block SendString255 can be used. The only difference is the string length of 255 characters for SendString.


ReceiveData

Interface

VAR_INPUT
    pPrefix     : POINTER TO BYTE;
    LenPrefix   : BYTE;
    pSuffix     : POINTER TO BYTE;
    LenSuffix   : BYTE;
    pReceiveData        : POINTER TO BYTE;
    SizeReceiveData : DINT;
    Timeout     : TIME;
    Reset       :BOOL;
END_VAR
VAR_OUTPUT
    DataReceived        : BOOL;
    busy                : BOOL;
    Error                : ComError_t;
    RxTimeout   : BOOL;
    LenReceiveData : UDINT;
END_VAR
VAR_IN_OUT
    RXbuffer    : ComBuffer;
END_VAR

Description

ReceiveData receives data of any type from the interface corresponding to the input variable RxBuffer, storing it in the ReceiveData variable. The start and end of the data stream are recognised by various mechanisms, which can be combined with one another:

  • Prefix

    If a variable is passed to the input variable prefix, the first characters of the received data must be the same as this prefix. Other characters are discarded. If no prefix is supplied (null), the receive data starts with the first received character.

  • Suffix

     If an input variable suffix is supplied, the input data is read until the end of the receive data agrees with the suffix. If during this process the received data reach the maximum length of the receive string, a COMERROR_STRINGOVERRUN error is generated. If no suffix (null) is supplied, a timeout must be defined instead, since otherwise the end of the data stream cannot be recognised.

  • Block Size
    If no suffix is supplied, up to SizeReceiveData characters are received.

  • Timeout

     If a timeout is supplied to the block, then characters will be received until a correspondingly long interval has elapsed after reception of a character. The receive data consists of the characters received up to that point. Suffix and timeout may be combined. If a suffix is supplied, the timeout may be 0.

As soon as the output DataReceived becomes TRUE, the receive data is ready in the ReceiveData variable. The number of characters received is given in LenReceiveData.

pPrefix

pPrefix is the address of any kind of data structure that is passed to the block using ADR(variable name). LenPrefix indicates the number of data bytes in the prefix.

LenPrefix

LenPrefix indicates the number of data bytes in the prefix.

pSuffix

pSuffix is the address of any kind of data structure that is passed to the block using ADR(variable name).

LenSuffix

LenSuffix indicates the number of data bytes in the suffix.

pReceiveData

pReceiveData is the address of the receive data, and is found by means of ADR(receive data). The receive data is placed in the variables to which pReceiveData points.

SizeReceiveData

SizeReceiveData is found by means of SIZEOF(receive data), and indicates the maximum size of the receive data.

Timeout

Timeout defines the maximum interval between two received characters. Timeout monitoring becomes effective after the first character. This means that timeout cannot be used to detect whether an expected telegram arrives or not. This is monitored externally.

Reset

Setting the Reset input will reset the block from the receive state into the initial state. Resetting is only necessary in exceptional cases, if, for example, the expected data could not be received and the block remains busy.

DataReceived

DataReceived becomes TRUE as soon as the receive data is valid. The output remains TRUE for precisely one cycle, which means that it is necessary to evaluate the received data immediately.

Busy

Busy becomes TRUE after the first character has been received, and goes FALSE as soon as the data has been received or an error has occurred.

Error

If a fault occurs, Error will contain an error code. The error code is defined by the data type ComError_t, and this is used to display it in text form at runtime.

RxTimeout

RxTimeout becomes TRUE if the maximum interval between two received characters is exceeded. This causes data reception to be aborted, and the characters received up to this point are available. If a suffix is not being used, then detection of a timeout does not represent a fault, but indicates the normal end of the receive data. If, on the other hand, a suffix was being used, it was not possible to receive this.

LenReceiveData

LenReceiveData indicates the actual number of data bytes received, and can be less than or equal to SizeReceiveData.

RxBuffer

RxBuffer is the receive data buffer corresponding to the interface in use.


SendData

Interface

VAR_INPUT
    pSendData : POINTER TO BYTE;
    Length : UDINT;
END_VAR
VAR_OUTPUT
    Busy : BOOL;
    Error: ComError_t;
END_VAR
VAR_IN_OUT
    TXbuffer: ComBuffer;
END_VAR

Description

SendData sends the contents of a variable of any type to the interface corresponding to the input variable TxBuffer. For as long as Busy=TRUE, the transmission is not completed. The data has successfully been sent when Busy=FALSE and Error=0.

pSendData

pSendData is the address of the send data, and is determined by means of ADR(send data).

The data must not be changed as long as Busy is TRUE and the transmission is not completed.

Length

Length is the number of data bytes to be sent, and can be smaller than or equal to the size of the data structure being used. If the entire contents of a variable are to be sent, then the length can be determined using SIZEOF(send data).


ClearComBuffer

Interface

VAR_IN_OUT
    Buffer : ComBuffer;
END_VAR

Description

The communication buffer, Buffer, internal to the PLC, is cleared.


SerialLineControl

The SerialLineControl function block looks after the communication between a serial interface (KL60xx, EL60xx or COM interface) and the PLC. The function block is called cyclically, and places received data into the RxBuffer. Data made available in the TxBuffer transmit buffer is sent to the interface at the same time.

Because the function operates independently of the application, it is referred to as background communication and can, particularly in the case of serial bus terminals, also operate in a fast task (see Communication concept and Supported hardware).

In Version 2.0 and above of the library the function block replaces the hardware-dependent KL6Control, KL6Control5B and PcComControl function blocks.

Interface

VAR_INPUT
        Mode    : ComSerialLineMode_t;
        pComIn  : POINTER TO BYTE
        pComOut         : POINTER TO BYTE
        SizeComIn       : UINT;
END_VAR
VAR_OUTPUT
        Error   : BOOL;
        ErrorID         : ComError_t;
END_VAR
VAR_IN_OUT
        TxBuffer        : ComBuffer;
        RxBuffer        : ComBuffer;
END_VAR

Mode | The Mode input specifies unambiguously which serial hardware is being used.
pComIn | Universal pointer to the input variable of the process data for the serial hardware (data types KL6inData, KL6inData5b, KL6inData22b, EL6inData22b, PcComInData). The pointer is assigned with the ADR() function.
pComOut | Universal pointer to the output variable of the process data for the serial hardware (data types KL6outData, KL6outData5b, KL6outData22b, EL6outData22b, PcComOutData). The pointer is assigned with the ADR() function.
SizeComIn | Size of the input process image of the serial hardware being used. The size is determined and assigned with the SIZEOF() function.
Error | The Error output becomes TRUE as soon as an error occurs.
ErrorID | The ErrorID output provides an error code when an error occurs.
TxBuffer | Buffer with transmit data for the serial hardware being used. The transmit buffer is filled by functions such as SendByte, SendData or SendString.
RxBuffer | Buffer into which received data is placed. The receive buffer is read by functions such as ReceiveByte, ReceiveData or ReceiveString.


SerialLineControlADS

The SerialLineControlADS function block looks after the communication between a virtual serial interface and the PLC. The function block is called cyclically, and places received data into the RxBuffer. Data made available in the TxBuffer transmit buffer is sent to the interface at the same time.

Because the function operates independently of the application, it is referred to as background communication and can, like the function block SerialLineControl, also operate in a fast task (see Communication concept and Supported hardware).

As soon as the function block is called cyclically and the input Connect is set, the parameterized serial COM port is opened automatically.
Thereby this COM port is blocked for other applications. Do you want to unblock the COM port to get access with another application, you can reset the input Connect. Thereby the current port will be closed. Is the COM port number or another parameter in the input structure SerialCfg changed, the previous port will get closed automatically and after it the new port will get opened.

Interface

FUNCTION_BLOCK SerialLineControlADS
VAR_INPUT
        Connect         :BOOL;                          (* connect to serial port [TRUE=connect, FALSE=disconnect] *)
        SerialCfg               :ComSerialConfig;
        NetId           :T_AmsNetId :='';                       (* host NetId *)
        Timeout         :TIME :=DEFAULT_ADS_TIMEOUT;    (* Timeout for ADS calls *)
END_VAR
VAR_IN_OUT
        TxBuffer                :ComBuffer;           (* serial Tx ComBuffer *)
        RxBuffer                :ComBuffer;           (* serial Rx ComBuffer *)
END_VAR
VAR_OUTPUT
        PortOpened      :BOOL;                  (* Indicates if selected serial port is opened *)
        Error           :BOOL;                  (* 'TRUE' if an error occurred *)
        ErrorID         :UDINT;                 (* Displays the error code; 0 = no error *)
        Busy            :BOOL;                  (* 'TRUE' if internal ADS communication is busy *)
        TxBufCount      :UDINT;                 (* number of bytes in internal Tx buffer *)
        RxBufCount      :UDINT;                 (* number of bytes in internal Rx buffer *)
END_VAR

Input variables

Connect | To open a connection to a serial port, Connect has to be TRUE. Is Connect FALSE specified, an open port will get closed. Note: If this input variable switches, it can take up to 6 times of the Timeout delay to finish the requested action. Therefore the application has to look after the output PortOpened and wait until it takes the desired state.
SerialCfg | This input structure defines a COM port and with which parameters the COM port is used and opened. For details see the description of ComSerialConfig.
NetId | For local access don't specify this input or allocate an empty string. For remote access to another TwinCAT target system specify its AMS Net Id.
Timeout | Specifies a maximum length of time for the execution of the function block. The default value is 5 seconds. (At least 1000ms should be adjusted.)

Input/output variables

TxBuffer | Buffer with transmit data for the serial hardware being used. The transmit buffer is filled by functions such as SendByte, SendData or SendString.
RxBuffer | Buffer into which received data is placed. The receive buffer is read by functions such as ReceiveByte, ReceiveData or ReceiveString.

Output variables

PortOpened | Indicates if the selected serial port is opened and connected.
Error | The Error output becomes TRUE as soon as an error occurs.
ErrorID | The ErrorID output provides an error code if an error occurs. A list of possible values as well as hints for fault correction are located in the chapter Error codes.
Busy | This output is TRUE as long as the internal ADS communication of the function block is active.
TxBufCount | The TxBufCount output indicates that some data bytes exist in the internal PLC buffer which are not yet sent.
RxBufCount | The RxBufCount output indicates that some received data bytes exist in the internal PLC buffer which are not yet transferred to the RxBuffer. It has to be ensured by the application that the received bytes are collected out off the RxBuffer fast enough.

PLC libraries to be linked
COMlibV2.lib [version 2.003.008 or higher]


PcComControl

Interface

VAR_INPUT
    COMin : PcComInData;
END_VAR
VAR_IN_OUT
    COMout : PcComOutData;
    TxBuffer: ComBuffer;
    RxBuffer: ComBuffer;
END_VAR

Description

The PcComControl function block controls the data transfer between the data buffers TxBuffer and RxBuffer internal to the PLC and the hardware. The data structures PcComInData and PcComOutData are declared globally, and are linked in the TwinCAT System Manager with the PC interface.

PcComControl is always called, regardless of whether there is any intention to send or receive data (Background Communication). This block should be called in a task that is fast enough to achieve an effective baud rate close to the physically determined baud rate.

Note

The function blocks for background communication are preferably handled in a fast task. The demands placed on the task cycle time by the serial PC interface are considerably less than those of the serial bus terminal, so that a special fast communication task for the serial PC interface is often not necessary (compare Supported Hardware).

This block is replaced by SerialLineControl from version 2 of the communication library.


KL6Control

Interface

VAR_INPUT
    COMin : KL6inData;
END_VAR
VAR_IN_OUT
    COMout : KL6outData;
    TxBuffer: ComBuffer;
    RxBuffer: ComBuffer;
END_VAR

Description

KL6Control controls the data transfer between the PLC’s internal data buffers TxBuffer and RxBuffer, and the hardware, in a manner similar to the PcComControl block.

Note

The function blocks for background communication are preferably handled in a fast task (compare Supported Hardware).

This block is replaced by SerialLineControl from version 2 of the communication library.


KL6Control5B

Interface

VAR_INPUT
    COMin : KL6inData5B;
END_VAR
VAR_IN_OUT
    COMout : KL6outData5B;
    TxBuffer: ComBuffer;
    RxBuffer: ComBuffer;
END_VAR

Description

KL6Control5B controls the data transfer between the data buffers TxBuffer and RxBuffer, internal to the PLC and the hardware in a manner similar to the KL6Control block, but in this case is for the serial bus terminal in 5-byte mode.

Note

The function blocks for background communication are preferably handled in a fast task (compare Supported Hardware).

This block is replaced by SerialLineControl from version 2 of the communication library.


ComReset

ComReset resets the connected serial hardware. This clears the internal hardware send and receive buffers. The function block supports a variety of serial hardware, such as the serial PC interface and the KL6xxx Serial Bus Terminals.

In Version 2.0 and above, the function block replaces the KL6Init function block.

Note: The function block does not clear the data buffer of type ComBuffer internal to the PLC. For initialisation purposes, this can be separately cleared with the ClearComBuffer function block.

Interface

VAR_INPUT
        Execute         : BOOL;
        pComIn  : POINTER TO BYTE
        pComOut         : POINTER TO BYTE
        SizeComIn       : UINT;
END_VAR
VAR_OUTPUT
        Done    : BOOL;
        Busy    : BOOL;
        Error   : BOOL;
        ErrorID         : UDINT;
END_VAR

Execute: A rising edge at the Execute input resets the connected serial hardware.

pComIn: Universal pointer to the input variable of the process data for the serial hardware (data types KL6inData, KL6inData5b, PcComInData). The pointer is assigned with the ADR() function.

pComOut: Universal pointer to the output variable of the process data for the serial hardware (data types KL6outData, KL6outData5b, PcComOutData). The pointer is assigned with the ADR() function.

SizeComIn: Size of the input process image of the serial hardware being used. The size is determined and assigned with the SIZEOF() function.

Done: The Done output becomes TRUE when the function has been carried out without error.

Busy: The Busy output becomes TRUE in response to rising edge at Execute, and remains TRUE for as long as the block is performing its function.

Error: The Error output becomes TRUE as soon as an error occurs.

ErrorID: The ErrorID output provides an error code when an error occurs.


KL6Configuration

The KL6configuration function block initialises and configures a KL6xxx Serial Bus Terminal.

In Version 2.0 and above of the library the function block replaces the hardware-dependent KL6Config and KL6Config5B function blocks.

Note: The function block uses register communication to configure KL6 terminals. Register communication is not available with EtherCAT terminals. EL terminal can be configured with function blocks (FB_EcCoeSdoWrite) from the TwincAT EtherCAT library.

Interface

VAR_INPUT
        Execute                 : BOOL;
        Mode            : ComSerialLineMode_t;
        Baudrate                : UDINT;                        (* 115200, 57600, 38400, 19200, 9600, 4800, 2400, 1200 *)
        NoDatabits      : BYTE;                         (* 7 or 8 *)
        Parity          : ComParity_t;            (* PARITY_NONE=0, PARITY_EVEN=1, PARITY_ODD=2 *)
        Stopbits                : BYTE;                         (* 1 or 2 *)
        Handshake       : ComHandshake_t;                 (* HANDSHAKE_NONE=0, HANDSHAKE_RTSCTS=1, HANDSHAKE_XONXOFF=2 *)
        ContinousMode   : BOOL;                         (* don't start transmission before transmit buffer is filled *)
        pComIn          : POINTER TO BYTE;      (* for universal register communication *)
        pComOut                 : POINTER TO BYTE;      (* for universal register communication *)
        SizeComIn       : UINT;
END_VAR
VAR_OUTPUT
        Done            : BOOL;
        Busy            : BOOL;
        Error           : BOOL;
        ErrorId                 : ComError_t;
END_VAR

Execute: A rising edge at the Execute input resets the connected serial hardware.

Mode: The Mode input specifies unambiguously which serial hardware is being used. (ComSerialLineMode_t).

Baudrate: The baud rate, provided it is supported by the serial hardware.

NoDatabits: The number of user data bits in one data byte.

Parity: The type of the parity bit in a data byte.

Stopbits: The number of stop bits per data byte.

Handshake: The type of handshake used, provided it is supported by the serial hardware.

ContinousMode: Switches on continuous transmission, provided this is supported by the serial hardware.

If ContinousMode is TRUE, transmitted data is not sent out by the serial hardware until the hardware transmit buffer is full. This means that there are no time gaps in the transmission, provided the quantity of data is similar in size to the hardware transmit buffer. Continuous mode is only necessary in special cases in which the end device reacts to time gaps with a time-out.

pComIn: Universal pointer to the input variable of the process data for the serial hardware (data types KL6inData, KL6inData5b, KL6inData22b, PcComInData). The pointer is assigned with the ADR() function.

pComOut: Universal pointer to the output variable of the process data for the serial hardware (data types KL6outData, KL6outData5b, KL6outData22b, PcComOutData). The pointer is assigned with the ADR() function.

SizeComIn: Size of the input process image of the serial hardware being used. The size is determined and assigned with the SIZEOF() function.

Done: The Done output becomes TRUE when the function has been carried out without error.

Busy: The Busy output becomes TRUE in response to rising edge at Execute, and remains TRUE for as long as the block is performing its function.

Error: The Error output becomes TRUE as soon as an error occurs.

ErrorID: The ErrorID output provides an error code when an error occurs.


KL6ReadRegisters

The KL6ReadRegisters function block reads one or several registers of a KL6xxx serial Bus Terminal.

Interface

VAR_INPUT
        Execute                 : BOOL;
        FirstRegister   : UINT;
        RegisterCount   : UINT;
        Mode            : ComSerialLineMode_t;
        pComIn          : POINTER TO ARRAY[0..65] OF BYTE; (* for universal register communication *)
        pComOut                 : POINTER TO ARRAY[0..65] OF BYTE; (* for universal register communication *)
        SizeComIn       : UINT;
        pRegisterList   : POINTER TO ARRAY[0..63] OF ComRegisterData_t;
        SizeRegisterList        : UINT;
END_VAR
VAR_OUTPUT
        Done            : BOOL;
        Busy            : BOOL;
        Error           : BOOL;
        ErrorId                 : ComError_t;
END_VAR

Execute: A rising edge at the Execute input resets the connected serial hardware.

FirstRegister : Specifies the first register to be read. From this register number (which may range between 1 and 64), RegisterCount data are read and stored in the register list of type ComRegisterData_t.

If no coherent register range is to be read, the value 16#FFFF can be stored in FirstRegister. In this case the user has to initialise the register numbers to be read in the register list before the block is triggered. In this case RegisterCount is not used.

RegisterCount : Specifies the number of registers to be read. The block reads a coherent register range from FirstRegister and stores the data in the register list.

Mode : The Mode input specifies unambiguously which serial hardware is being used. (ComSerialLineMode_t).

pComIn: Universal pointer to the input variable of the process data for the serial hardware (data types KL6inData, KL6inData5b, KL6inData22b, PcComInData). The pointer is assigned with the ADR() function.

pComOut: Universal pointer to the output variable of the process data for the serial hardware (data types KL6outData, KL6outData5b, KL6outData22b, PcComOutData). The pointer is assigned with the ADR() function.

SizeComIn: Size of the input process image of the serial hardware being used. The size is determined and assigned with the SIZEOF() function.

pRegisterList : Start adress of a register list of type ComRegisterData_t. The start adress can be determined with ADR(register list).

SizeRegisterList : Size of the register list in bytes. The size can be determined with SIZE(register list). The list may have between 1 and 64 entries.

Done: The Done output becomes TRUE when the function has been carried out without error.

Busy: The Busy output becomes TRUE in response to rising edge at Execute, and remains TRUE for as long as the block is performing its function.

Error: The Error output becomes TRUE as soon as an error occurs.

ErrorID: The ErrorID output provides an error code when an error occurs.


KL6WriteRegisters

The function block KL6WriteRegisters writes data to one or several registers of a serial KL6xxx Bus Terminal.

Interface

VAR_INPUT
        Execute                 : BOOL;
        Mode            : ComSerialLineMode_t;
        pComIn          : POINTER TO ARRAY[0..65] OF BYTE; (* for universal register communication *)
        pComOut                 : POINTER TO ARRAY[0..65] OF BYTE; (* for universal register communication *)
        SizeComIn       : UINT;
        pRegisterList   : POINTER TO ARRAY[0..63] OF ComRegisterData_t;
        SizeRegisterList        : UINT;
END_VAR
VAR_OUTPUT
        Done            : BOOL;
        Busy            : BOOL;
        Error           : BOOL;
        ErrorId                 : ComError_t;
END_VAR

Execute: A rising edge at the Execute input resets the connected serial hardware.
The register list must be initialised before the block is triggered. This means the register numbers and register content must be entered in the list.

Mode: The Mode input specifies unambiguously which serial hardware is being used. (ComSerialLineMode_t).

pComIn: Universal pointer to the input variable of the process data for the serial hardware (data types KL6inData, KL6inData5b, KL6inData22b, PcComInData). The pointer is assigned with the ADR() function.

pComOut: Universal pointer to the output variable of the process data for the serial hardware (data types KL6outData, KL6outData5b, KL6outData22b, PcComOutData). The pointer is assigned with the ADR() function.

SizeComIn: Size of the input process image of the serial hardware being used. The size is determined and assigned with the SIZEOF() function.

pRegisterList : Start address of a register list of type ComRegisterData_t. The start address can be determined with ADR(register list). The register list must be initialised before the block is triggered. This means the register numbers and register content must be entered in the list.

SizeRegisterList : Size of the register list in bytes. The size can be determined via SIZE(register list). The list may have between 1 and 64 entries.

Done: The Done output becomes TRUE when the function has been carried out without error.

Busy: The Busy output becomes TRUE in response to rising edge at Execute, and remains TRUE for as long as the block is performing its function.

Error: The Error output becomes TRUE as soon as an error occurs.

ErrorID: The ErrorID output provides an error code when an error occurs.


KL6Init

Interface

VAR_INPUT
    Start : BOOL;
    SerStatus : BYTE;
END_VAR
VAR_OUTPUT
    Busy : BOOL;
    Ready : BOOL;
END_VAR

Description

KL6Init initialises the KL6xxx serial bus terminal without altering its configuration. The terminal’s internal buffers are cleared.

The SerStatus and SerCtrl input data correspond to the data linked with the terminal in the TwinCAT System Manager. They are defined in the COMlib KL6inData and KL6outData data structures respectively.

The terminal has been successfully initialised after the Start signal when Busy=FALSE and Ready=TRUE.


KL6Config

Interface

VAR_INPUT
    Start : BOOL; (* Edge triggered *)
    Baudrate : INT;         (* 19200, 9600, 4800, 2400, 1200 *)
    NoDatabits : BYTE;      (* 7 or 8 *)
    Parity : BYTE;          (* 0=no 1= even 2 = odd *)
    Stopbits : BYTE;        (* 1 or 2 *)
    Handshake : BYTE;       (*0=none,1=RTS/CTS,2=XON/XOFF*)
    COMin : KL6inData;
END_VAR
VAR_OUTPUT
    Err : BOOL;
    ErrId : WORD;
    Busy : BOOL;
END_VAR
VAR_IN_OUT
    COMout : KL6outData;
END_VAR

Description

KL6Config configures the interface parameters of the KL6xxx serial bus terminal.

Note

As long as the KL6Config block is active (busy), the KL6Control block for background communication must not be called! Initialisation and normal communication with the serial bus terminal use the same registers.

This block is replaced by KL6configuration from version 2 of the communication library.


KL6Config5B

Interface

VAR_INPUT
    Start : BOOL; (* Edge triggered *)
    Baudrate : INT;        (* 19200, 9600, 4800, 2400, 1200 *)
    NoDatabits : BYTE;     (* 7 or 8 *)
    Parity : BYTE;         (* 0=no, 1= even, 2 = odd *)
    Stopbits : BYTE;       (* 1 or 2 *)
    Handshake : BYTE;        (*0=none,1=RTS/CTS,2=XON/XOFF*)
    COMin : KL6inData5B;
END_VAR
VAR_OUTPUT
    Err : BOOL;
    ErrId : WORD;
    Busy : BOOL;
END_VAR
VAR_IN_OUT
    COMout : KL6outData5B;
END_VAR

Description

KL6Config5B works in a manner similar to that of the KL6Config block, but operates the serial bus terminal in 5-byte mode.

Note

As long as the KL6Config5B block is active (busy), the KL6Control5B block for background communication must not be called! Initialisation and normal communication with the serial bus terminal use the same registers.

This block is replaced by KL6configuration from version 2 of the communication library.


ASC

Interface

FUNCTION ASC : BYTE
VAR_INPUT
    str : STRING;
END_VAR

Description

The function Asc returns the ASCII code of the first character of the input sting as one byte.

Background

Transmission data is often available as a string of characters. If it is to be sent, the individual characters are required as bytes.


CHR

Interface

FUNCTION CHR : STRING
VAR_INPUT
    c : BYTE;
END_VAR

Description

The function Chr returns the character corresponding to the ASCII code in the input variable c to a string.

Background

Received characters arrive as bytes at the PLC system, and must often be further processed in the form of strings.


ComBuffer

The ComBuffer data structure is a data buffer that decouples the hardware-dependent communication blocks from the hardware-independent blocks (see Communication Principle). At the same time this decouples a fast communication task from the standard task. Data buffers of type ComBuffer are never directly written or read by the user, but are merely used as intermediate storage for the communication blocks.

TYPE ComBuffer
STRUCT
    Buffer: ARRAY[0..300] OF BYTE;
    RdIdx: INT;
    WrIdx: INT;
    Count: INT; (* Number of characters in the ring buffer *)
    FreeByte:INT; (* Number of free spaces in the ring buffer *)
    Error: INT; (* Interface error code *)
    blocked : BOOL;
END_STRUCT
END_TYPE


Data structures RegisterList

Data type ComRegisterList_t has been defined for reading and writing of registers of a serial Bus Terminal. Each entry of the register list contains the register number and the register content.

ComRegisterList_t

TYPE ComRegisterList_t : ARRAY[0..63] OF ComRegisterData_t;
END_TYPE

ComRegisterData_t

TYPE ComRegisterData_t :
STRUCT
        Register : BYTE;
        Value : WORD;
END_STRUCT
END_TYPE


ComSerialConfig

This input structure defines a COM port and with which parameters the COM port is used and opened.

If a parameter is changed during the cyclic call of SerialLineControlADS the existing COM port connection is automatically closed and reopened again with the new parameters. In this case it is not necessary to explicitly close the port by reset the input Connect.

TYPE ComSerialConfig :
(* contains the configuration parameters of the com port to be opened. *)
STRUCT
        ComPort         :UDINT          :=1;                    (* Serial port number [1..255] *)
        Baudrate        :UDINT          :=9600;
        Parity          :ComParity_t    :=PARITY_NONE;
        DataBits        :INT            :=8;                    (* [4..8] *)
        StopBits        :ComStopBits_t  :=STOPBITS_ONE;

        DTR             :ComDTRCtrl_t   :=DTR_CTRL_HANDSHAKE;   (* 'Data Terminal Ready' signal *)
        RTS             :ComRTSCtrl_t   :=RTS_CTRL_HANDSHAKE;   (* 'Request to Send' signal (= RFR 'Ready for Receiving') *)
        CTS             :BOOL           :=FALSE;                (* 'Clear to Send' signal *)
        DSR             :BOOL           :=FALSE;                (* 'Dataset Ready' signal *)

        TraceLevel      :BYTE           :=0;                    (* None=0;Error=1,Warning=2,Info=3,Verbose=4,Noise=5 *)

        Reserved1       :BYTE;
        Reserved2       :BYTE;
        Reserved3       :BYTE;
END_STRUCT
END_TYPE

ComPort | Any COM port, COM1 .. COM255, can be selected. Which number is given by the driver (e.g. a USB-To-Virtual-Com-Port-Driver), can be figured out with the Windows Hardware Device-Manager.
Baudrate | All standard communication baud rates can be adjusted. Baud rates are available from 150 baud up to 115200 baud. Default is 9600 baud.
Parity | The setting of the parity checking for the serial communication is done here. Possible values are given by the enumeration ComParity_t.
DataBits The setting of the number of data bits for the serial communication is done here. Possible values are 4,5,6,7 and 8.
For a value smaller than 8 bits, the full data bytes will be given to the PLC buffer anyway. However, not all 8 bits per byte will be transmitted via the serial interface. The most significant bits are cut off. Due to this, the amount of bits per each transmitted data byte is reduced. This setting was basically reasonable in former times, if you knew that the most significant bits were never used und you wanted to decrease the transfer time. It is used rarely, so it's recommended to keep the value of data bits at 8 [default].
StopBits | The setting of the number of stop bits for the serial communication is done here. Possible values are given by the enumeration ComStopBits_t.
RTS | The setting of the 'Request to Send' ( = RFR 'Ready for Receiving' ) signal for the serial communication is done here. Possible values are given by the enumeration ComRTSCtrl_t.
DTR | The setting of the 'Data Terminal Ready' signal for the serial communication is done here. Possible values are given by the enumeration ComDTRCtrl_t.
CTS | The setting of the 'Clear to Send' signal for the serial communication is done here. If the value is TRUE no data is sent if the CTS input signal of the transmission is not set.
DSR | The setting of the 'Dataset Ready' signal for the serial communication is done here. If the value is TRUE no data is sent if the DSR input signal of the transmission is not set. Also received data bytes are ignored if parameter DSR is TRUE and the DSR input signal of the transmission is not set.
TraceLevel The message output (debug traces) of the TcAdsSerialCommServer is configured with this input variable.

This do not concern the error output of the PLC function block SerialLineControlADS. It is a matter of an additional diagnostic possiblity.

The following Trace Level are available (default = 0):

None | 0 (default)
Error | 1
Warning | 2
Info | 3
Verbose | 4
Noise | 5

All messages with a lower or equal level than the given one are output. If level 'None' is chosen no messages are output.

As output Debug Traces are used. Under win32 also Log Events (application log) are used for error /warning /info messages.
At level 'Noise' even the incoming data from the serial port is output in messages. Therefore many system resources are needed and it should only be used for temporary tests.
Hint: Using the tool DebugView (from SysInternals) the setting CaptureGlobalWin32 has to be active to receive the messages.

Note: Not every configuration of the parameters for the serial communication is always possible. Some settings or combinations of settings are not supported by Windows or the Com-Port-Drivers.
(Example: Often the possibility of 1.5 stop bits or 4 data bits or the combination of 5 data bits and 2 stop bits is not supported. Or the baud rate is limited to a maximum of 115200 baud.)

Further information to the parameters for a serial communication are given in the Microsoft MSDN description of the DCB structure.

PLC libraries to be linked
COMlibV2.lib [version 2.003.008 or higher]


Data structures for the KL6xxx serial bus terminal in 3-byte mode

For data exchange by way of the I/O bus, every serial bus terminal needs variables of type KL6inData and KL6outData. These variables are placed at a fixed address in the memory map, and are linked to the hardware with the TwinCAT System Manager.

KL6inData

TYPE KL6inData
STRUCT
    Status: BYTE;
    SerStatus: BYTE;
    D: ARRAY[0..2] OF BYTE;
END_STRUCT
END_TYPE

KL6outData

TYPE KL6outData
STRUCT
    Ctrl: BYTE;
    SerCtrl: BYTE;
    D: ARRAY[0..2] OF BYTE;
END_STRUCT
END_TYPE


Data structures for the KL6xxx serial bus terminal in 5-byte mode

For data exchange by way of the I/O bus, every serial bus terminal needs variables of type KL6inData5B and KL6outData5B. These variables are placed at a fixed address in the memory map, and are linked to the hardware with the TwinCAT System Manager.

KL6inData5B

TYPE KL6inData5B
STRUCT
    Status: BYTE;
    D: ARRAY[0..4] OF BYTE;
END_STRUCT
END_TYPE

KL6outData5B

TYPE KL6outData5B
STRUCT
    Ctrl: BYTE;
    D: ARRAY[0..4] OF BYTE;
END_STRUCT
END_TYPE


Data structures for the KL6xxx serial bus terminal in 22-byte mode

TS6340 | TwinCAT PLC Lib: Serial Communication

Data structures for the KL6xxx serial bus terminals in 22-byte mode

For data exchange by way of the I/O bus, every serial bus terminal needs variables of type KL6inData22B and KL6outData22B. These variables are placed at a fixed address in the memory map, and are linked to the hardware with the TwinCAT System Manager.

KL6inData22B

TYPE KL6inData22B
STRUCT
        Status  : WORD;
        D       : ARRAY[0..21] OF BYTE;
END_STRUCT
END_TYPE

KL6outData22B

TYPE KL6outData22B
STRUCT
        Ctrl    : WORD;
        D       : ARRAY[0..21] OF BYTE;
END_STRUCT
END_TYPE


Data structures for the KL6xxx serial bus terminal in 22-byte mode

TS6340 | TwinCAT PLC Lib: Serial Communication

Data structures for the EL60xx serial EtherCAT terminal in 22-byte mode

For data exchange by way of the I/O bus, every serial EtherCAT terminal needs variables of type EL6inData22B and EL6outData22B. These variables are placed at a fixed address in the memory map, and are linked to the hardware with the TwinCAT System Manager.

EL6inData22B

TYPE EL6inData22B
STRUCT
        Status  : WORD;
        D       : ARRAY[0..21] OF BYTE;
END_STRUCT
END_TYPE

EL6outData22B

TYPE EL6outData22B
STRUCT
        Ctrl    : WORD;
        D       : ARRAY[0..21] OF BYTE;
END_STRUCT
END_TYPE


Data structures for the COM serial PC interfaces

Every serial PC interface needs a variable of type PcComInData and one of type PcComOutData for data exchange. These variables are placed at a fixed address in the memory map, and are linked to the hardware with the TwinCAT System Manager.

PcComInData

TYPE PcComInData
STRUCT
    SerStatus: WORD;
    D: ARRAY[0..63] OF BYTE;
END_STRUCT
END_TYPE

PcComOutData

TYPE PcComOutData
STRUCT
    SerCtrl: WORD;
    D: ARRAY[0..63] OF BYTE;
END_STRUCT
END_TYPE


Enumeration types

TS6340 | TwinCAT PLC Lib: Serial Communication

Enumarated Types for the Communication Library

ComSerialLineMode_t

The enumeration type ComSerialLineMode_t defines the type of used serial hardware for different hardware dependent function blocks of the serial communication library.

TYPE ComSerialLineMode_t :
(
        SERIALLINEMODE_DEFAULT,
        SERIALLINEMODE_KL6_3B_ALTERNATIVE,
        SERIALLINEMODE_KL6_5B_STANDARD,
        SERIALLINEMODE_KL6_22B_STANDARD,
        SERIALLINEMODE_PC_COM_PORT,
        SERIALLINEMODE_EL6_22B,
        SERIALLINEMODE_IE6_11B
);
END_TYPE

ComHandshake_t

TYPE ComHandshake_t :
(
        HANDSHAKE_NONE,
        HANDSHAKE_RTSCTS,
        HANDSHAKE_XONXOFF,
        RS485_FULLDUPLEX,
        RS485_HALFDUPLEX,
        RS485_FULLDUPLEX_XONXOFF,
        RS485_HALFDUPLEX_XONXOFF
);
END_TYPE

ComParity_t

TYPE ComParity_t :
(
        PARITY_NONE,
        PARITY_EVEN,
        PARITY_ODD,
        PARITY_MARK,    (* only available with SerialLineControlADS *)
        PARITY_SPACE    (* only available with SerialLineControlADS *)
);
END_TYPE

ComStopBits_t

TYPE ComStopBits_t :
(
        STOPBITS_ONE    := 1,
        STOPBITS_TWO    := 2,
        STOPBITS_ONE5   := 3
);
END_TYPE

ComDTRCtrl_t

TYPE ComDTRCtrl_t :
(
        DTR_CTRL_DISABLE,
        DTR_CTRL_ENABLE,
        DTR_CTRL_HANDSHAKE
);
END_TYPE

ComRTSCtrl_t

TYPE ComRTSCtrl_t :
(
        RTS_CTRL_DISABLE,
        RTS_CTRL_ENABLE,
        RTS_CTRL_HANDSHAKE,
        RTS_CTRL_TOGGLE
);
END_TYPE


Error Codes

ComError_t

TYPE ComError_t :
(
        COMERROR_NOERROR                        := 0,
        COMERROR_PARAMETERCHANGED               := 1,           (* input parameters changed during reception *)
        COMERROR_TXBUFFOVERRUN          := 2,           (* string > transmit buffer *)
        COMERROR_STRINGOVERRUN          := 10,          (* end of string *)
        COMERROR_ZEROCHARINVALID                := 11,          (* string cannot receive zero characters *)
        COMERROR_INVALIDPOINTER         := 20,          (* invalid data pointer, e. g. zero *)
        COMERROR_INVALIDRXPOINTER               := 21,          (* invalid data pointer for ReceiveData *)
        COMERROR_INVALIDRXLENGTH                := 22,          (* invalid length for ReceiveData, e. g. zero *)
        COMERROR_DATASIZEOVERRUN                := 23,          (* end of data block *)
        COMERROR_INVALIDPROCESSDATASIZE := 24,
        COMERROR_MODENOTSUPPORTED               := 16#0101,     (* mode not supported (3-Byte Terminals connectd to bus controllers) *)
        COMERROR_INVALIDCHANNELNUMBER   := 16#0102,
        COMERROR_INVALIDBAUDRATE                := 16#1001,
        COMERROR_INVALIDNUMDATABITS             := 16#1002,
        COMERROR_INVALIDNUMSTOPBITS             := 16#1003,
        COMERROR_INVALIDPARITY          := 16#1004,
        COMERROR_INVALIDHANDSHAKE               := 16#1005,
        COMERROR_INVALIDNUMREGISTERS    := 16#1006,
        COMERROR_INVALIDREGISTER                := 16#1007,
        COMERROR_TIMEOUT                        := 16#1008
);
END_TYPE

Note: Error codes of type ComError_t are not used by the function block SerialLineControlADS.


Error Codes

Overview of the function block FB_ASC_SerialLineControl error codes

Offset + error code | Range | Description
0x00000000 + TwinCAT system error | 0x00000000-0x00007800 | TwinCAT system error (including ADS error codes)
0x00000000 + TcAdsSerialCommServer error | 0x00009000-0x000091FF | Error of the TwinCAT ADS Serial Comm Server
0x3D090000 + Win32 system error code | 0x3D090000-0x3D09FFFF | Win32 system error

Note: Error codes of type ComError_t are not used by this function block.

TcAdsSerialCommServer errors

Code (hex) | Code (dec) | Description | Symbolic name
0x00009001 | 36865 | COM Port is invalid. valid range: 1 .. 255 | COMERRORADS_INVALID_COMPORT
0x00009002 | 36866 | The command for the TcAdsSerialCommServer is invalid. | COMERRORADS_INVALID_CMD
0x00009003 | 36867 | internal error | COMERRORADS_INVALID_DATAPOINTER
0x00009011 | 36881 | The transferred parameter structure is unknown. | COMERRORADS_INVALID_CFGSTLEN
0x00009012 | 36882 | The transferred parameter structure is unknown. | COMERRORADS_INVALID_CFGSTVER
0x00009013 | 36883 | The trace level (variable TraceLevel in input structure SerialCfg) for message output is invalid. | COMERRORADS_INVALID_TL
0x00009021 | 36897 | Baud rate is not supported. | COMERRORADS_INVALID_BAUDRATE
0x00009022 | 36898 | Parity is invalid. | COMERRORADS_INVALID_PARITY
0x00009023 | 36899 | Number of data bits is invalid. | COMERRORADS_INVALID_BYTESIZE
0x00009024 | 36900 | Number of stop bits is invalid. | COMERRORADS_INVALID_STOPBIT
0x00009025 | 36901 | Dtr Control is invalid. | COMERRORADS_INVALID_DTR_CTRL
0x00009026 | 36902 | Rts Control is invalid. | COMERRORADS_INVALID_RTS_CTRL
0x00009027 | 36903 | Cts is invalid. | COMERRORADS_INVALID_CTS_OUTCTRL
0x00009028 | 36904 | Dsr is invalid. | COMERRORADS_INVALID_DSR_OUTCTRL
0x00009029 | 36905 | Dsr is invalid. | COMERRORADS_INVALID_DSR_SENS
0x00009031 | 36913 | internal error | COMERRORADS_NOT_INIT
0x00009032 | 36914 | The receive buffer in the TcAdsSerialCommServer is overrun. Incoming data will be lost. Note: Received data has to be retrieved immediately. It has to be ensured by the application that no data accumulate in the function block SerialLineControlADS. This can be observed with the output RxBufCount . At a stable communication connection this value do not exceed 1000. | COMERRORADS_RD_BUFFER_OVERRUN
0x00009033 | 36915 | The COM Port is already open. SerialLineControlADS will automatically try to close the port and reopen it again with the input parameters. If there is no error output for the next cycles and if the output PortOpened gets TRUE, the COM Port has successfully be opened. | COMERRORADS_PORT_CONNECTED
0x00009034 | 36916 | The COM Port is not yet opend by the TcAdsSerialCommServer. The interaction with the port was not possible. SerialLineControlADS will automatically try to reopen the port again with the input parameters. If there is no error output for the next cycles and if the output PortOpened gets TRUE, the COM Port has successfully be opened. | COMERRORADS_PORT_NOT_CONNECTED
0x00009035 | 36917 | The COM Port couldn't be closed correctly. | COMERRORADS_RD_THREAD_TIMEOUT
0x00009036 | 36918 | The COM Port couldn't be closed correctly. | COMERRORADS_WR_THREAD_TIMEOUT
0x00009037 | 36919 | During an existing communication connection this error can occur if the USB device is disconnected. Before disconnecting the USB device the input bConnect has to be set to FALSE in order to close the COM Port. Also a read error can be the reason. Details can be output using the variable TraceLevel in the input structure SerialCfg. Note: SerialLineControlADS has closed the port and will automatically try to reopen it again with the input parameters. If there is no error output for the next cycles and if the output PortOpened gets TRUE, the COM Port has successfully be opened. | COMERRORADS_RD_FAILURE
0x00009038 | 36920 | A write error can be the reason for this error code. Details can be output using the variable TraceLevel in the input structure SerialCfg. It's possible that data is not transferred. No retry of writing is started automatically. | COMERRORADS_WR_FAILURE
0x000090E0 - 0x000090FF | 37088 - 37119 | internal errors |
0x00009101 | 37121 | The version of the TcAdsSerialCommServer is incompatible. An official product installation clears the error. | COMERRORADS_SERVER_INCOMPATIBLE

additional explanation of the most important Win32 system errors

Code (hex) | Code (dec) | Description | additional explanation | Symbolic name
0x3D090002 | 1024000002 | The system cannot find the file specified. | This error can occur if the selected COM port is not available. Check if the value of the used COM port and of the other parameters in ComSerialConfig is set correctly. | ERROR_FILE_NOT_FOUND
0x3D090005 | 1024000005 | Access is denied. | Check if the corresponding serial COM port is already opened by another application. Then you have to unblock this port in the other application to make the communication possible. | ERROR_ACCESS_DENIED
0x3D090057 | 1024000087 | The parameter is incorrect. | This error occurs if an input parameter for the serial communication (see ComSerialConfig) is invalid. Not every configuration of the parameters for the serial communication is always possible. Some settings or combinations of settings aren't supported by Windows or the Com-Port-Drivers. In this case you should check if the communication works with other input parameters. | ERROR_INVALID_PARAMETER

Note: For a more detailed fault analysis the debug messages of the TcAdsSerialCommServer can be configured with the variable TraceLevel in the input structure SerialCfg.


Installation

COMlibV2

In order to install, the library COMlibV2.lib must be copied into the TwinCAT directory TwinCAT\PLC\LIB.

COMlib

In order to install, the library COMlib.LIB and the auxiliary libraries ChrAsc.LIB and ChrAsc.OBJ, which are also supplied, must be copied into the TwinCAT directory TwinCAT\PLC\LIB.

The associated test program should be copied to any project directory of your choice, e.g. to TwinCAT\PLC.

  • Sample Program Serial Communication

Link libraries

Create a new PLC project with TwinCAT PLC Control in order to perform the library linking.

Go to Library Management and add the libraries ChrAsc.LIB and ComLib.LIB.


Global Variables

Four global data structures are needed to access a serial interface. Two provide the connection to the hardware in the send and receive directions. Two data buffers are also necessary for intermediate storage.


Task Configuration

The speed of the serial interfaces must be considered for the task configuration (see the section on Supported Hardware and the Communication Principle). For example, in order that, with 9600 bps at the serial bus terminal, the data can all actually be processed at this speed, the associated communication block must be active at least once per millisecond. The task that operates the block must have a correspondingly fast setting. The simplest case is when the entire PLC program runs in this fast task. If the task is set slower, then as long as the interface operates with a hardware handshake, the communication will function at reduced speed. Without handshake, data to be received can be lost.

Note

Pay attention to the K-Bus update time if bus terminals KL6xxx and bus couplers BKxxxx are used. The K-Bus update time which can be figured out in the TwinCAT SystemManager with a click on the bus coupler under I/O Configuration has to be less than the PLC task cycle time (10%-20%). If many terminals are connected to one bus coupler it may be necessary to increase the task cycle time to a minimum of 2 ms.


Background Communication

Communication between the serial hardware and the data buffer, whose type is ComBuffer, is handled in a separate fast task.

See also the Communication Principle.

with COMlibV2:

with COMlib:


Sending and Receiving

Sending data

Data is sent from the standard task. The example program included sends data by way of the serial PC interface to a printer.

Possible errors

More than one character may be transmitted during one PLC cycle, provided they can be accepted by the send buffer. If the send buffer overflows, the busy output of the send block will remain TRUE after it has been called. In that case the last character is not sent, and the block must be called again with the same input data in the next PLC cycle. How full a buffer is can be determined at any time (e.g. TxBuffer.Count or TxBuffer.FreeByte).

Data reception

The example program receives a bar code from a scanner that is connected to a serial bus terminal.


Serial PC Interface

The PC’s standard serial interface is entered into the I/O configuration as a new I/O device.

After this the interface is configured:

COMlib only supports KL6xx1 emulation operation. Data bytes must be set to 64 bytes. The interface parameters are set appropriately in the application.

Sync mode: In Sync mode, communication with the interface hardware is synchronised with the communication task. This setting usually offers benefits at high baud rates, as long the cycle time of the communication task is short enough. At 115 kBaud, for example, 12 characters are received each millisecond. The interface therefore has to be operated with a maximum cycle time of 1 ms, in order to avoid overflow of the 16-byte hardware FIFO. If the cycle times are too long, there is a risk of buffer overflow.

If Sync mode is switched off, the interface is served via the Windows timer interrupt every millisecond, irrespective of the task cycle time. This mode is not real-time capable, and with high computer utilisation longer operating intervals may be experienced. In this case, with very high baud rates there is also a risk of buffer overflow.

It is recommended to activate Sync mode and to adjust the cycle time of the communication task to the baud rate in such a way that overflow of the 16-byte hardware buffer is avoided. For smaller baud rates and with a slower communication task, Sync mode may perhaps be deactivated.

The next step is to link the inputs and outputs to the corresponding data structures in the PLC (types PcComInData and PcComOutData) by means of multiple linking.

The new configuration is activated, and the system is restarted.


Serial Bus Terminal

KL6xxx in 3-Byte Mode

The serial bus terminal is entered into the system under a bus coupler.

Then the input and output data is linked with the corresponding PLC variables (of types KL6inData and KL6outData).

The new configuration is activated, and the system is restarted.


Serial Bus Terminal

KL6xxx in 5-Byte Mode

Before a KL6xxx bus terminal can be used in 5-byte mode, it must be appropriately reconfigured. This can not be done through ComLib while running, but must be performed with the Beckhoff KS2000 configuration program. The terminal is then permanently set for 5-byte mode.

The serial bus terminal is now entered into the system under a bus coupler.

Then the input and output data are individually linked to the corresponding PLC variables (of types KL6inData5B and KL6outData5B).

The new configuration is activated, and the system is restarted.


Task Assignment

When declaring global variables in TwinCAT PLC Control, the individual variables are not assigned to a particular task. Therefore they initially appear in the TwinCAT System Manager under the standard task.

Since the task’s cycle time determines the update cycle on the I/O bus, it is essential that the data structures for communication between the fast communication task and the hardware be assigned to that task. The corresponding entries under the standard task’s inputs and outputs are dragged with the mouse or with the Move to context menu into the communication task.

All data structures of the following types are affected:

  • KL6inData
  • KL6outData
  • KL6inData5B
  • KL6outData5B
  • KL6inData22B
  • KL6outData22B
  • EL6inData22B
  • EL6outData22B
  • PcComInData
  • PcComOutData

Communication data structures in the fast communication task


Samples

TS6340 | TwinCAT PLC Lib: Serial Communication

Examples

The following examples have been developed with different hardware.

Sample 2 - Tutorial

The usage of the library function blocks is described as tutorial in the chapters 'Linking into a PLC Program' and 'Configuration in the TwinCAT System Manager'. The employment of different hardware is mentioned here too.

Sample 3 - Usage of virtual serial com ports

with installation > v2.3.0 supported

This example can be used for various applications with virtual com ports.
It is possible to send a user-defined data stream and to receive any incomming data.

This sample is no application sample. It is a test program to test the communication to the USB device.
Only the call of SerialLineControlAds is specific if the application uses a virtual com port. The handling of write and read data is identical to applications using real serial ports.

Note: Attend the installation guide on the overview page.
It is recommended to check the operativeness of the VirtualComPort driver of your device first with a windows terminal program.

No linking in the TwinCAT system manager is needed.
The sample can be used for a comfortable start-up and test of the device. The sample includes a visualization.

Project Download