我正在向设备发送一个字节("\x2b"),并将接收一个回显字节和3个字节的数据(“\x2b\x??\x??\x?\x?\x??”).I我正在使用.replace("2b","",4)去除回显字节。我需要将收到的十六进制的3个字节更改为int(16),并将它们命名为3个不同的变量,我可以在计算中一次调用一个。这是我到目前为止所拥有的。
import serial
import os
ser = serial.Serial(port="COM17", baudrate=9600)
ser.open()
ser.write("\x2b")
print int(ser.readline(4).encode("hex").replace("2b", "", 4), 16)
ser.close()
os.system("pause")发布于 2017-01-03 04:57:33
使用struct模块从字节字符串中检索任意二进制数据:
import serial
import os
import struct
ser = serial.Serial(port="COM17", baudrate=9600)
ser.open()
ser.write("\x2b")
response = ser.readline(4)
echo, a, b, c = struct.unpack("4B", response)
print ("Response numbers: {:02x}, {:02x}, {:02x}".format(a, b, c))
ser.close()附带说明:避免将os.system("pause")作为程序的一部分。这是一些人的一个可怕的习惯,当程序运行完成时,Windows DOS提示符保持打开,但它是(1) WIndows,对于原本可以在Mac和Linux上运行的程序,以及(2)涉及为普通操作创建一个完整的其他进程。
您可以在Python语言中添加一个简单的input调用,要求用户按<enter>键:
(最后一行):
input("Press <enter> to close terminal")发布于 2017-01-03 04:36:00
不存在将3字节流转换为3(?) int16 (又称short)数字的“自然”转换。
所以你必须更具体:
int8?当然,将结果数字视为int16 (因为它们适合)是完全正确的。int16),你使用的是BIG_ENDIAN还是BIG_ENDIAN在任何情况下,struct包都可以为您完成转换:
import struct
# read 4 bytes, discard the first one, so we get a list of 3 bytes
inputdata = ser.readline(4)[1:]
# the following parses 'inputdata' as 3 `uint8` numbers
a,b,c = struct.unpack('BBB', inputdata)https://stackoverflow.com/questions/41432819
复制相似问题