Using pySerial with Python 3.3

P_Rein picture P_Rein · Apr 15, 2013 · Viewed 20.4k times · Source

I've seen many code samples using the serial port and people say they are working codes too. The thing is, when I try the code it doesn't work.

import serial

ser = serial.Serial(
    port=0,
    baudrate=9600
    # parity=serial.PARITY_ODD,
    # stopbits=serial.STOPBITS_TWO,
    # bytesize=serial.SEVENBITS
)

ser.open()
ser.isOpen()

print(ser.write(0xAA))

The error it gives me is : "SerialException: Port is already opened". Is it me using python3.3 the problem or is there something additional I need to instal ? Is there any other way to use COM ports with Python3.3 ?

Answer

P_Rein picture P_Rein · Apr 17, 2013

So the moral of the story is.. the port is opened when initialized. ser.open() fails because the serial port is already opened by the ser = serial.Serial(.....). And that is one thing.

The other problem up there is ser.write(0xAA) - I expected this to mean "send one byte 0xAA", what it actually did was send 170(0xAA) zeros. In function write, I saw the following : data = bytes(data) where data is the argument you pass. it seems the function bytes() doesn't take strings as arguments so one cannot send strings directly with: serial.write(), but ser.write(bytearray(TheString,'ascii')) does the job.

Although I am considering adding:

if(type(data) == type('String')):
    data = bytearray(data,'ascii')

in ser.write(), although that would make my code not work on other PCs.