Modbus是一種串行通信協議,是工業(yè)領域通信協議的業(yè)界標準,是工業(yè)電子設備之間常用的連接方式。最近在工作中需要上位機python程序和PLC做通訊,就測試了下使用modbus tcp 通訊。
? ? ? ? 目前實際測試結果是與西門子PLC/信捷PLC都可以正常通訊使用,但是看到網上說可以傳輸小數、負數,當然也包含整數了,其實在實踐后發(fā)現只有整數才可以精確傳輸(有范圍限制),由于modbus 本身缺陷,小數傳輸會存在問題。我測試的python做客戶端,PLC作服務端。
1. python安裝modbus_tk包
pip install modbus_tk
2. 借助大神的程序運行
import modbus_tk
import modbus_tk.defines as cst
import modbus_tk.modbus_tcp as modbus_tcp
if __name__ == "__main__":
try:
# 實際使用PLC地址
master = modbus_tcp.TcpMaster(host="192.168.12.15")
master.set_timeout(5.0)
# 寫整數
"""
WRITE_MULTIPLE_REGISTERS 寫多寄存器
WRITE_SINGLE_REGISTER 寫單個寄存器
"""
# master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 300, output_value=[1, 2, 3, 4])
master.execute(1, cst.WRITE_SINGLE_REGISTER, 300, output_value=25)
# 讀整數
result_int = master.execute(1, cst.READ_HOLDING_REGISTERS, 300, 1)
print(result_int)
# 寫小數
# master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 5, output_value=[3.14, -6.28], data_format='<ff')
# # 讀小數
# result_float = master.execute(1, cst.READ_HOLDING_REGISTERS, 500, 4, data_format='<ff')
# print(result_float)
except modbus_tk.modbus.ModbusError as e:
print("%s- Code=%d" % (e, e.get_exception_code()))
運行結果如下:
?
?大神連接:Python 基于modbus tcp 協議 實現與plc通信文章來源:http://www.zghlxwxcb.cn/news/detail-584455.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-584455.html
到了這里,關于python 與PLC 基于 modbus tcp 協議通訊的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!