Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 300
W. Stine Avatar asked Aug 14 '15 21:08

W. Stine


People also ask

How do you send data to a serial port in Python?

Transmitting Data: Firstly, we need to include the serial library. We can then declare an instance of the serial port and add the SerialPort, baudRate and timeOut parameters , I'm using serial0, 115200 and 0.050. To find your Pi serial port use the command 'lsdev'. In my case, my serial port was serial0.

Which protocol is used for serial data communication in Python?

The universal asynchronous receiver/transmitter or UART is the most common serial communication protocol used by embedded devices.

What is PySerial used for?

PySerial is a useful package for problem solvers because it allows us to exchange data between computers and pieces of external hardware such as voltmeters, oscilloscopes, strain gauges, flow meters, actuators, and lights. PySerial provides an interface to communicate over the serial communication protocol.


1 Answers

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.

like image 59
Johan E. T. Avatar answered Oct 21 '22 14:10

Johan E. T.