简体   繁体   English

Pymodbus将浮点数添加到服务器上下文寄存器

[英]Pymodbus adding float to server context register

I'm new to pymodbus and modbus in general, I've been trying for some time now to add a float directly 我是pymodbus和modbus的新手,我一直在尝试一段时间直接添加一个float
to server context without any success, I wondered if you had any lead on how to do it. 到服务器环境没有任何成功,我想知道您是否在如何做到这一点上有领先优势。 I already try to use payload by doing something like : 我已经尝试通过执行以下操作来使用有效负载:

builder = BinaryPayloadBuilder(endian=Endian.Little)
builder.add_32bit_float(long(69000))
payload = builder.build()

context[slave_id].setValues(register, address, payload)

However I get an error about pymodbus trying to cast the payload to int, my code is mostly the one from the sync server example. 但是我遇到了有关pymodbus尝试将有效负载转换为int的错误,我的代码主要是同步服务器示例中的代码。 Any help would be very nice 任何帮助将是非常好的

builder = BinaryPayloadBuilder(endian=Endian.Little)
builder.add_32bit_float(30.3)
payload = builder.to_registers()

context[slave_id].setValues(register, address, payload)

This is the correct way, take note that "register" is the starting registers and all modbus registers are 16 bit wide so a 32 bit float occupies 2 (register and register+1). 这是正确的方法,请注意“寄存器”是起始寄存器,所有modbus寄存器均为16位宽,因此32位浮点数占用2(寄存器和寄存器+1)。

After some research on register and and splitting of float into 16bit integer I came up with : 经过一些关于寄存器和将float拆分为16bit整数的研究之后,我想到了:

register = 3
slave_id = 0x00
address  = 0x01

values   = context[slave_id].getValues(register, address, count=2)

# Two integers to a floating point
i1 = values[0]
i2 = values[1]
f = unpack('l',pack('<HH',i1,i2))[0]
f = f+1
# Floating point to two integers
i1, i2 = unpack('<HH',pack('l',f))
print(f,i1,i2)

context[slave_id].setValues(register, address, [i1,i2])

I had some issue with the encoding in Endian check what is the one you need with your modbus client, 我对Endian中的编码有问题,请检查您的Modbus客户端需要什么,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM