24
Modbus TCP Master Sample Application Revision 1.02 Prepared by Pyramid Solutions, Inc. This document describes the application and use of the Modbus TCP Master Sample Application. The program was written to run on a Control Logix 5000 processor with a compatible Ethernet Module. This sample application can be used standalone by adding any required logic for your application, or can be added to an existing application following the directions outlined below. The audience for this document would be Software engineers, controls engineers, and application engineers familiar with Logix 5000 controllers, RSLogix 5000, and Modbus TCP protocol and its uses. Knowledge of the use of the Modbus protocol is crucial to using this application. This application will allow you to create a Modbus TCP Master capable of connecting to multiple Modbus TCP compatible slaves(s) to read and write control data. There is also a Modbus TCP Slave Sample application if a slave is desired, i.e. you need to be connected to by a Master. This application is provided as is and there is no Warranty or implied merchantability. See the Rockwell Sample Code Download Terms and Conditions.pdf that was downloaded with this document for more information on Acceptance of Terms and Conditions. Your rights to download and use this content are limited and can be revoked at any time. No support contract is implied or delivered with this code or any modified version of this code. .

ModbusTCP Master Application R102

Embed Size (px)

DESCRIPTION

Modbus handbook

Citation preview

Page 1: ModbusTCP Master Application R102

Modbus TCP Master Sample

Application Revision 1.02

Prepared by Pyramid Solutions, Inc.

This document describes the application and use of the Modbus TCP Master Sample Application. The program was written to run on a Control Logix 5000 processor with

a compatible Ethernet Module.

This sample application can be used standalone by adding any required logic for your application, or can

be added to an existing application following the directions outlined below.

The audience for this document would be Software engineers, controls engineers, and application

engineers familiar with Logix 5000 controllers, RSLogix 5000, and Modbus TCP protocol and its uses.

Knowledge of the use of the Modbus protocol is crucial to using this application.

This application will allow you to create a Modbus TCP Master capable of connecting to multiple Modbus

TCP compatible slaves(s) to read and write control data. There is also a Modbus TCP Slave Sample

application if a slave is desired, i.e. you need to be connected to by a Master.

This application is provided as is and there is no Warranty or implied merchantability. See the Rockwell Sample Code Download Terms and Conditions.pdf that was downloaded with this document for more information on Acceptance of Terms and Conditions. Your rights to download and use this content are limited and can be revoked at any time. No support contract is implied or delivered with this code or any modified version of this code.

.

Page 2: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Before you Begin You will require a compatible Ethernet module to run the Modbus TCP Master application with. The

path to the modules port will be configured in the tags and will be used for all operations. This port

can also functions as a programming interface and web application provider as well, depending on

performance needs.

Sample Files in RSLogix 5000 V20 format The RSLogix 5000 project file associated with this solution uses RSLogix 5000 version 20.

It is recommended you use this solution with RSLogix 5000 version 20 or greater. Remember, your

