我知道这个问题已经讨论了很多,但我仍然有一个问题。我正在尝试使用pyserial将十六进制值发送到我的设备。
command="\x89\x45\x56"
ser.write(command)
然而,我一直收到一个错误,指出 string argument without encoding.
有人知道如何解决这个问题吗?
packet = bytearray()
packet.append(0x41)
packet.append(0x42)
packet.append(0x43)
ser.write(packet)
从pySerial API文档中:
write(data) 将字节数据写入端口。此数据应为bytes类型(或兼容类型,如bytearray或memoryview)。Unicode字符串必须进行编码(例如'hello'.encode('utf-8'))。
假设您正在使用Python 3(您应该这样做),以下是发送单个字节的方法:
command = b'\x61' # 'a' character in hex
ser.write(command)
对于几个字节:
command = b'\x48\x65\x6c\x6c\x6f' # 'Hello' string in hex
ser.write(command)
我已经成功地从字符串中发送十六进制值,代码如下:
input = '736e7000ae01FF'
ser.write(input.decode("hex"))
print "sending",input.decode("hex")
>> sending snp «☺
command=b"\x89\x45\x56"
bytes
对象。command=b"\x89\x45\x56"
谢谢,
最终,我找到了如何读取二进制文件的特定区域并通过UART发送(作为流控制)的方法。
binary_file = open("test_small.jpg", 'rb')
filesize = getSize(binary_file)
ser = serial.Serial('COM7', 115200, timeout=0.5)
count = 0
while (offset < filesize):
binary_file.seek(offset, 0)
ser.write(binary_file.read(MTU))
offset = offset + MTU
binascii
?from binascii import unhexlify
,然后command = unhexlify("894556")
。 - TyrantWave