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

W. Stine picture W. Stine · Aug 14, 2015 · Viewed 47.9k times · Source

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?

Answer

Johan E. T. picture Johan E. T. · Aug 15, 2015

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.