SoFunction
Updated on 2024-10-30

Python implementation of ModBusRTU client-side approach

The python implementation of a ModBusRTU client based on serial communication is a simple thing to do with the pymodbus module.

I. About ModbusRTU

1, what is ModbusRTU

Modbus RTU (Remote Terminal Unit) is a serial communications protocol used to transfer data in industrial automation systems. It is a variant of the Modbus protocol that uses binary encoding and typically operates on the RS-485 serial communications physical layer.

The Modbus RTU protocol allows devices (e.g., sensors, actuators, controllers, etc.) to communicate with a host device such as a computer, PLC (Programmable Logic Controller), etc., via a serial port (usually RS-485).

The communication can include sensor measurement data, control commands and so on. It is a common industrial communication protocol that is widely used in automation, monitoring, data acquisition and other fields.

Features of the Modbus RTU protocol include:

(1) Simplicity: The Modbus RTU protocol is relatively simple, easy to implement and understand, and suitable for systems of all sizes.

(2) Real-time: Modbus RTU communication typically has low latency and is suitable for application scenarios with high real-time requirements.

(3) Flexibility: Multiple devices can be connected through the serial port to realize point-to-point or multi-point communication.

(4) Reliability: The Modbus RTU protocol provides a CRC (Cyclic Redundancy Check) checksum for detecting errors in communication data.

(5) Widely used: Due to its simplicity and reliability, the Modbus RTU protocol is widely used in industrial automation, especially in the modernization of older systems.

In Modbus RTU communication, devices are recognized by their addresses and use different function codes to perform different operations, such as reading data, writing data, etc. The communication content is transmitted in binary form, so serial communication, e.g. RS-485, is usually used at the hardware level.

In a nutshell, Modbus RTU is a communication protocol used in industrial automation that provides a simple, real-time and reliable way of exchanging data, making it easy for various devices to communicate with the control system.

2、ModbusRTU message parsing

Roughly as depicted in the figure above, in Modbus RTU communication, communication data is transmitted in binary form through the serial port.

The structure of a Modbus RTU frame is as follows:

(1) Start of Frame: The beginning of a frame is marked by a period of silence (no communication) called a "gap".

(2) Device address (Address): 1 byte indicating the address of the Modbus device.

(3) Function Code (Function Code): 1 byte indicating the type of Modbus operation (read, write, etc.).

(4) Data: variable length, contains the parameters of the operation (register address, number, etc.).

(5) CRC Check (Cyclic Redundancy Check): 2 bytes for detecting errors in data transmission.

(6) End of Frame: The end of a frame is marked by a fixed time interval called a "gap".

3. How many CRC algorithms are there?

CRC (Cyclic Redundancy Check) is an error detection algorithm with many different variants and polynomials.

Here are some common CRC algorithms and their polynomials:

These are just some common CRC algorithms, in fact, CRC algorithms can choose different polynomials as needed. Each polynomial has different performance characteristics for different application scenarios. The selection of appropriate CRC algorithm usually depends on the characteristics of data transmission and the need for error detection.

4、Which CRC to choose for ModbusRTU?

The Modbus RTU protocol typically uses the Cyclic Redundancy Check with 16-bit polynomial, also known as the Modbus CRC.The CRC-16 check uses a 16-bit polynomial, specifically x^16 + x^15 + x^2 + 1.

In Modbus RTU communication, CRC-16 checksum is the standard checksum method, which is used to detect whether an error has occurred during the transmission of data. The reasons for choosing CRC-16 include its good performance and wide range of applications. It is able to detect most single-bit, double-bit and other common transmission errors.

Overall, CRC-16 is a commonly used checksum in the Modbus RTU protocol because it provides a high level of error detection and is suitable for most application scenarios.

5. CRC-calculated websites

CRC Online Calculation

(1) Example of Modbus RTU calculation

Note: The following 20EA may be EA20 in the message due to the presence of major and minor end sequences.

II. A Demo

1. Sample program

from  import ModbusSerialClient
 
# Configure serial port parameters
COM_PORT = '/dev/ttyS0'  # Serial port number (Windows systems may be COM1, COM2, etc.)
BAUD_RATE = 9600  # Baud rate
PARITY = 'N'  # Parity ('N' for no parity, 'E' for even parity, 'O' for odd parity)
STOP_BITS = 1  # Stop bits
DATA_BITS = 8  # Data bits
 
# Create Modbus RTU clients
client = ModbusSerialClient(method='rtu', port=COM_PORT, baudrate=BAUD_RATE,
                            parity=PARITY, stopbits=STOP_BITS, bytesize=DATA_BITS)
 
# Connect to Modbus devices
if ():
    print("Device connected successfully.")
    
    # Read the value of the holding register (example address is 1, register address is 0, read a register)
    response = client.read_holding_registers(address=0, count=1, slave=1)
    if ():
        print("Read failed:", response)
    else:
        print("Holding register value:", )
 
    # Close the connection
    ()
else:
    print("Device connection failed.")

2. Are ModbusRTU and ModbusTCP function codes the same?

Modbus RTU and Modbus TCP are both variants of the MODBUS protocol, and as such, ModbusRTU and ModbusTCP use theSame function code

In fact, the function code definitions for the Modbus communication protocol are universal, and the meaning and usage of the function codes are the same whether you are using serial communication in RTU (Remote Terminal Unit) mode or using ModbusTCP on a TCP/IP network.

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.