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

时间:2015-08-14 21:35:53

标签: python pyserial spyder 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

但是当我在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

如何让Spyder在这方面表现得像Canopy?

2 个答案:

答案 0 :(得分:5)

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

尝试将值显式声明为bytearray并将其写入串行端口:

imort 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)

编辑:更正拼写错误。

答案 1 :(得分:0)

创建options nofmterr symbolgen; %macro data_checks(dset,newset); %if &newset= %then %let newset = new; %local re yr; %let re = %sysfunc(prxparse(/_y(\d\d?)$/)); %let rc = %sysfunc(prxmatch(&re,&dset)); %let yr = %sysfunc(prxposn(&re, 1, &dset)); %put &=yr; %mend data_checks; %data_checks(owners.ownersclean_y10, new_dataset); (尽管您可能还需要转换为bytearray)。

str