Logix5000 controller must use a firmware revision that matches the RSLogix 5000 version (i.e., we

recommend you upgrade your Logix5000 controller to firmware revision 20.x or greater to use this

solution. See Knowledgebase ID 470365 for a detailed list of supported controllers.

Page 3: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Subset of Modbus Function Codes Supported The following table shows the functions codes supported by this application. If needed,

additional function codes could be added by a user providing they fit the application. The

Modbus specification is available at http://www.modbus-IDA.org.

Table 1

Function code: Name: Data level:

Description:

01 Read Coils Bit level This function code is used to read from 1 to 2000 contiguous status of coils in a remote device. The application as configured has a maximum of 256. The coils in the response message are packed as one coil per bit of the data field. 0 = OFF 1 = ON

02 Read Discrete Inputs

This function code is used to read from 1 to 2000 contiguous status of discrete inputs in a remote device. The application as configured has a maximum of 256. The discrete inputs in the response message are packed as one input per bit of the data field. 0 = OFF 1 = ON

05 Write Single Coil

This function code is used to write a single output to either ON or OFF in a remote device. 0 = OFF 1 = ON

15 Write Multiple Coils

This function code is used to force each coil in a sequence of coils to either ON or OFF in a remote device. The protocol supports a maximum count of 2000. The application as configured has a maximum of 256. 0 = OFF 1 = ON

03 Read Holding Registers

Word (16-bit) level

This function code is used to read the contents of a contiguous block of holding registers in a remote device. The protocol has a maximum count of 125. The application as configured has a maximum of 120.

04 Read Input Registers

This function code is used to read from 1 up to 125 contiguous input registers in a remote device. The application as configured has a maximum of 120.

06 Write Single Register

This function code is used to write a single holding register in a remote device

16 Write Multiple Registers

This function code is used to write from 1 up to 125 contiguous registers in a remote device. The application as configured has a maximum of 120.

Page 4: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Using the application The ModbusTCP_Master_R1021.acd file allows you to use a Logix5000 controller as a master on

Modbus. I t r e q u i r e s 2 0 0 - 2 3 0 k o f c o n t r o l l e r m e m o r y i n i t s s u p p l i e d c o n f i g u r a t i o n . The ACD file contains:

• 42 Controller tags

• 1 continuous task with 1 program

• 9 user-defined data types

The application, as supplied, has the following limitations.

• Maximum of 4 connections to unique IP addresses

• 5 Transactions per connection (each transaction is a read or write operation)

• Maximum transaction size of 120 (either registers or coils depending on the transaction type)

• Maximum local address range of 1024 coils and discrete inputs and 256 registers and input

registers.

Note that these limitations can be changed by the user modifying the application.

Implementing your application There are two options for starting your application using this sample app. First is to start with this

sample and add your own task(s) to it. The other is to copy the components of this application into

an existing project. The steps to do this second method will be discussed here.

Notes on the Controller Tag Naming Convention Used In the controller tags used in this application there are two prefixes used to help you discern the tags used for Modbus TCP usage and those used for the user‟s application. These prefixes each have a different meaning to help the user know which values they should be using and those they should not. MBTU_ is used to designate a tag that is to be set or used by the user on a normal basis. MBTI_ SHOULD NOT normally be modified. They are used for internal values which are either used by the application while running or are set to a value to indicate the extents of the program. The later would only be changed if the programs limits, for example number of connections, is changed by actually modifying the program‟s array sizes along with additions or removals of tags.

Page 5: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Importing the sample application into your own project. To import the Modbus TCP Master application into your own project the following steps

should be followed in order.

1. First assure you have a compatible Ethernet network card configured in your

application.

2. Import the Modbus TCP Master application into your project.

3. Configure the path to the Ethernet port which the application will use.

4. Enable the New program

5. Verify that your RSLogix 5000 project is working.

You will need to open two instances of RSLogix 5000, on with the Modbus Master application the other with the application you wish to integrate it into. In the Modbus TCP Project, right click on the PROGRAM FOLDER and select export program as shown to create an L5X file "ModbusMasterTCP.L5X”.

Page 6: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Now in the application you are integrating into, right click on a task and select program import as shown to import "ModbusMasterTCP.L5X" as shown.

NOTE: It is recommend to import into a periodic task of 50 to 100ms to insure proper operation. Slow or faster speeds have not been tested.

Page 7: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

New Modbus Master Controller Tags The following table describes the controller tags you imported from the Master Sample Project.

Note that tags beginning with MBTI_ are NOT changed unless the extents of the program have

changed. i.e. the number of possible connections or the number of transactions on a connection.

Tag name: Tag type: Description: Valid Values:

MBTI_Buf_Len_Sent DINT Number of bytes sent to a device on a write function.

MBTI_Connect_Sock_MSG_00 through MBTI_Connect_Sock_MSG_03

MESSAGE Messages blocks for the connections

MBTI_Create_Sock_MSG_00 through MBTI_Create_Sock_MSG_03

MESSAGE Message blocks for creating the connection

MBTI_Delete_All_MSG MESSAGE Message block for the Delete All command

MBTI_Delete_Socket_MSG_00 through MBTI_Delete_Socket_MSG_03

MESSAGE Message block to delete the connection

MBTI_DestAddress_00 through MBTI_DestAddress_03

OpenConnParams Used internally to set the destination addresses for each device to connect to.

Do not directly modify this value. Instead change the address in the MBTIConnections tag.

MBTI_Instance DINT[4] Stores the instance values for each connected socket.

MBTI_Read_Data_MSG_00 through MBTI_Read_Data_MSG_03

MESSAGE Used to read data sent from the slave.

MBTI_Read_Data_Req READ_DATA_REQ[20] Internal buffer. MBTI_Read_Resp READ_RESP_STR[20] Internal buffer. MBTI_Write_Data_MSG_00 through MBTI_Write_Data_MSG_03

MESSAGE Message blocks to write data to the connections

MBTI_Write_Data_Out WRT_DATA[20] Arrays for the outgoing messages for each transaction

MBTU_Connections MBConnection[4] Connection configuration and status object. Used to set the destination address and enable

Page 8: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

each of the individual

connections. Status information is also written here.

MBTU_EnetModulePort String Path to the network port that will service the MODBUS TCP protocol.

* See below explanation.

MBTU_EnMBTCP BOOL Main Enable bit for all communications. 1 – enable communications.

Clearing and setting this bit will reset the entire communications application.

MBTU_MB_0xx BOOL[1024] Local storage for all coil operations.

Source for writes dest. for reads.

MBTU_MB_1xx BOOL[1024] Local Storage for all discrete input operations.

MBTU_MB_3xx INT[256] Local Storage for all input register operations.

MBTU_MB_4xx INT[256] Local Storage for all holding register operations

MBTU_SocketParam REQUEST_PARAMET ERS

Parameters used to set up the socket on opening. Default values should work in most instances.

MBTU_Transactions_00 through MBTU_Transactions_04

MBTransactions[5] These define each transaction, read or write, for each corresponding connection.

See description below for how to populate the UDT.

* MBTU_EnetModulePort this value should be set to '$01$00' for all CompactLogix 5370 processors. This value should be set to '$01$xx‟ where xx is the 1756 backplane slot number, in hex, of the desired Ethernet module for all 1756 ControlLogix processors, for example '$01$02' for an Ethernet module located in 1756 backplane slot 2 or '$01$10' for an Ethernet module located in 1756 backplane slot 16. It is recommended to leave all MSG instructions as configured. All MSG instructions are currently configured as unconnected See Knowledgebase ID 530345 for information on connected vs. unconnected messaging.

Page 9: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Configuring your Master Application. The final step in getting your master application running is to set up the configuration tag values and configure your Ethernet Port. The critical values to set are below. Finally setting MBTU_EnMBTCP will enable the master causing all configured and enabled outgoing connections to be attempted.

Once this bit is set, the Master will attempt connections (using port 502 which is setup in MBTU_Connections[x]) to the given slave(s), and upon success will start the transactions enabled for that connection. The read and write requests will use the local data arrays for the source or destination data. MBTU_MB_0xx is used for coil transactions types 01, 05, and 15. MBTU_MB_1xx is used for discrete input transaction type 2. MBTU_MB_3xx is used for input register transaction type 4. MBTU_MB_4xx is used for holding register transactions types 3, 6, and 16.

Configuration Tags

(note: tags starting with MBT are controller scoped, all others are program scoped).

Tag Name Description

MBTU_EnetModulePort Path to the Ethernet port being used. This can either be the port name or the numeric path i.e. “$01$01” See below. *

MBTU_Connections Each element is used to enable the corresponding connection that is configured. By default there are four connections configured, but only the first is enabled for use.

NumberOfConnection Set to the number of connections configured. Do not confuse with the number enabled, this is the amount the application is able to handle. The default value is 4 for four connections.

MBTU_Socket_Param A structure used for creating the socket. Settings include the port address (default 502 for Modbus TCP Protocol) that the connections will be made to.

MBTU_Transactions_00 through MBTU_Transactions_03

Array of UDT MBTransaction. These are used to define the read and writes transactions done on each connection. See the description following on how to configure and use a transaction.

MBTU_EnMBTCP Master enable bit used to turn the driver on and off. Turning off will close any connections that were open.

*MBTU_EnetModulePort this value should be set to '$01$00' for all CompactLogix 5370 processors. This value should be set to '$01$xx‟ where xx is the 1756 backplane slot number, in hex, of the desired Ethernet module for all 1756 ControlLogix processors, for example '$01,$02' for an Ethernet module located in 1756 backplane slot 2 or '$01,$10' for an Ethernet module located in 1756 backplane slot 16.

Refer to your Ethernet module documentation to configure you Ethernet module. At minimum you should configure the address and subnet mask or select DHCP.

Page 10: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Configuring a connection:

Each connection is configured using it‟s element in the MBTU_Connections tag. Below is a description of the values in the MBCOnnection UDT. The value that should be configured prior to connection is the MBTU_DestAddress.

MBConnection

UDT

Tag Name Description

MBTU_DestAddress A string containing the IP address and port to make a connection to of the form of „xxx.xxx.xxx.xxx?port=502‟. Notice that port 502 is the default setting for ModbusTCP communications. Note that “port” must be in all lower case!

MBTU_Enable A Boolean that enables and disables this single connection.

MBTI_NumberOfTransactions States the size of the Transactions array for this connection minus one. This is basically used as the terminating value for FOR instructions, therefore the minus 1 value.

MBTI_Connected A Bool value indicating a connection exists or no connection exists.

MBTI_ConnLastError This value is set on various connection level errors when they occur. A 0 represents all is well on an enabled connection. Other values are outlined below and covered in the debugging section. Other errors that can exist for a single transaction are written to the Transaction‟s UDT.

Note if your changing your MBTU_DestAddress while running, you will need to disable your connection (enable bit in the connection UDT) wait about 30 seconds, then re-enable the connection to switch to the new address.

Configuring and Using a Transaction. Below are the instructions for creating and using a transaction for the Modbus TCP Master Sample application to use.

Reference the descriptions below in the following sections.

To configure a transaction: You will need to set the following values.

• Enabled set to one to enable this transaction

• PollInterval set to something 1 or higher. Any other value will disable the transaction.

• Transtype 1, 2, 3, 4, 5, 6, 15, or 16. The read or write Modbus transaction you wish performed.

• UID (possibly) Typically used if the destination address is a gateway with more than one device on the other side, or if a particular device uses a UID. If this is the case enter the device‟s UID.

• BeginAddress The starting address of the operation minus 1 without the first digit type identifier. For example, address 40001 in the PAC will be 0 here.

• Count Number of items to read or write (either registers or discrete, whichever applies).

• LocalOffset This is the offset into the local data arrays (MBTU_MB_Xxx) at which to begin the data for this operation.

Page 11: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

After these have been set, clearing the ReqBuilt bit will build your new transaction string. Also for write operations, the request string is automatically built on every transmission so the data changes will be reflected.

To use a transaction:

In the case of reads, checking the Transcomplete and TransStat will let you know the validity of the transaction and its data. The data can be read from MBTU_MB_0xx for coil operations, MBTU_MB_1xx for discrete input reads, MBTU_MB_3xx for input register reads, and MBTU_MB_4xx for holding register operations. Data will always begin at the transaction‟s specified local offset in those arrays. The TransLastError value will indicate any errors, either local or Modbus Exceptions received. A 0 here indicates successful transactions, any other values can be found in the following section on error codes.

Page 12: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Transaction Examples

The following sections will give examples and explanations of each of the supported transaction types. It should be noted that some devices will require a matching value in the Unit ID (UID) field of the transactions.

The following tables show the key values in the Transaction structures for each transaction. The description following the table describes what will happen.

Read Coils

This transaction will poll every 10th

time the poll timer times out, which in the case of a 100ms poll timer, would mean this transaction is done every 1000 milliseconds or 1 second. The TransType is 1 meaning a coil read is going to be done. Begin address is 0, means we will start reading at address 00001 of the device being read. The count is 10, meaning 10 coils will be read and a LocalOffset of 0 will put the data starting at the first element (index 0) of MBTU_MB_0xx and continue on to index 9.

Read Discrete Inputs

Tag Name Value

PollInterval 20

TransType 2

BeginAddress 9

Count 10

LocalOffset 10

This transaction will poll every 20th

time the poll timer times out, which in the case of a 100ms poll timer, would mean this transaction is done every 2 second. The TransType is 2 meaning a discrete input read is going to be done. Begin address is 9, means we will start reading at address 10010 of the device being read. The count is 10, meaning 10 coils will be read and with a LocalOffset of 10 the data will be placed starting at index 10 of MBTU_MB_1xx and continue on to index 19.

Read Holding Registers

Tag Name Value

PollInterval 15

TransType 3

BeginAddress 99

Count 25

LocalOffset 100

This transaction will poll every 15th

time the poll timer times out, which in the case of a 100ms poll timer, would mean this transaction is done every 1.5 second. The TransType is 3 meaning a holding register read is going to be done. Begin address is 99, means we will start reading at address 40100

of the device being read. The count is 25, meaning 25 16 bit holding registers will be read and with a

LocalOffset of 100 the data will be placed at indexes 100 through 124 of MBTU_MB_4xx.

Tag Name Value

PollInterval 10

TransType 1

BeginAddress 0

Count 10

LocalOffset 0

Page 13: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Read Input Registers

This transaction will poll every 20th

time the poll timer times out, which in the case of a 100ms poll timer, would mean this transaction is done every 2 second. The TransType is 4 meaning an input register read is going to be done. Begin address is 4, means we will start reading at address 30005 of the device being read. The count is 10, meaning 10 16 bit input registers will be read and with a LocalOffset of 5, the data will be placed in index 5 through 14 of MBTU_MB_3xx.

Write Single Coil

This transaction will poll every 2nd time the poll timer times out, which in the case of a 100ms poll timer, this transaction is done 5 times a second. The TransType is 5 meaning a coil write is going to be done. Begin address is 24, means we will write to address 00025 of the device being written to. The count isn‟t applicable for a TransType of 5. A LocalOffset of 25 means the data will come from index 25 of MBTU_MB_0xx.

Also keep in mind that since this is a write operation, every time you change the data to be written you must clear the ReqBuilt flag in this transaction definition so that the request will be rebuilt with the new data in it.

Write Single Register

This transaction will poll every 5th

time the poll timer times out, which in the case of a 100ms poll timer, would mean this transaction is done twice a second. The TransType is 6 meaning it will be writing a single register. Begin address is 9, means we will write to address 40010 of the device being written to. The count does not apply to a TransType of 6. A LocalOffset of 10 the data will come from index 10 of MBTU_MB_4xx.

Also keep in mind that since this is a write operation, every time you change the data to be written you must clear the ReqBuilt flag in this transaction definition so that the request will be rebuilt with the new data in it.

Tag Name Value

PollInterval 20

TransType 4

BeginAddress 4

Count 10

LocalOffset 5

Tag Name Value

PollInterval 2

TransType 5 BeginAddress 24

Count NA

LocalOffset 25

Tag Name Value

PollInterval 5

TransType 6

BeginAddress 9

Count NA

LocalOffset 10

Page 14: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Write Multiple Coils

Tag Name Value

PollInterval 10

TransType 15

BeginAddress 99

Count 25

LocalOffset 100

This transaction will poll every 10th

time the poll timer times out, which in the case of a 100ms poll timer, would mean this transaction is done every second. The TransType is 15 meaning it will be writing multiple coils. Begin address is 99, means we will start writing at address 00100 of the device being written to. The count is 25, meaning 25 single bit coils will be written and with a LocalOffset of 100 the data will come from indexes 100 through 124 of MBTU_MB_0xx.

Also keep in mind that since this is a write operation, every time you change the data to be written you must clear the ReqBuilt flag in this transaction definition so that the request will be rebuilt with the new data in it.

Write Multiple Holding Registers

Tag Name Value

PollInterval 30

TransType 16

BeginAddress 49

Count 10

LocalOffset 50

This transaction will poll every 30th

time the poll timer times out, which in the case of a 100ms poll timer, would mean this transaction is done every 3 seconds. The TransType is 16 meaning it will be writing multiple registers. Begin address is 49, means we will start writing at address 40050 of the device being written to. The count is 25, meaning 25 registers will be written, and with a LocalOffset of 50 the data will come from indexes 50 through 59 of MBTU_MB_4xx.

Also keep in mind that since this is a write operation, every time you change the data to be written you must clear the ReqBuilt flag in this transaction definition so that the request will be rebuilt with the new data in it.

Retry Timers Each connection has a retry timer which is used to re-establish communications in the event a connection is lost or errors out. The timers are named Retry_Timers[] and their default setting is 10 seconds. You can modify these to suite your needs and network environment.

Page 15: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

How to Enable a New Connection The application comes with a default capability of 4 connections to different IP addresses. Anyone of these IP addresses can be a gateway device which allows more than one controller to be accessed on the other side of the gateway using the unit ID‟s in the transaction definitions. The application is distributed with only one of these connections enabled. To enable additional connections follow the procedure outlined below.

First verify that the tag NumberOfConnectios is set to 4 (default value), or whatever the total number of

connections there are in your version of the application, whether they‟re enabled or not. And remember you will be using the Ethernet port specified in MBTU_EnetModulePort for all connections, so ensure you have a physical path to the device your trying to connect to through that port.

Configure your transactions for that connection. Remember to set the enable tag and clear the ReqBuilt flag so the request string will be rebuilt and the transaction will be processed. If this is the second connection you should be modifying transactions in MBTU_Transactions_01, and for the third MBTU_Transactions_02, etc. Also note if the poll interval is not a valid value (o or a negative value), the Enable tag will be cleared by the application.

Set the MBTU_DestAddress in the MBTU_Connections element for the connection your configuring. Again in the case of adding the second connection this should be MBTU_Connections[1].MBTU_DestAddress. For a device with an IP address of 192.168.1.197. you would be specified the DestAddr member as „192.168.1.197?port=502‟. Port 502 is the default port for Modbus TCP communications.

The final step is to enable the actual connection and reset communications. In the MBTU_Connections[x] array, find the element corresponding to the connection you‟re enabling and set the MBTU_Enable value. For instance in the case of enabling the second connection you would set MBTU_Connections[1].MBTU_Enable. Now clear the tag MBTU_ENMBTCP, wait for approximately 10 seconds, and then set it again. This last step will clean up any loose connections items and re-initialize all connections that are enabled.

Page 16: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

How to Change the Number of Transactions on a Connection The number of transaction that can be configured for each connection can be modified to fit one‟s

needs. Either they can be increased if additional reads or writes are necessary, or they can be

reduced to save memory. The default is 5 transactions on each connection.

The change is relatively simple if increasing the number of transactions, first resize the array of transactions for that connection. Say if increasing the number from 5 to 10 for the second connection, resize the controller scoped tag MBTU_Transactions_01 from 5 to 10 elements, then modify the value controller tag MBTU_Connections[1].MBTI_NumberOfTransactions from 4 to 9 (it is always set to one less than the actual number), in this case MBTU_Connections[1].MBTI_NumberOfTransactions = 9.

To decrease the number of transactions you would do the same but in reverse. First change the value of NumberOfTransactions, then change the actual number of elements in the tag MBTU_Connections[x].MBTI_NumberOfTransactions. For instance on the first connection to go from 5 to 2, you would first change MBTU_Connections[0].MBTI_NumberOfTransactions to 1, then modify MBTU_Transactions_00 to have only 2 elements.

Page 17: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Description of the MBTransaction UDT:

Element Name Description Notes/Value restrictions

Enabled Enables this transaction if it is on an enabled connection.

0 – disabled 1 - enabled

PollInterval Specifies the interval of the root poll time that this transaction is performed.

If the root poll interval is 0.1 seconds and you wish to run this transaction every 0.3 seconds, this value would be set to 3. The poll rate should not be faster than the time the remote device can answer or error -15 will occur on the connection.

TransType Transaction type to perform as specified in the Modbus transaction types.

1 – Read Coils 2 – Read Discrete Inputs 3 – Read Holding Registers 4 – Read Input Register 5 – Write Single Coil 6 – Write single Register 15 – Write Multiple Coils 16 – Write Multiple Registers

UID Unit Id. With some devices, this will be a “don‟t care” (like the matching slave application), setting this to 0 in those situations would be advised.

This value should be set to the UID of the device connecting to. If connecting through a gateway, this value will be the UID of the device on the other side of the gateway.

BeginAddress This is the address or start address for the intended operation minus one. This is the address as it is contained in the MB Transaction. The first digit of the PAC address identifying the type is omitted.

Address 0001 is 0 10001 is 0 30001 is 0 40001 is 0.

Count Number of items to read or write. This would be The number of bits for coils and discrete inputs and number of registers for register operations.

Limit is 120 as the application is supplied.

Page 18: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

LocalOffset The offset to begin this operation in the appropriate local data array (MBTU_MB_Xxx).

Note that the maximum local addresses are 1024 for discrete operations and 256 for register operations.

TransactionComplete The application will set this to 0 when a request is made and set to 1 when a response is received.

This value is normally cleared automatically at the start of each request, but can be cleared by the application to ensure that the write operation has occurred.

TransStat Integer with the status code from the previous transaction. 0 = successful. If a response has not been received -1, which is normal on each poll of the transaction for the time from the request is made until a response is received.

Read only.

Request This is where the string for the actual request is built. Useful for debugging, but don‟t modify it directly.

Read Only

ReqBuilt A BOOL value indication that the transaction string has been built. Clearing this bit will force the Request string to be re- evaluated. This should be done if the transaction is changed in any way, including write operation‟s data values.

Clear this bit if the transaction definition is modified.

TransID The transaction ID that the last request was sent under. Do not modify this value directly. It is used to match replies to their corresponding request.

Read Only.

TransLastError Records any errors that may occurred on transaction level.

0 – successfully working when transaction is enabled on an enabled connection. See the following chart for error values.

Page 19: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Transtat values Transstat values give you a status of the current transaction.

-1 Request was sent but no reply has been received yet. 0 The request was sent and a response with no exception was received.

Transaction‟s TransLastError and MBTI_ConnLastError Values There are two error tags that can be examined for diagnostic purposes. The Transaction definition structures contain a TransLastError component which will post the following values if an error occurs during reading and writing. In addition each connection has is represented in the Connections UDT member MBTI_ConnLastError which will display connection status. Both sets of values are described in the table below. This table includes errors for both the Modbus TCP master and slave applications. See the Modbus reference for further information on the exception values.

Local generated errors:

0 Transaction completed successfully or connection was successful. -1 Transaction has not received a reply, note that this is normal if checked after the request is

made but before the reply is received. -2 Network write error occurred. An error reported by the TCP/IP stack during a write. -3 Local write error occurred. An error with the message block occurred during a write. -4 Network read error occurred. An error reported by the TCP/IP stack during a read. -5 Local read error occurred. An error with the message block occurred during a read. -6 Connection to remote device failed to connect. -7 Delete All failed. Most likely due to the MBTU_EnetModulePort is incorrectly set. -8 Create Socket failed. Most likely due to bad input parameters, or lack of socket resources. -9 Connect failed. An attempt to connect/reconnect was made and was not successful. -10 Connection Dropped. This could be caused by the remote device or loss of connectivity. -11 Error in setting the connection accept timeout. -12 Invalid transaction type requested, the transaction has been disabled. -13 Requested transaction will exceed local data array‟s size (MBTU_MB_XXX arrays). The

transaction has been disabled. -15 10 consecutive requesting transactions were sent out with no replies received from previous

requests. Either no replies are being received, or you are requesting the data faster than the device is capable of replying. A re-connect is being attempted. You may need to adjust the preset on the NoReplyCounter for the connection involved from the default of 10 depending on your applications poll rate and the device you‟re are communicating with. A higher rate of request may cause more missing replies during a temporary network interruption.

If a Modbus exception was received, see the values below.

Modbus exception values: 01 Illegal Function 02 Illegal data address

03 Illegal data value 04 Slave device failure 05 Acknowledge 06 Slave device busy 08 Memory parity error 0A Gateway path unavailable 0B Gateway target device failed to respond

Page 20: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Message Block Error Values

Page 21: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Other codes that are possible but not common, here is a full list:

Error Code (Dec/Hex)

22 16 EINVAL Invalid argument

32 20 EPIPE Broken pipe

40 28 EDESTADDRREQ Destination address required

41 29 EPROTOTYPE Protocol wrong type for socket

42 2A ENOPROTOOPT Protocol not available

43 2B EPROTONOSUPPORT Protocol not supported

44 2C ESOCKTNOSUPPORT Socket type not supported 45 2D EOPNOTSUPP Operation not supported on socket

46 2E EPFNOSUPPORT Protocol family not supported

47 2F EAFNOSUPPORT Addr family not supported

48 30 EADDRINUSE Address already in use

49 31 EADDRNOTAVAIL Can't assign requested address

50 32 ENOTSOCK Socket operation on non-socket

51 33 ENETUNREACH Network is unreachable

52 34 ENETRESET Network dropped connection on reset

53 35 ECONNABORTED Software caused connection abort

54 36 ECONNRESET Connection reset by peer

55 37 ENOBUFS No buffer space available

56 38 EISCONN Socket is already connected

57 39 ENOTCONN Socket is not connected

58 3A ESHUTDOWN Can't send after socket shutdown

59 3B ETOOMANYREFS Too many references: can't splice

60 3C ETIMEDOUT Connection timed out

61 3D ECONNREFUSED Connection refused

62 3E ENETDOWN Network is down

63 3F ETXTBSY Text file busy

64 40 ELOOP Too many levels of symbolic links

65 41 EHOSTUNREACH No route to host

66 42 ENOTBLK Block device required

67 43 EHOSTDOWN Host is down

68 44 EINPROGRESS Operation now in progress

69 45 EALREADY Operation already in progress

70 46 EWOULDBLOCK Operation would block

71 47 ENOSYS Function not implemented

Page 22: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Debugging Connection Issues

This section will outline a method of diagnosing problems with the application. Key values to look at and probably causes for some issues are covered.

If communications don‟t appear to be working at all, check the MBTI_ConnLastError values in the MBTU_Connections arrays. Error values of -7 indicates the delete all in the MainRoutine has failed. Most likely cause of this is the MBTU_EnetModulePort being set incorrectly. Other error values indicate an error in creating, connecting, or dropping an existing connection. Below is a list that should give some guidance as to where to look with each error value.

-7 Check the Delete all message in rung 2 of the MainRoutine. Most likely cause is the MBTU_EnetModulePort being incorrectly set.

-8 An error occurred in the Create socket block for that connection. Check the corresponding MSG

block‟s error and extended error values in the MainRoutine to see what the issue is. For example for the first connection, check the MSG block in rung 4 of the main routine. Error values are listed above for reference.

-9 An error occurred in the Connect socket block for that connection. Check the corresponding MSG

block‟s error and extended error values in the MainRoutine to see what the issue is. For example for the first connection, check the MSG block in rung 6 of the main routine. Most likely causes of this error is an incorrectly specified address, or the remote device not being accessible.

-10 A disconnect has occurred. Examine the TransLastError values in the individual transactions for

that connection for additional information.

Debugging transaction errors If one or more transactions are failing, examining the TransLastError tag in each transaction‟s UDT will help you diagnose the problem.

Below is a list of values and actions you can take to further determine the root cause of the issue. The read and write message blocks for all connections are contained in the Process_Transaction routine. The connections are in order, so find the corresponding MSG block for the connection you are diagnosing. For example a write error on connection one would be on rung 3 and a read error on rung 5.

-2 &-3 A write block error has occurred, check the corresponding write MSG instruction for

additional information in the Error and Extended Error values. Most likely cause is a dropped connection or loss of network connectivity.

-4 & -5 A Read block error has occurred, check the corresponding read MSG instruction for

additional information in the Error and Extended Error values. Most likely cause is a dropped connection or loss of network connectivity.

Page 23: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

References

MODBUS PROTOCOL SPECIFICATION V1.1B A

Available from http://www.Modbus.org.

MODBUS MESSAGING ON TCP/IP IMPLEMENTATION GUIDE V1.0B

Available from http://www.Modbus.org.

ROCKWELL PUBLICATION ENET-AT002_-EN-P.PDF ETHERNET./IP SOCKET INTERFACE

Available from http://www.rockwellautomation.com/ literature/.

Revision History

August 31, 2012

ModbusTCP_Master_R100.ACD initial release

October 17, 2012

Updated Master documentation, page 13 incorrectly stated:

'meaning 25 32 bit holding registers' changed to

'meaning 25 16 bit holding registers'

No ladder changes were made.

Document renamed Modbus TCP Master Sample Application R101.

April 5, 2013

Document updated and renamed Modbus TCP Master Sample Application R102.

ACD modified and renamed, ModbusTCP_Master_R102.ACD, _SUB_SET_PATH added

four COP instructions to resolve an issue of not all MSG paths being properly updated.

Minor documentation/comment changes made to ACD.

Modified the Master documentation in the “Using the application” section, added

information on the amount of controller memory needed.

Modified the Master documentation in the “Sample Files in RSLogix 5000 V20 format”

section, added KB ID 470365 reference with detailed information on supported controllers.

Modified the Master documentation in the “New Modbus Master Controller Tags” section,

added KB ID 530345 reference with information on connected vs. unconnected MSGs.

Modified the Master documentation in the description section pg. 1 to enhance the As Is No

Warranty section.

Page 24: ModbusTCP Master Application R102

| Modbus TCP Master Sample Application

Publication Modbus TCP Master Sample Application – April 2013 Copyright ©2013 Rockwell Automation, Inc. All Rights Reserved. Printed in 2013.