You are on page 1of 11

Modbus Protocol Basically Modbus is an application layer protocol (see Figure 1) for communication between devices, mainly to exchange

data typical for the field of automation. Figure 1: ISO/OSI Context

At this level Modbus is a stateless client-server protocol (e.g. much like HTTP), based on transactions, which consist of a request (issued by the client) and a response (issued by the server). In the field where this protocol is usually applied, there exists a concept that is one of the possible schemas governing the lower level communication behavior on a network using a shared signal cable: Master-Slave. To prevent confusion, the following directed relations describe Master-Slave in terms of the Client-Server paradigm:

the Master is a Client the Slave is a Server

A transaction and it's context is visualized in Figure 2. Figure 2: Modbus Transaction

The stateless communication is based on a simple package, that is called Protocol Data Unit (PDU). The protocol specification defines three types of PDU's:

Request PDU, consisting of: 1. a code specifying a function (Function Code, 1 byte) 2. and function specific data (Function Data, varying number of bytes) Response PDU, consisting of: 1. the function code corresponding to the request (Function Code, 1 byte) 2. and response specific data (Response Data, varying number of bytes) Exception Response PDU, consisting of: 1. the function code corresponding to the request + 0x80 (128), (Error Code, 1 byte) 2. and a code specifying the exception (Exception Code, 1 byte)

Figure 3 presents a visualization of these packages.

Figure 3: Modbus Protocol Data Units (PDU)

