OpenPLC_v3 use libmodbus so I thought it could be useful to do some prototyping in Python for this library.
Lets assume you like to use libmodbus in a project and need to test some ideas. Instead of using C we will use Python.
For this to work on Windows platform we need a compiled shared library of modbus.dll
If we use Linux or macOS we need to download the libmodbus and compile it.
To make Python able to use libmodbus we need to install 2 package for Python.
-> pip install pylibmodbus cffi
To be able to find the modbus.dll we need to setup library path system environment variables so Python could find the .dll file.
On Linux or macOS I guess its enough to copy the shared library to /usr/local/lib
If we do not use library path we need to edit
modbus_core.py that you find in site-package directory and pylibmodbus.
When you have setup above correctly you could now use libmodbus with Python.
Here is example.
import pylibmodbus
# Connect to Modbus server (replace with your device IP)
modbus = pylibmodbus.ModbusTcp("127.0.0.1", 502) # Modbus TCP example
modbus.connect()
# ---- Reading Functions ----
# Read 10 Holding Registers from address 0
holding_registers = modbus.read_registers(0, 10)
print("Holding Registers:", holding_registers)
# Read 10 Input Registers from address 0
input_registers = modbus.read_input_registers(0, 10)
print("Input Registers:", input_registers)
# Read 10 Coils from address 0
coils = modbus.read_bits(0, 10) # Discrete Coils
print("Coils:", coils)
# Read 10 Discrete Inputs from address 0
discrete_inputs = modbus.read_input_bits(0, 10)
print("Discrete Inputs:", discrete_inputs)
# ---- Writing Functions ----
# Write a single Coil (ON)
modbus.write_bit(5, 1) # Set coil at address 5 to ON
# Write a single Register
modbus.write_register(5, 1234) # Set register at address 5 to 1234
# Write multiple Coils (ON/OFF)
modbus.write_bits(0, 10, [1, 0, 1, 1, 0, 0, 1, 1, 1, 0]) # Writes 10 coil states at address 0
# Write multiple Holding Registers
modbus.write_registers(0, [100, 200, 300, 400, 500]) # Set multiple register values
# ---- Debugging & Cleanup ----
modbus.close() # Close connection
The print statement for the read may look little strange its C-Style array. To convert it to Python list we could do for ex. holding_registers
print("Holding Registers:", list(holding_registers)) and we could do the same for all the other C-Style array.