Modbus Simulation between two PCs using a USB connection with libmodbus or pymodbus

819 views Asked by At

I am trying to connect to PCs (one master one slave) that will communicate with each other using the modbus protocol, I wanna use pymodbus (Python) or libmodbus (C++) to make this but I am relatively new to Modbus therefore I am not sure where to start. I have build (I think) a Modbus server with pymodbusTCP but I am not sure how to communicate with another PC using pymodbusTCP.

I have written the below given code:

#!/bin/python
import sys
sys.path.append("..")
from pyModbusTCP.server import ModbusServer, DataBank
from time import sleep
from random import uniform

# Create an instance of ModbusServer
server = ModbusServer("127.0.0.1", 12345, no_block=True)

try:
    print("Start server ...")
    server.start()
    print("Server is online")
    while True:
        continue    

except:
    print("Shutdown server ...")
    server.stop()
    print("Server is offline")

and when I connect from my localhost (as slave), I am able to connect.

>>> from pyModbusTCP.client import ModbusClient
>>> 
>>> client = ModbusClient(host="127.0.0.1", port=12345)
>>> client.open()
True
>>>

What do I have to do to connect two PCs one working as a master and the other one as a slave?

How can I send write to coils to make this happen?

Any help would be gladly appreciated.

NOTE: The environment is Ubuntu 20.04

1

There are 1 answers

0
Marcos G. On

You are on the right track but you are missing a couple of things:

-For the server, you need to define and initialize the Modbus registers and coils.

-On the client, you need to define queries to read those registers and/or coils.

Foy pymodbus, the best way to start is to look at the examples. Download, edit the port (by default it is 5020) and run the server example from the GitHub repo and run some queries from your client with:

rr = client.read_coils(1, 1, unit=0x01)
print(rr.registers)

You can find other kinds of queries on any of the async client examples.

Once you have the client-server connection up and running you can look at the details of the server, and maybe define more slaves with different IDs or setup registers with more meaningful values.

After you get some proficiency with pymodbus, libmodbus should be pretty straightforward.