Pyserial 读取传入的信息,但答案不寻常

Pyserial reading incoming informations with unusual answer

我正在尝试与 UIRobot UIM 2502 模块进行通信。我可以问一些像比特率之类的东西。当我试图获得实际电机位置时,答案不是正常的十六进制代码。

我可以使用程序 StepEva 获取当前位置并移动步进器。所以我用 StepEva 移动了步进器,并通过 python 询问了位置。结果如代码中的注释。

from serial import Serial
ser = Serial(port='COM7', baudrate=38400, timeout=1, bytesize=8, parity='N', stopbits=1)
commando = 'POS;'
ser.write(commando.encode())
response=ser.readline()
print(response)
# responses:
# b'\xcc\x05\xb0\x00\x00\x00\x009\xff'            StepEva position:     57
# b'\xcc\x05\xb0\x00\x00\x00\x01T\xff'            StepEva position:    212
# b'\xcc\x05\xb0\x0f\x7f\x7f<\x13\xff             StepEva position:  -8685 

我不知道如何转换这个十六进制代码。手册说 b0 字节后的 5 个字节描述了位置。 手册中的 POS 响应: CC [控制器 ID] B0 [P0] [P1] [P2] [P3] [P4] FF

评论:B0 >> 的消息ID 当前位置 [P0] ~ [P4] >> 接收数据 0 ~ 4

根据 User Manual UIM2502 and "Page 62 Figure12-2: Conversion from five 7bits message data to a 32bits data" of User Manual UIM242XX Series 的 "Page 18 Figure5-1: Conversion from three 7bits message data to a 16bits data",每个字节包含 7 位值,您可以将其以大端形式连接成 32 位整数。

文档中没有包含您问题的消息,但根据问题,数字将是 32 位有符号整数。
作为一个Python程序,它会是这样的。

def getPosition(response):
    position = 0
    for i in range(3,8):
        position <<= 7
        position += response[i]

    if position > 0x7FFFFFFF:
        position -= 0x100000000

    return position

例如可以这样使用

print(getPosition(b'\xcc\x05\xb0\x00\x00\x00\x009\xff')) # result is 57
print(getPosition(b'\xcc\x05\xb0\x00\x00\x00\x01T\xff')) #           212
print(getPosition(b'\xcc\x05\xb0\x0f\x7f\x7f<\x13\xff')) #           -8685

response=ser.readline()
position=getPosition(response)
print(position)

顺便说一句,我没看内容,但是搜索时,有这样一个包,所以可能有功能可以通过各种方式使用。
python-can