Modbus Functions The specification defines a certain number of functions, each of which is assigned a specific function code. These are in the range 1-127 (decimal), as 129(1+128)- 255(127+128) represents the range of error codes. While the first published version of the specification defined different classes of functions (e.g. Class 0, Class 1, Class 2), the newly released specification (from http://www.modbus.org; see Knowledge Base Index) defines categories of function codes:

Public Are guaranteed to be unique and specify well defined functions that are publicly documented. These are validated by the community and a conformance test exists. User-Defined Are available for user-defined functions, thus their codes might not be unique. The specification defines the code ranges 65-72 and 100-110 for user-defined functions. Reserved These are currently used by some companies for legacy products and are not available for public use (these are not discussed any further in the specification).

The documentation for a function consists of: 1. a description of the function (i.e. what it is good for), it's parameters and return values (including possible exceptions). 2. the assigned Function Code 3. the Request PDU 4. the Response PDU 5. the Exception Response PDU The specification further documents defined and assigned public functions. Exceptions In certain cases, the response from a slave will be an exception. The primary identification of an exception response is the error code (function code + 128), which is further specified by the exception code. Assigned codes and descriptions can be found in the specification. Modbus Data Model The basic public functions have been developed for exchanging data typical for the field of automation. Table 1 contains the basic Mod bus data types defined by the specification.

Table 1: Modbus Data Types

Name Discrete Input Discrete Output (Coils)

Type single bit single bit

Access read-only read-write

Visual

Input Registers Holding Registers (Registers) Note

16-bit word 16-bit word

read-only read-write

The specification does not define the ways of organizing the related data in a device. However, the organization has a direct influence on the addresses used in basic access functions. (Thus always consult the device's documentation to learn about addressing in basic access functions!) Modbus Implementations Basically Mod bus has been implemented and used over all types of physical links (wire, fiber and radio) and various types of lower level communication stacks. However, we will concentrate on the two basic types of implementations (which are supported by jamod):

1. Serial: Asynchronous Master/Slave 2. IP: Master/Slave


Serial Modbus Implementations Modbus started it's life in form of an implementation for asynchronous serial network communication. The application level protocol operates directly on top of a serial interface and serial communication standards. The most common ones (over wire) are:

RS232 (EIA232): see The RS232 Standard RS422/RS485: see Introduction to RS422 and RS485

RS232 is used for short distance point-to-point communication, the same is valid for RS 422, which is a bidirectional extension of RS232 for industrial environments, that also supports longer distances. RS485 can be used for multipoint communication (i.e. multiple devices connected to the same signal cable), employing the Master-Slave paradigm (one master and n fixed address slaves). Figure 4 visualizes the possible network setups.

Figure 4: Serial Network Architectures

To enable the actual communication for this setups, the implementation extends the PDU with additional fields, better said, it wraps the PDU into a package with a header and an error checksum (see Figure 5). The resulting package is defined by the protocol specification as Application Data Unit (ADU), that has a maximum package size of 256 bytes. Note The maximum package size limitation of 256 bytes applies for all existing Mod bus protocol implementations! Figure 5: Serial ADU

The header is composed of an address field (1 byte) and the tail is an error checksum over the whole package, including the address field (i.e. header). For transmission the Mod bus message (i.e. ADU) is placed into a frame that has a known beginning and ending point, allowing detection of the start and the end of a message and thus partial messages. There exist two transmission modes, which differ in encoding, framing and checksum:

1. ASCII
Frames are encoded into two ASCII characters per byte, representing the hexadecimal notation of the byte (i.e. characters 09, AF). The error checksum is represented by a longitudinal redundancy check (LRC; 1 byte) and messages start with a colon (':', 0x3A), and end with a carriage return line feed ("CRLF", 0x0D0A). Pauses of 1 second between characters can occur. 2. RTU Frames are transmitted binary to achieve a higher density. The error checksum is represented by a cyclic redundancy check (16 bit CRC; 2 byte) and messages start and end with a silent interval of at least 3.5 character times. This is most easily implemented as a multiple of character times at the baud rate that is being used on the network. The maximum pause that may occur between two bytes is 1.5 character times.

Warning The RTU implementation does only support the Master side. It is working by the best effort principle, which means it might not work in a reliable way in a low-latency real-time context. It is indeed possible to implement the serial transport based on other serial stack implementations (i.e. replacements for the Java Comm API implementation) like for example SerialPort ( http://www.sc-systems.com/products/serialport/serialport.htm). According to the product info it supports around 20 platforms and it has been successfully used to implement the two serial transmission modes in Java (Master only, see Field Talk/Java, a commercial Master protocol pack from Focus Engineering). IP based Modbus Implementations A TCP/IP based Modbus protocol implementation (Modbus/TCP) has been recently committed as an RFC draft to the IETF. It uses the TCP/IP stack for communication (registered port is 502) and extends the PDU with an IP specific header (see Figure 6). The possible network setups are not governed by the specification; it is possible to setup multimaster systems or realize bidirectional communication (i.e. have nodes that are master and slave at the same time). However, the user should be well aware that there are implications from deviations of the Master/Slave schema. Figure 6: Modbus/TCP ADU

The IP specific header (called MBAP in the specification) is 7 bytes long and composed of the following fields:

1. the invocation identification (2 bytes) used for transaction pairing; formerly called
transaction identifier

2. the protocol identifier (2 bytes), is 0 for Modbus by default; reserved for future extensions 3. the length (2 bytes), a byte count of all following bytes 4. the unit identifier (1 byte) used to identify a remote unit located on a non-TCP/IP network
Critical Evaluation of the Specification(s) There are a few points regarding the specification, which are definitely discussable: 1. The specification does not present a consistent naming for all of the basic simple data types. This propagates to the naming of a number basic data access functions. Probably it would be good to elaborate one consistent naming schema, to avoid confusion and allow better mind mapping. 2. The Modbus Encapsulated Interface (MEI) is exposed through a documented public function, without being further explained. 3. The properties of the protocol are perfectly suited for the use of UDP/IP as transport layer protocol: a. it is stateless, b. transaction oriented c. and the package size is limited to 256 bytes, which should be easily transferable over any IP capable link (including IP over Serial) without the necessity to split the package.

Especially if a real-time communication has to be achieved, it might be of interest to investigate in a Modbus/UDP implementation. Modbus message structure The Modbus communication interface is built around messages. The format of these Modbus messages is independent of the type of physical interface used. On plain old RS232 are the same messages used as on Modbus/TCP over ethernet. This gives the Modbus interface definition a very long lifetime. The same protocol can be used regardless of the connection type. Because of this, Modbus gives the possibility to easily upgrade the hardware structure of an industrial network, without the need for large changes in the software. A device can also communicate with several Modbus nodes at once, even if they are connected with different interface types, without the need to use a different protocol for every connection. On simple interfaces like RS485 or RS232, the Modbus messages are sent in plain form over the network. In this case the network is dedicated to Modbus. When using more versatile network systems like TCP/IP over ethernet, the Modbus messages are embedded in packets with the format necessary for the physical interface. In that case Modbus and other types of connections can co-exist at the same physical interface at the same time. Although the main Modbus message structure is peer-to-peer, Modbus is able to function on both point-to-point and multidrop networks. Each Modbus message has the same structure. Four basic elements are present in each message. The sequence of these elements is the same for all messages, to make it easy to parse the content of the Modbus message. A conversation is always started by a master in the Modbus network. A Modbus master sends a message anddepending of the contents of the messagea slave takes action and responds to it. There can be more masters in a Modbus network. Addressing in the message header is used to define which device should respond to a message. All other nodes on the Modbus network ignore the message if the address field doesn't match their own address. Modbus message structure Field Description

Device address Address of the receiver Function code Data Error check Code defining message type Data block with additional information Numeric check value to test for communication errors

Modbus serial transmission modes: Modbus/ASCII and Modbus/RTU Serial Modbus connections can use two basic transmission modes, ASCII or RTU, remote terminal unit. The transmission mode in serial communications defines the way the Modbus messages are coded. With Modbus/ASCII, the messages are in a readable ASCII format. The Modbus/RTU format uses binary coding which makes the message unreadable when monitoring, but reduces the size of each message which allows for more data exchange in the same time span.

All nodes on one Modbus network segment must use the same serial transmission mode. A device configured to use Modbus/ASCII cannot understand messages in Modbus/RTU and vice versa. When using Modbus/ASCII, all messages are coded in hexadecimal values, represented with readable ASCII characters. Only the characters 0...9 and A...F are used for coding. For every byte of information, two communication-bytes are needed, because every communication-byte can only define 4 bits in the hexadecimal system. With Modbus/RTU the data is exchanged in a binary format, where each byte of information is coded in one communication-byte. Modbus messages on serial connections are not sent in a plain format. They are framed to give receivers an easy way to detect the beginning and end of a message. When using Modbus/ASCII, characters are used to start and end a frame. The colon ':' is used to flag the start of a message and each message is ended with a CR/LF combination. Modbus/RTU on the other hand uses time gaps of silence on the communication line for the framing. Each message must be preceded by a time gap with a minimum length of 3.5 characters. If a receiver detects a gap of at least 1.5 characters, it assumes that a new message is comming and the receive buffer is cleared. The main advantage of Modbus/ASCII is, that it allowes gaps between the bytes of a message with a maximum length of 1 second. With Modbus/RTU it is necessary to send each message as a continuous stream. Properties of Modbus/ASCII and Modbus/RTU Modbus/ASCII Characters Error check Frame start Frame end Gaps in message Start bit Data bits Parity Stop bits ASCII 0...9 and A..F LRC Longitudinal Redundancy Check character ':' characters CR/LF 1 sec 1 7 even/odd 1 none 2 Modbus/RTU Binary 0...255 CRC Cyclic Redundancy Check 3.5 chars silence 3.5 chars silence 1.5 times char length 1 8 even/odd 1 none 2

Modbus addressing The first information in each Modbus message is the address of the receiver. This parameter contains one byte of information. In Modbus/ASCII it is coded with two hexadecimal characters, in Modbus/RTU one byte is used. Valid addresses are in the range 0..247. The values 1..247 are assigned to individual Modbus devices and 0 is used as a broadcast address. Messages sent to the latter address will be accepted by all slaves. A slave always responds to a Modbus message. When responding it uses the same address as the master in the request. In this way the master can see that the device is actually responding to the request.

Within a Modbus device, the holding registers, inputs and outputs are assigned a number between 1 and 10000. One would expect, that the same addresses are used in the Modbus messages to read or set values. Unfortunately this is not the case. In the Modbus messages addresses are used with a value between 0 and 9999. If you want to read the value of output (coil) 18 for example, you have to specify the value 17 in the Modbus query message. More confusing is even, that for input and holding registers an offset must be substracted from the device address to get the proper address to put in the Modbus message structure. This leads to common mistakes and should be taken care of when designing applications with Modbus. The following table shows the address ranges for coils, inputs and holding registers and the way the address in the Modbus message is calculated given the actual address of the item in the slave device. Device and Modbus address ranges Device address Modbus address Description Coils (outputs) Inputs Holding registers

1...10000* address - 1 10001...20000* address - 10001 40001...50000* address - 40001


*

Maximum value is device dependent

Modbus function codes The second parameter in each Modbus message is the function code. This defines the message type and the type of action required by the slave. The parameter contains one byte of information. In Modbus/ASCII this is coded with two hexadecimal characters, in Modbus/RTU one byte is used. Valid function codes are in the range 1..255. Not all Modbus devices recognize the same set of function codes. The most common codes are discussed here. Normally, when a Modbus slave answers a response, it uses the same function code as in the request. However, when an error is detected, the highest bit of the function code is turned on. In that way the master can see the difference between success and failure responses. Common Modbus function codes Code 01 02 03 04 05 06 07 Description Read coil status Read input status Read holding registers Read input registers Force single coil Preset single register Read exception status

15 16 17 Function 01: Read coil status

Force multiple coils Preset multiple registers Report slave ID

In Modbus language, a coil is a discrete output value. Modbus function 01 can be used to read the status of such an output. It is only possible to query one device at a time. Broadcast addressing is not supported with this Modbus function. The function can be used to request the status of various coils at once. This is done by defining an output range in the data field of the message. Function 01 query structure Byte 1 2 3 4 5 6 Value 1...247 1 0...255 0...255 0...255 0...255 Description Slave device address Function code Starting address, high byte Starting address, low byte Number of coils, high byte Number of coils, low byte Error check value

7(...8) LRC/CRC

When receiving a Modbus query message with function 01, the slave collects the necessary output values and constructs an answer message. The length of this message is dependent on the number of values that have to be returned. In general, when N values are requested, a number of ((N+7) mod 8) bytes are necessary to store these values. The actual number of databytes in the datablock is put in the first byte of the data field. Therefore the general structure of an answer to a Modbus function 01 query is: Function 01 answer structure Byte 1 2 3 4...N+3 Value 1...247 1 0...255 0...255 Description Slave device address Function code Number of data bytes N Bit pattern of coil values Error check value

N+4(...N+5) LRC/CRC Function 02: Read input status

Reading input values with Modbus is done in the same way as reading the status of coils. The only difference is that for inputs Modbus function 02 is used. Broadcast addressing mode is not

supported. You can only query the value of inputs of one device at a time. Like with coils, the address of the first input, and the number of inputs to read must be put in the data field of the query message. Inputs on devices start numbering at 10001. This address value is equivalent to address 0 in the Modbus message. Function 02 query structure Byte 1 2 3 4 5 6 Value 1...247 2 0...255 0...255 0...255 0...255 Description Slave device address Function code Starting address, high byte Starting address, low byte Number of inputs, high byte Number of inputs, low byte Error check value

7(...8) LRC/CRC

After receiving a query message with Modbus function 02, the slave puts the requested input values in a message structure and sends this message back to the Modbus master. The length of the message depends on the number of input values returned. This causes the length of the output message to vary. The number of databytes in the data field that contain the input values is passed as the first byte in the data field. Each Modbus answering message has the following general structure. Function 02 answer structure Byte 1 2 3 4...N+3 Value 1...247 2 0...255 0...255 Description Slave device address Function code Number of data bytes N Bit pattern of input values Error check value

N+4(...N+5) LRC/CRC Function 03: Read holding registers

Internal values in a Modbus device are stored in holding registers. These registers are two bytes wide and can be used for various purposes. Some registers contain configuration parameters where others are used to return measured values (temperatures etc.) to a host. Registers in a Modbus compatible device start counting at 40001. They are addressed in the Modbus message structure with addresses starting at 0. Modbus function 03 is used to request one or more holding register values from a device. Only one slave device can be addressed in a single query. Broadcast queries with function 03 are not supported.

Function 03 query structure Byte 1 2 3 4 5 6 Value 1...247 3 0...255 0...255 0...255 0...255 Description Slave device address Function code Starting address, high byte Starting address, low byte Number of registers, high byte Number of registers, low byte Error check value

7(...8) LRC/CRC

After processing the query, the Modbus slave returns the 16 bit values of the requested holding registers. Because of the size of the holding registers, every register is coded with two bytes in the answering message. The first data byte contains the high byte, and the second the low byte of the register. The Modbus answer message starts with the slave device address and the function code 03. The next byte is the number of data bytes that follow. This value is two times the number of registers returned. An error check is appended for the host to check if a communication error occured.

You might also like