Search code examples
pythonmodbusmodbus-tk

How to set up simple slave and master with modbus-tk RTU (Python)


I wanted to set up a communication between a Raspberry PI (slave) and my PC (Master) through Modbus protocol. Currently, I'm using modbus-tk (python) to set up the communication protocol.

The issue is that the Master was not able to read the register from the slave. May I know what is wrong with my code? I'm very confused.

The error that I obtained from Slave was:
Handle request failed: Invalid CRC in request or Request length is invalid

The error that I obtained from Master was:
ModbusInvalidResponseError

Note: the purpose is to use the Master to read the data from the slave.

Here is the code for the slave:

import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
import serial
import time  

modbusServ = modbus_rtu.RtuServer(serial.Serial('/dev/ttyUSB0'),baudrate= 19200,
                 bytesize=8, parity='N', stopbits=1, xonxoff=0)
print("start")

modbusServ.start()

slave_1 = modbus_tk.modbus.Slave(1)

slave_1.add_block ( "1", modbus_tk.defines.HOLDING_REGISTERS, 1, 5)

aa= (1,2,3,4,5) # data in the register

while True:

    slave_1.set_values ("1", 1, aa)
    time.sleep(0.5)   

Here is the code for the Master:

import sys
import serial

#add logging capability
import logging

import modbus_tk.modbus
import modbus_tk.defines as cst
import modbus_tk.modbus_rtu as modbus_rtu
logger = modbus_tk.utils.create_logger("console")

while True:          
            master = modbus_rtu.RtuMaster(serial.Serial('COM3', baudrate= 19200, bytesize=8, parity='N', stopbits=1))
            master.open
            master.set_timeout(3)
            master.set_verbose(True)
            logger.info("connected")
            logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 1, 5))

Here is the datasheet and a picture of the USB-to-rs485 device that I am using to connect my Raspberry Pi and my PC:
https://www.enika.cz/data/files/produkty/komponenty/mereni-a-regulace/UT-890A%20User%20manual.pdf

https://c.76.my/Malaysia/ut-890-usb-to-rs485-converter-belco-1605-07-belco@2569.jpg

Thank you very very much for the help.


Solution

  • The master does not read from the COM Port even though the slave is connected across that port. Reading is done using ttyUSB0 instead of COM3. That should help you read the data.