Thread Content
The Modbus protocol is a universal language used in electronic controllers. Through this protocol, controllers can communicate with each other, as well as with other devices via a network (such as Ethernet). It has become a universal industrial standard. With it, control devices produced by different manufacturers can be connected into an industrial network for centralized monitoring. This protocol defines the message structures that a controller can recognize and use, regardless of the network through which communication takes place. It describes the process by which a controller requests access to other devices, how responses are sent in response to requests from those devices, and how errors are detected and recorded. It establishes a common format for the structure and content of message domains. When communicating over a Modbus network, this protocol dictates that each controller must know its device address, identify messages sent by address, and determine what action to take. If a response is required, the controller will generate feedback information and send it using the Modbus protocol. On other networks, messages containing the Modbus protocol are converted into frame or packet structures used on that network. This transformation also expands the methods for resolving node addresses, routing paths, and error detection based on specific networks. 1. Transmission over a Modbus network: The standard Modbus interface uses an RS-232C compatible serial interface, which defines the pins of the connection port, the cables, the signal bits, the transmission baud rate, and parity checking. The controller can be connected directly or via a modem network. Controller communication uses master-slave technology, meaning only one device (the master device) can initiate transmission (queries). Other devices (slave devices) respond accordingly to the data provided by the master device based on its queries. Typical master devices: hosts and programmable instruments. Typical slave device: Programmable controller. The master device can communicate with slave devices individually, as well as communicate with all slave devices in a broadcast manner. If communicating individually, the device returns a message in response; if the query is sent in a broadcast manner, no response is given. The Modbus protocol defines the format for master device queries: device (or broadcast) address, function code, all data to be sent, and an error detection field. The device response message is also composed of the Modbus protocol, including the field indicating the action to be taken, any data to be returned, and an error detection field. If an error occurs during message reception, or if the slave device is unable to execute its commands, it will generate an error message and send it as a response. 2. Transmission over other types of networks: On other networks, the controllers use peer-to-peer communication techniques, allowing any controller to initiate communication with other controllers. In this way, during a separate communication process, the controller can act as either a master device or a slave device. The multiple internal channels provided can allow transmission processes to occur simultaneously. In terms of messaging, the Modbus protocol still adopts a master-slave principle, although the network communication method is \"peer-to-peer\". If a controller sends a message, it acts merely as the master device and expects a response from the slave devices. Similarly, when the controller receives a message, it will create a response format from the device and send it back to the sending controller. 3. Query-Response Cycle (1) Query: The function code in the query message indicates which function the selected slave device is to perform. The data segment contains any additional information that the device needs to carry out its functions. For example, function code 03 requires the slave device to read the hold registers and return their contents. The data segment must contain the information to be communicated to the slave device: from which register reading should begin and how many registers need to be read. The error detection field provides the slave device with a way to verify whether the message content is correct. (2) Response: If a normal response is generated by the device, the function code in the response message is the response to the function code in the query message. The data segment includes data collected from the device: such as register values or status. If an error occurs, the function code will be modified to indicate that the response message is incorrect, while the data segment contains code describing this error information. The error detection field allows the master device to confirm whether the message content is available. II. Two Transmission Modes: The controller can be set to either of the two transmission modes (ASCII or RTU) for standard Modbus network communication. The user selects the desired mode, including serial communication parameters (baud rate, parity, etc.). When configuring each controller, all devices on a Modbus network must choose the same transmission mode and serial parameters. ASCII mode: Address, Function Code, Number of Data Items, Data1 ... Datan, LRC High Byte, LRC Low Byte, Enter, Line Feed. RTU mode: Address, Function Code, Number of Data Items, Data1 ... Datan, CRC High Byte, CRC Low Byte. The selected ASCII or RTU mode is applicable only to standard Modbus networks; it defines each bit of the message segments transmitted sequentially over these networks, as well as how information is packaged into message fields and how it is decoded. On other networks (such as MAP and Modbus Plus), Modbus messages are converted into frames that are independent of serial transmission. 1. ASCII mode: When the controller is set to communicate over a Modbus network in ASCII (American Standard Code for Information Interchange) mode, each 8-bit byte in the message is sent as two ASCII characters. The main advantage of this method is that the time interval between character transmissions can reach 1 second without any errors occurring. Code system · Hexadecimal, ASCII characters 0...9, A...F · Each ASCII character in the message consists of one hexadecimal character. Bits per byte · 1 start bit · 7 data bits, with the least significant bit sent first · 1 parity bit (absent if no parity checking is used) · 1 stop bit (when parity checking is used), 2 bits (when no parity checking is used). Error detection method · LRC (Longitudinal Redundancy Check). 2. RTU mode: When the controller is set to communicate over a Modbus network in RTU (Remote Terminal Unit) mode, each 8-bit byte in the message contains two 4-bit hexadecimal characters. The main advantage of this method is that, at the same baud rate, it can transmit more data than the ASCII method. Code system · 8-bit binary, hexadecimal digits 0...9, A...F · Each 8-bit field in the message consists of two hexadecimal characters per byte · 1 start bit · 8 data bits, with the least significant bit sent first · 1 parity bit (absent if no parity checking is used) · 1 stop bit (when parity checking is used), 2 bits (when no parity checking is used) Error detection field · CRC (Cyclic Redundancy Check) III. Modbus message frame In both transmission modes (ASCII or RTU), the transmitting device converts the Modbus message into a frame with a start and end point, which allows the receiving device to begin processing at the start of the message, read the address assignment information, determine which device has been selected (in broadcast mode, the message is sent to all devices), and know when the message is complete. Partial messages can also be detected, and errors can be set as the return result. 1. ASCII frame: Uses ASCII mode; the message begins with a colon character (:), which has an ASCII code of 3AH, and ends with newline characters (ASCII codes 0DH, 0AH). The transmission characters that can be used in other domains are hexadecimal 0...9, A...F. Devices on the network continuously scan for the “:” character; when a colon is received, each device decodes the next field (the address field) to determine whether it is intended for itself. The maximum time interval between characters in a message cannot exceed 1 second; otherwise, the receiving device will consider it a transmission error. A typical message frame is as follows: start bit, device address, function code, data, LRC checksum, end symbol – 1 character, 2 characters, 2 characters, n characters, 2 characters, 2 characters. Figure 2: ASCII message frame. 2. RTU frame: In RTU mode, message transmission must begin with a pause of at least 3.5 character times. At the network baud rate, diverse character times are the easiest to achieve (as shown as T1-T2-T3-T4 in the figure below). The first field in the transmission is the device address. The transfer characters that can be used are hexadecimal 0...9, A...F. Network devices continuously monitor the network bus, including during pause intervals. When the first domain (address domain) is received, each device decodes it to determine whether it is intended for itself. After the last transmitted character, a pause of at least 3.5 character times marks the end of the message. A new message can start after this pause. The entire message frame must be transmitted as a continuous stream. If there is a pause of more than 1.5 character times before the frame is completed, the receiving device will refresh the incomplete message and assume that the next byte is the address field of a new message. Similarly, if a new message starts within less than 3.5 characters of the previous message, the receiving device will consider it to be a continuation of the preceding message. This will result in an error, because the value in the final CRC field cannot be correct. A typical message frame is as follows: start bit, device address, function code, data, CRC checksum, end bits – T1-T2-T3-T4, 8Bit, 8Bit, n bytes of 8Bit each, 16Bit. T1-T2-T3-T4 Figure 3: RTU message frame. 3. Address field: The address field of a message frame consists of two characters (ASCII) or 8Bit values (RTU). Possible slave device addresses are 0...247 (decimal). The address range for a single device is 1...247. The master device selects the slave device by placing the address of the slave device to be contacted in the address field of the message. When a slave device sends a response message, it includes its own address in the address field of the response, so that the master device knows which device has sent the response. Address 0 is used as a broadcast address so that all slave devices can recognize it. When the Modbus protocol is used on higher-level networks, broadcasting may not be allowed or may be replaced by other methods. 4. How to handle the functional code field: The functional code field in the function domain message frame contains two characters (ASCII) or 8 bits (RTU). The possible code range is 1...255 in decimal. Of course, some code is applicable to all controllers, some is designed for a specific controller, and some is reserved for future use. When a message is sent from the master device to the slave device, the function code field indicates what actions the slave device needs to perform. For example, reading the status of input switches, reading the data contained in a set of registers, reading the diagnostic status of a slave device, and allowing the loading, recording, and verification of programs within the slave device. When the device responds, it uses the function code field to indicate whether it is a normal response (without errors) or if some error has occurred (referred to as an abnormal response). For a normal response, the device only responds with the corresponding function code. In response to an exception, the device returns a code equivalent to a normal code, but the most important value is logic 1. For example, if a message sent from the master device to the slave device requests the reading of a set of hold registers, the resulting function code will be: 0 0 0 0 0 0 1 1 (hexadecimal 03H). As a normal response, the slave device will simply reply with the same function code. In response to an error, it returns: 1 0 0 0 0 0 1 1 (hexadecimal 83H). Apart from the function code being modified due to the error, the slave device includes a unique code in the data field of the response message, which indicates what error has occurred. After the master device application receives a response to an objection, the typical approach is to resend the message, or to diagnose the message sent to the slave device and report it to the operator. 5. Data field: The data field is composed of two sets of hexadecimal numbers, ranging from 00...FF. Depending on the network transmission mode, this can be composed of a pair of ASCII characters or of one RTU character. The data field of the message sent from the master device to the slave device contains additional information: the slave device must be used to carry out the actions defined by the function code. This includes things such as discontinuous register addresses, the number of items to be processed, and the actual number of data bytes in a field. For example, if the master device needs to read a set of hold registers from the slave device (function code 03), the data field specifies the starting register as well as the number of registers to be read. If the master device writes to a set of slave device registers (function code 10 in hexadecimal), the data field specifies the starting register for writing, the number of registers to be written to, the number of data bytes in that field, and the data to be written into the registers. If no error occurs, the data field returned by the slave device contains the requested data. If an error occurs, this field contains an error code that the host device application can use to determine the next action to take. In certain messages, the data field can be absent (0 length). For example, the master device requires the slave device to respond with a communication event record (function code 0B in hexadecimal), and the slave device does not need any additional information. 6. Error detection field: The standard Modbus network has two error detection methods. The content of the error detection field depends on the selected detection method. When ASCII mode is selected for the character frame, the error detection field consists of two ASCII characters. This is calculated for the message content using the LRC (Longitudinal Redundancy Check) method, and does not include the leading colon and line feed characters. The LRC character is appended before the newline character. When the RTU mode is used for character frames, the error detection field contains a 16-bit value (represented by two 8-bit characters). The content of the error detection field is obtained by applying a cyclic redundancy check method to the message content. The CRC field is appended at the end of the message, with the lower byte followed by the higher byte when added. Therefore, the highest byte of the CRC is the last byte of the transmitted message. 7. Sequential transmission of characters: When messages are transmitted over a standard Modbus network, each character or byte is sent in the following order (from left to right): least significant bit…most significant bit. When using an ASCII character frame, the sequence of bits is as follows: parity bit, start bit, 1, 2, 3, 4, 5, 6, 7; parity bit, stop bit. When no parity checking is used, the sequence is: start bit, 1, 2, 3, 4, 5, 6, 7, stop bit, stop bit. Figure 4. Bit order (ASCII). When using an RTU character frame, the bit sequence is: parity bit, start bit, 1, 2, 3, 4, 5, 6, 7, 8; parity bit, stop bit. When no parity checking is used, the sequence is: start bit, 1, 2, 3, 4, 5, 6, 7, 8, stop bit, stop bit. Figure 4. Bit order (RTU). IV. Error detection methods: The standard Modbus serial network uses two error detection methods. Parity can be used for each character, while frame detection (LRC or CRC) is applied to the entire message. They are all generated by the master device before message transmission, while the slave devices detect each character and the entire message frame during reception. The user must configure a predefined timeout interval for the master device; this interval must be long enough to allow any slave device to respond properly. If a transmission error is detected from the device, the message will not be received, nor will a response be sent to the master device. In this way, the timeout event will trigger the main device to handle the error. Sending to an address of a non-existent slave device also causes a timeout. 1. Parity check: Users can configure the controller to use odd or even parity, or no parity check. This will determine how the parity bits are set in each character. If odd or even parity is specified, the number of \"1\"s is counted as part of the number of bits per character (7 data bits in ASCII mode, 8 data bits in RTU mode). For example, an RTU character frame contains the following 8 data bits: 1 1 0 0 0 1 0 1, and the total number of ’1’s is 4. If even parity is used, the parity bit of the frame will be 0, so the total number of \"1\"s will still be 4. If odd parity is used, the parity bit of the frame will be 1, resulting in a total of 5 ones. If no parity bits are specified, there are no parity bits during transmission, and no parity checking is performed. It is inserted into the character frame to be transmitted in place of an additional stop bit. 2. LRC detection uses ASCII mode, and the message includes an error detection field based on the LRC method. The LRC field examines the content in the message field, excluding the starting colon and the ending newline characters. The LRC field is a byte that contains an 8-bit binary value. The LRC value is calculated by the transmitting device and placed in the message frame. The receiving device calculates the LRC while receiving the message and compares it with the value in the LRC field of the received message; if the two values do not match, it indicates an error. The LRC method involves continuously adding the 8-bit bytes in a message, discarding any carry values. The simple LRC function is as follows: static unsigned char LRC(auchMsg,usDataLen) { unsigned char *auchMsg ; /* The message to be processed */ unsigned short usDataLen ; /* Number of bytes to be processed by LRC */ { unsigned char uchLRC = 0 ; /* Initialize the LRC byte */ while (usDataLen--) { uchLRC += *auchMsg++; /* Accumulate values */ } return ((unsigned char)(-((char)_uchLRC))); } 3. CRC detection: In RTU mode, the message includes an error detection field based on the CRC method. The CRC field checks the content of the entire message. The CRC field is two bytes long and contains a 16-bit binary value. It is calculated by the transmission device and added to the message. The receiving device recalculates the CRC of the received message and compares it with the value in the CRC field; if the two values differ, there is an error. CRC involves first loading a 16-bit register filled with all ‘1’ values, and then invoking a procedure to process each consecutive 8-bit byte in the message using the value in the current register. Only the 8-bit data within each character is valid for CRC; the start bit, stop bit, and parity bit are not valid. During CRC generation, each 8-bit character is individually ORed with the contents of the register; the result is shifted toward the least significant bit, with the most significant bit filled with 0. The LSB is extracted for detection; if the LSB is 1, the register is processed separately using a preset value or similar, whereas if the LSB is 0, no action is taken. The entire process needs to be repeated 8 times. After the last one (the 8th) is processed, the next 8-byte sequence is again XORed individually with the current value of the register. The value in the final register is the CRC value after all bytes in the message have been processed. When CRC is added to a message, the lower byte is added first, followed by the higher byte. The simple CRC function is as follows: unsigned short CRC16(puchMsg, usDataLen) unsigned char *puchMsg ; /* Message for which CRC verification is to be performed */ unsigned short usDataLen ; /* Number of bytes in the message */ { unsigned char uchCRCHi = 0xFF ; /* Initialize the upper CRC byte */ unsigned char uchCRCLo = 0xFF ; /* Initialize the lower CRC byte */ unsigned uIndex ; /* Index used in the CRC calculation loop */ while (usDataLen--) /* Process each byte of the message */ { uIndex = uchCRCHi ^ *puchMsg++; /* Calculate the CRC value */ uchCRCHi = uchCRCLo ^ uchCRCHi; } return (uchCRCHi