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?
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.
The universal asynchronous receiver/transmitter or UART is the most common serial communication protocol used by embedded devices.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With