ModbusTcp获取数据
记录一个用 pymodbus 库来获取数据的代码。
- 注意:
- 1.读取寄存器地址是16进制的。
- 2.大小端转换通过代码知道原理。
- 读取数据时,切记频率别太高,否则会出现连接被关闭问题。
from pymodbus.client.sync import ModbusTcpClient
import struct
from datetime import datetime
import time
def read_coordinate(host, port, register_address, unit_id,coordinate):"""通过Modbus TCP读取机械臂的X坐标值。参数:host (str): Modbus TCP服务器的IP地址。port (int): Modbus TCP服务器的端口号。register_address (int): 存储X坐标值的第一个寄存器地址。unit_id (int): Modbus设备的单元ID,默认为1。返回:float: 机械臂的X坐标值,如果读取失败则返回 None。"""start_time = datetime.now()client = ModbusTcpClient(host, port)try:if client.connect():# 读取两个连续的寄存器response = client.read_holding_registers(address=register_address, count=6, unit=unit_id)if response.isError():print(f"Modbus error: {response}")return Noneelse:# 获取两个寄存器的值registers = response.registerscoordinates = []for i in range(0,6,2):#小端模式combined_value = (registers[i + 1] << 16) | registers[i]#大端模式# combined_value = (registers[i] << 16) | registers[i + 1]# 将两个寄存器的值组合成一个32位整数coordinate_value = struct.unpack('!f', struct.pack('!I', combined_value))[0]coordinates.append(coordinate_value)coordinate.extend(coordinates)return coordinateselse:print("Failed to connect to Modbus server")return Nonefinally:client.close()if __name__ == "__main__":
# 示例使用host = '192.168.2.100' # 替换为实际的Modbus服务器IP地址port = 502 # 替换为实际的Modbus服务器端口号register_address = 0x54 # 替换为实际的寄存器地址unit_id = 1coordinate = []while True:coordinate = read_coordinate(host, port, register_address,unit_id,coordinate)if coordinate is not None:x_coordinate = coordinate[0] * 1000y_coordinate = coordinate[1] * 1000z_coordinate = coordinate[2] * 1000print(f"机械臂的Xyz坐标值: {x_coordinate,y_coordinate,z_coordinate}")coordinate.clear()else:print("无法读取机械臂的X坐标值")time.sleep(0.2)