python 通过modbus rtu 485 读取传感器数据 | python代码速记 | python 技术论坛-江南app体育官方入口
#python读取baumer laser om30-11235102的测量数据,数据的类型为float
import serial
import time
import struct
ser = serial.serial(
port=’com3’,
baudrate=57600,
bytesize=8,
parity=serial.parity_even, # 偶校验
stopbits=1,
timeout=1
)
slave_addr = 1 # 设备地址
func_code = 4 # 功能码
start_reg = 200 # 起始寄存器地址
num_regs = 13 # 寄存器数量
crc = 0xffff # crc校验初始值
cmd = bytearray([slave_addr, func_code, start_reg >> 8, start_reg & 0xff, num_regs >> 8, num_regs & 0xff])
for b in cmd:
crc ^= b
for _ in range(8):
if crc & 0x0001:
crc = (crc >> 1) ^ 0xa001
else:
crc >>= 1
cmd = bytearray([crc & 0xff, crc >> 8])
def communication():
ser.write(cmd)
time.sleep(0.5) # 等待设备响应
response = ser.read(ser.in_waiting)
# 处理响应数据
if len(response) == 5 num_regs * 2 and response[0] == slave_addr and response[1] == func_code:
data = response[3:-2]
values = [data[i] << 8 | data[i 1] for i in range(0, len(data), 2)]
# print(values)#打印接收到的所有数据,包含长度信息,状态信息等
#将接收到的数据位移数据2、3位转换成float类型的数据显示(banmer通讯手册要求的)
num1 = int(values[2]/2) #值超出32676,报错,将这个小数部分缩小10倍
num2 = int(values[3])
packed = struct.pack(‘2h’,num1,num2)
float_num = struct.unpack(‘f’,packed)[0]
print(float_num) #
else:
print(“modbus rtu error”)
while true:
communication()
ser.close()