简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM