Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pySerial with Python 3.3

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 ?

like image 275
P_Rein Avatar asked Apr 15 '13 14:04

P_Rein


People also ask

Is Pyserial the same as serial?

The serial package on Pypi is something different to pyserial . Maybe what's confusing you is that you need to install Pyserial with pip install pyserial , but import it with serial . The name a package can be imported by gets set in the packages field in their setup.py .

Does Anaconda have Pyserial?

Installing PySerialIf you installed the full Anaconda distribution of Python, PySerial comes pre-installed. If you do have the full Anaconda distribution of Python installed, PySerial can be installed using the Anaconda Prompt.

How do I know if Pyserial is installed?

Go to your installed Pyzo directory and look for the directory called site-packages or for older versions; pyzo-packages. To check that it is installed, start Pyzo and at the command prompt type in: import serial If it just gives you another >>> prompt, all is good.


1 Answers

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.

like image 61
P_Rein Avatar answered Sep 25 '22 21:09

P_Rein