如果你的开发环境是python3及以上
pip3 install modbus_tk
否则使用
pip install modbus_tk
直接贴Python代码
系统:win10
IDE:pycharm + Qtdesigner
目标:实现简单modbus通信
import serial
import serial.tools.list_ports
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
PORT = 'COM10'
def main():
try:
master= modbus_rtu.RtuMaster(serial.Serial(port=PORT,baudrate=115200,bytesize=8,parity='O',stopbits=1,xonxoff=0)
)
master.set_timeout(5)
master.set_verbose(True)
print('connected')
print(master.execute(35,cst.READ_HOLDING_REGISTERS,102,10))#slaveAddr funCode startAddr regNum
except modbus_tk.modbus.ModbusError as exc:
print('err')
if __name__ == '__main__':
main()
摘出几个要点:
-
serial.Serial(port=PORT,baudrate=115200,bytesize=8,parity=‘O’,stopbits=1,xonxoff=0)
port:对应设备的端口号,win下是COMn,linux下是/dev/ttyp5n
bytesize:通信数据长度,可选FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8),常用的还是8,我便没有尝试其他的
parity:奇偶校验,可选PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = ‘N’, ‘E’, ‘O’, ‘M’, ‘S’。不建议不校验,我选择ODD校验
stopbits:注意这里注意!!!MB协议要求的,若无parity,停止位应该是2位。我已经使用奇校验,故而停止位是1位
xonoff:流控制没用 -
master.execute(35,cst.READ_HOLDING_REGISTERS,102,10))
#slaveAddr : 35(0x23)
#funCode : cst.READ_HOLDING_REGISTERS (0x03)不要自己写0x03,程序不认
#startAddr : 102(0x66)
#regNum : 10(0x0A) -
pycharm实现的是主机,从机是飞思卡尔K60,移植了freeModbus,具体细节可参考
https://blog.csdn.net/ysgjiangsu/article/details/81512310 -
调试建议,从机先用Modbus Poll调通,再写上位机,以便定位问题。此前,从机用Modbus Poll通信30000+次,0错误,结果如下:
而我用Python写的上位机,调试结果如下:
D:\Python35\python.exe "D:\Program Files\JetBrains\PyCharm 2018.3\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 2984 --file F:/研究生/咖盟/AMP/prj/pythonserial/test1.py
pydev debugger: process 14416 is connecting
Connected to pydev debugger (build 183.4284.139)
connected
(4370, 4884, 5398, 5912, 6426, 6940, 7454, 7968, 8482, 8996)
Process finished with exit code -1
- 下一篇写个界面友好的QT吧,方便些
---------------------------------------------------本篇结束-------------------------------------------