开发者

pySerial: opening multiple ports at once

EDIT: Found the problem: I tried referencing a variable, but mixed up its name, so instead I declared a new variable. Turns out pySerial is not limited to one open serial point at a time.

I'm trying to open two serial ports at once using the following code

    ser0 = serial.Serial(
                         port = port_list[0],
                         baudrate = 115200,
                         timeout = 0.1
                         )

    ser1 = serial.Serial(
                         port = port_list[1],
                         baudrate = 115200,
                         timeout = 0.1
                         )

But it seems that I open the second, the first one closes. Is there an inherent limit to one serial port open at a time using pySerial?

Thanks, T.G.

EDIT: I should have posted this to begin with

while not (comm_port0_open and comm_port1_open):
    print 'COM ports available:'
    port_list = []
    i = 0
    for port in __EnumSerialPortsWin32():
        port_list.append(port[0])
        print '%i:' % i, port[0]
        i+=1
    print 'Connect to which port? (0, 1, 2, ...)'
    comm_port_str = sys.stdin.readline()
    try:
        if len(comm_port_str)>0:
            if comm_port0_open:
                ser1 = serial.Serial(
                                    port = port_list[int(comm_port_str)],
                                    baudrate = 115200,
                                    timeout = 0.1
                                    )
                comm1_port_open = True
                print '%s opened' % port_list[int(comm_port_str)]
            else:
                ser0 = serial.Serial(
                                 开发者_如何学C   port = port_list[int(comm_port_str)],
                                    baudrate = 115200,
                                    timeout = 0.1
                                    )
                comm0_port_open = True
                print '%s opened' % port_list[int(comm_port_str)]                   
        else:
            print 'Empty input'
    except:
        print 'Failed to open comm port, try again'


Without seeing the context of the code, this is only a guess.

Serial ports will be closed when they are garbage collected and __del__ is run. Uner CPython, if your ser0 reference count drops to zero after that block of code is run, but somehow the ser1 doesn't, it will give the appearance of one port closing when the other opens.

But post more code!


The variables referenced when declaring the com ports open do not match the ones checked in the while condition. Oops.


In your code you test comm_port0_open and comm_port1_open, but set them with comm0_port_open = True and comm1_port_open. Different names!

Another point: don't use bare 'except', it can hide all kinds of errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