יום רביעי, 1 במאי 2019

Modbus connection from PC to Unitronics

As a nub in Python I struggled quit a while finding the way to get data from Unitronics PLC to my computer. all of our technicians at work where abroad and i did not want to bother them . nun of us worked with python before.
I tried opc and then stumbled on modbus-tk (tool kit) python library.
so here is my solution.

on the PLC side you need to set the PLC to allow Modbus connection like so:

set plc name, card socket (use socket 2 port 502 as it is the default and unitronics asked you to :).
set the network id and remember it for the python code this is the slave number.
rung 2 sets the Modbus scan to work always so you will refresh values every PLC cycle.

on the python side :
install modbus_tk : pip install modbus_tk
reading values works with this  code


import modbus_tk.defines as cst
import modbus_tk.modbus as modbus
import modbus_tk.modbus_tcp as modbus_tcp

master = modbus_tcp.TcpMaster(host='172.21.2.183', port=502, timeout_in_sec=5.0)
master.open
actual_bytes = master.execute(slave=1, function_code=cst.READ_COILS, starting_address=1, quantity_of_x=25)
print("actual_bytes =", actual_bytes)

master.close

this code reads MI:1 to MI:26

Hope in the future I will have time to explain how to read other data.


אין תגובות:

 
Locations of visitors to this page