How to Read Modbus Register: Simple Guide with Example
To read a Modbus register, use the
Read Holding Registers function (function code 0x03) by sending a request with the device address, starting register address, and number of registers to read. The device responds with the register values in a data frame you can decode.Syntax
The basic syntax to read a Modbus register involves sending a request frame with these parts:
- Device Address: The ID of the Modbus device you want to read from.
- Function Code: Use
0x03for reading holding registers. - Starting Register Address: The first register number to read.
- Number of Registers: How many registers you want to read.
- CRC Checksum: Error-checking code to ensure data integrity.
The device replies with the requested register values in a similar frame.
plaintext
Request Frame Format: [Device Address][Function Code][Starting Register High][Starting Register Low][Quantity High][Quantity Low][CRC Low][CRC High]
Example
This example shows how to read 2 registers starting at address 100 from a device with address 1 using Python and the pymodbus library.
python
from pymodbus.client.sync import ModbusTcpClient # Connect to Modbus TCP device at IP 192.168.1.10, port 502 client = ModbusTcpClient('192.168.1.10', port=502) client.connect() # Read 2 holding registers starting at address 100 result = client.read_holding_registers(100, 2, unit=1) if not result.isError(): print('Register values:', result.registers) else: print('Failed to read registers') client.close()
Output
Register values: [1234, 5678]
Common Pitfalls
- Wrong Register Address: Modbus register addresses often start at 0 or 1 depending on the device; check your device manual.
- Incorrect Function Code: Use
0x03for holding registers, not input registers or coils. - Unit ID Mismatch: The device address (unit ID) must match the target device.
- Connection Issues: Ensure network or serial connection is stable and configured correctly.
- Ignoring Response Errors: Always check if the response contains errors before using data.
python
Wrong way: result = client.read_holding_registers(101, 2, unit=1) # Off by one address Right way: result = client.read_holding_registers(100, 2, unit=1) # Correct address
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| Device Address | ID of the Modbus device | 1 |
| Function Code | Operation to perform | 0x03 (Read Holding Registers) |
| Starting Register | First register to read | 100 |
| Quantity | Number of registers to read | 2 |
| CRC | Error check code | Calculated automatically |
Key Takeaways
Use function code 0x03 to read holding registers from a Modbus device.
Always verify the starting register address matches your device's documentation.
Check the response for errors before using the register data.
Ensure the device address (unit ID) is correct in your request.
Use libraries like pymodbus for easier Modbus communication in code.