1. 前言
- modbus_tk是使用python语言实现的modbus协议栈,该库函数及支持主机也支持从机,同时支持RTU串口通信和TCP范式通信。
2. 准备工作
- 查阅modbus相关资料
- 下载modbus-tcp tester,这里面有server-tester和client-tester,能加速测试程序过程
3. modbus_tk安装
- 环境:python2.7, win10 & 树莓派
- 操作:直接 pip install modbus_tk 或者采用 easy_install
4. 基础示例
- 从机程序,需要先运行从机程序,才能启动master
'''
作者:raphael
时间:2017/3/10
简介:modbus协议从机测试脚本
'''
import sys
import logging
import threading
import modbus_tk
import modbus_tk.defines as cst
import modbus_tk.modbus as modbus
import modbus_tk.modbus_tcp as modbus_tcp
LOGGER = modbus_tk.utils.create_logger(name="console", record_format="%(message)s")
if __name__ == "__main__":
try:
SERVER = modbus_tcp.TcpServer(address="192.168.1.111", port=1100)
LOGGER.info("running...")
LOGGER.info("enter 'quit' for closing the server")
SERVER.start()
SLAVE1 = SERVER.add_slave(1)
SLAVE1.add_block('A', cst.HOLDING_REGISTERS, 0, 4)
SLAVE1.add_block('B', cst.HOLDING_REGISTERS, 4, 14)
SLAVE2 = SERVER.add_slave(2)
SLAVE2.add_block('C', cst.COILS, 0, 10)
SLAVE2.add_block('D', cst.HOLDING_REGISTERS, 0, 10)
SLAVE1.set_values('A', 0, 4)
SLAVE1.set_values