1
votes

Having a small problem with opening a serial/console port via pySerial. My program is meant to get the active com port, open a console connection and then send data. When the program is running and I plug in my RS232 USB I receive a SerialException error. (More specifically, "Could not open port: FileNotFoundError")

In the event where the program is run, it will keep printing "No RS232 Connected", but when the RS232 USB is connected the program breaks and runs into the SerialException error.

If I plug in the RS232 USB before running the program and then run it, it reads and performs normal operation without issue.

    ports = serial.tools.list_ports.comports(include_links=False)

    if not ports:
        print("No RS232 Connected")
    if ports:
        for port in ports:
            print('Found port ' + port.device)
            ser = serial.Serial(port.device)

            if ser.isOpen():
                ser.close()
        break
console = serial.Serial(port.device, baudrate=9600, parity="N", stopbits=1, bytesize=8, timeout=0.4)

I am quite new to Python and programming in general, but I feel that the problem may be around the 'ports' list already being populated twice due to the while True loop. Then when we go to create the console by opening the port we are expecting one entry in the list, but there are two. Since we can't have 2 open console connections on the same COM port, we receive the error.

If I print the 'ports' list I get this.

"[<serial.tools.list_ports_common.ListPortInfo object at 0x000002B5D77F0D68>] [<serial.tools.list_ports_common.ListPortInfo object at 0x000002B5D77F0D68>]"

Any help would be greatly appreciated! Please let me know if you require any more details. Thanks,

1
Half your code is missing. Anyway, using a set instead of a list (if your objects are hashable) should remove duplicates. Or just test for membership in the list before appending.Andras Deak
Also what you say is printed can not be a single python list. Something is off.Andras Deak
Thanks Andras for your help, I have managed to figure out the issue. It was more to do with the way Windows sets up a serial port, rather than the way I was trying to get the COM port number.beng95

1 Answers

2
votes

After further research into it, I have realised that when a RS232 USB is plugged into the PC, we need to give it a bit of time to open a stream. It sounds like it is opened when the temp file is created for it. Although it was identifying that a COM port was available almost immediately, it was not ready by the time I was trying to create the Serial instance, which was why I was getting the FileNotFound error.

A simple sleep function of half a second has solved the issue!