UDP example

The following example shows the implementation of a simple peer-to-peer application in the PLC. The PLC application presented can send a test string to a remote PC and at the same time receive test strings from a remote PC. The test strings are displayed in a message box on the monitor of the target computer. A simple implementation of a suitable communication partner in .NET is also presented. The example can be used as a basis for realizing more complex implementations.

System requirements

Project sources

The sources of the two PLC devices only differ in terms of different IP addresses of the remote communication partners.

Project description

Auxiliary functions in the project example

In the example several functions, constants and function blocks are used, which are briefly described below:

FUNCTION_BLOCK FB_Fifo
VAR_INPUT
    new     : ST_FifoEntry;
END_VAR
VAR_OUTPUT
    bOk     : BOOL;
    old     : ST_FifoEntry;
END_VAR

A simple Fifo function block. One instance of this block is used as "send Fifo", another one as "receive Fifo". The messages to be sent are stored in the send Fifo, the received messages are stored in the receive Fifo. The bOk output variable is set to FALSE if errors occurred during the last action (AddTail or RemoveHead) (Fifo empty or overfilled).

A Fifo entry consists of the following components:

TYPE ST_FifoEntry :
STRUCT
    sRemoteHost : STRING(15);       (* Remote address. String containing an (Ipv4) Internet Protocol dotted address. *)
 nRemotePort : UDINT;    (* Remote Internet Protocol (IP) port. *)
 msg : STRING;       (* Udp packet data *)
END_STRUCT
END_TYPE
FUNCTION LogError : DINT

UDP example 1:

The function writes a message with the error code into the log book of the operating system (Event Viewer). The global variable bLogDebugMessages must first be set to TRUE.

FUNCTION LogMessage : DINT

UDP example 2:

The function writes a message into the log book of the operating system (Event Viewer) if a new socket was opened or closed. The global variable bLogDebugMessages must first be set to TRUE.

FUNCTION SCODE_CODE : DWORD

UDP example 3:

The function masks the lower 16bits of a Win32 error code returns them.

Global constants/variables

Name

Default value

Description

g_sTcIpConnSvrAddr

''

Network address of the TwinCAT TCP/IP Connection Server. Default: Empty string (the server is located on the local PC);

bLogDebugMessages

TRUE

Activates/deactivates writing of messages into the log book of the operating system;

PLCPRJ_ERROR_SENDFIFO_OVERFLOW

16#8103

Sample project error code: The send Fifo is full.

PLCPRJ_ERROR_RECFIFO_OVERFLOW

16#8104

Sample project error code: The receive Fifo is full.