modbus_tk模块详细使用

呼延钱明
2023-12-01

源码:Github

modbus_tk模块 通过modbus-RTU 读取地址,调用后返回反馈数值和故障信息。

modbus_tk模块安装

  pip install pymodbus_tk

Demo

# -*- coding: utf_8 -*-


import serial
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu

def mod(PORT="com10"):
    #print("加载modbus_tk 完成")
    red = []
    alarm = ""
    try:
        #设定串口为从站
        master = modbus_rtu.RtuMaster(serial.Serial(port=PORT,
        baudrate=9600, bytesize=8, parity='N', stopbits=1, xonxoff=0))
        master.set_timeout(5.0)
        master.set_verbose(True)

        #读保持寄存器 03H 1站号 地址2700 长度0-42
        red = master.execute(1, cst.READ_HOLDING_REGISTERS, 2700, 43) #这里可以修改需要读取的功能码
        #print(red)
        alarm="正常"
        return list(red),alarm

    except Exception as exc:
        #print(str(exc))
        alarm = (str(exc))

    return red, alarm      ##如果异常就返回[],故障信息

if __name__ == "__main__":
    mod()

功能码及使用说明:

  • READ_COILS H01 读线圈
  • READ_DISCRETE_INPUTS H02 读离散输入
  • READ_HOLDING_REGISTERS H03 读寄存器
  • READ_INPUT_REGISTERS H04 读输入寄存器
  • WRITE_SINGLE_COIL H05 写单一线圈
  • WRITE_SINGLE_REGISTER H06 写单一寄存器
  • WRITE_MULTIPLE_COILS H15 写多个线圈
  • WRITE_MULTIPLE_REGISTERS H16 写多寄存器
#读保持寄存器 03H 1站号 0地址 长度2 
logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2))
#01 03 00 00 00 02 C4 0B

# 读输入寄存器 04H    
logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 0, 8))
#反馈:01 04 00 00 00 08 F1 CC

# 读线圈寄存器 01H   
logger.info(master.execute(1, cst.READ_COILS, 0, 6))
#反馈:01 01 00 00 00 06 BC 08

#读离散输入寄存器 02H
logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 16))
#反馈:01 02 00 00 00 10 79 C6 

# 单个读写寄存器操作 06H
# 写寄存器地址为0的保持寄存器 06H  
logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 0, output_value=6))
#反馈:01 06 00 00 00 06 09 C8
 
logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 1))
#反馈:01 03 00 00 00 01 84 0A

# 写寄存器地址为0的线圈寄存器,写入内容为0(位操作) 05H
logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 0, output_value=0))
#反馈:01 05 00 00 00 00 CD CA 

logger.info(master.execute(1, cst.READ_COILS, 0, 1))
#反馈:01 01 00 00 00 01 FD CA

# 多个寄存器读写操作 10H
# 写寄存器起始地址为0的保持寄存器,操作寄存器个数为4
logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 11, output_value=[20,21,22,23]))
#反馈:01 10 00 0B 00 04 08 00 14 00 15 00 16 00 17 AB A9

logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 4))
#反馈:01 03 00 00 00 04 44 09 
 类似资料: