如何使用 Python 将字节数组发送到串行端口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32018993/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:52:50  来源:igfitidea点击:

How can I send a byte array to a serial port using Python?

pythonpyserialspydercanopy

提问by W. Stine

I am working on an application which requires the sending of a byte array to a serial port, using the pyserial module. I have been successfully running code to do this in canopy:

我正在开发一个应用程序,它需要使用 pyserial 模块将字节数组发送到串行端口。我已经成功地运行代码来在 canopy 中做到这一点:

import serial
ser = serial.Serial('/dev/ttyACM0', 9600, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE)
ser.write([4, 9, 62, 144, 56, 30, 147, 3, 210, 89, 111, 78, 184, 151, 17, 129])
Out[7]: 16

But when I run the same code in Spyder (both are running Python 2.7.6) I get an error message, as

但是当我在 Spyder 中运行相同的代码(两者都运行 Python 2.7.6)时,我收到一条错误消息,如

import serial
ser = serial.Serial('/dev/ttyACM0', 9600, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE)
ser.write([4, 9, 62, 144, 56, 30, 147, 3, 210, 89, 111, 78, 184, 151, 17, 129])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 475, in write
n = os.write(self.fd, d)
TypeError: must be string or buffer, not list

How can I make Spyder behave like Canopy in this regard?

在这方面,我怎样才能让 Spyder 表现得像 Canopy?

回答by Ignacio Vazquez-Abrams

By creating a bytearray(although you may need to convert to a stras well).

通过创建 a bytearray(尽管您可能也需要转换为 a str)。

>>> bytearray([1, 2, 3])
bytearray(b'\x01\x02\x03')
>>> str(bytearray([1, 2, 3]))
'\x01\x02\x03'

回答by Johan E. T.

It looks like the error is caused by the type of object passed to ser.write(). It seems that it is interpreted as a list and not a bytearray in Spyder.

看起来错误是由传递给 ser.write() 的对象类型引起的。似乎它被解释为列表而不是 Spyder 中的字节数组。

Try to declare the values explicitly as a bytearray and then write it to the serial port:

尝试将值显式声明为字节数组,然后将其写入串行端口:

import serial
ser = serial.Serial('/dev/ttyACM0', 9600, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE)

values = bytearray([4, 9, 62, 144, 56, 30, 147, 3, 210, 89, 111, 78, 184, 151, 17, 129])
ser.write(values)

edit:Correcting typos.

编辑:更正错别字。