11

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:

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

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?

W. Stine
  • 111
  • 1
  • 1
  • 3

2 Answers2

14

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.

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.

Johan E. T.
  • 185
  • 8
1

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

>>> bytearray([1, 2, 3])
bytearray(b'\x01\x02\x03')
>>> str(bytearray([1, 2, 3]))
'\x01\x02\x03'
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358