Python 使用pyserial发送二进制数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17589942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using pyserial to send binary data
提问by BladeRunner
I know there has been a lot of discussion on this but I still have a question. I am trying to send hex values through pyserial to my device using pyserial
我知道已经对此进行了很多讨论,但我仍然有一个问题。我正在尝试使用 pyserial 通过 pyserial 将十六进制值发送到我的设备
command="\x89\x45\x56"
ser.write(command)
However I keep getting an error saying string argument without encoding.
Does anyone know how to solve this?
但是我一直收到一个错误说 string argument without encoding.
有人知道如何解决这个问题吗?
回答by John Szakmeister
If this is Python 3, it's probably treating your string as unicode, and doesn't know how to transform it. I think you probably mean to use bytes here:
如果这是 Python 3,它可能将您的字符串视为 unicode,并且不知道如何转换它。我想你可能想在这里使用字节:
command=b"\x89\x45\x56"
回答by TobiMarg
If you use Python 3 you can use a bytes
object.
如果您使用 Python 3,则可以使用bytes
对象。
command=b"\x89\x45\x56"
From the error it looks like pyserial tries to convert a (your) string into a bytes object without specifying an encoding.
从错误看来 pyserial 试图将(您的)字符串转换为字节对象而不指定编码。
回答by jjz
I have had success sending hex values from a string like so:
我已经成功地从这样的字符串发送十六进制值:
input = '736e7000ae01FF'
ser.write(input.decode("hex"))
print "sending",input.decode("hex")
>> sending snp ???
回答by rjha94
packet = bytearray()
packet.append(0x41)
packet.append(0x42)
packet.append(0x43)
ser.write(packet)
回答by amartin1911
From pySerial API documentation:
来自 pySerial API文档:
write(data)Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8').
write(data)将字节数据写入端口。这应该是字节类型(或兼容,例如 bytearray 或 memoryview)。Unicode 字符串必须被编码(例如'hello'.encode('utf-8')。
Assuming you're working on Python 3 (you should), this is the way to send a single byte:
假设您正在使用 Python 3(您应该这样做),这是发送单个字节的方式:
command = b'\x61' # 'a' character in hex
ser.write(command)
For several bytes:
对于几个字节:
command = b'\x48\x65\x6c\x6c\x6f' # 'Hello' string in hex
ser.write(command)
回答by Jimmy Wong
Thanks,
谢谢,
Finally, I figure out how to read the specify region of binary file and send through uart (as flow control).
最后,我弄清楚如何读取二进制文件的指定区域并通过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