简体   繁体   中英

Logic to recognize the name of the COM port to which a USB to RS422 connector is connected (for Windows application))

I have an application where I am writing data to the serial port via an USB to RS422 convertor. This convertor cable to connected to my PC through an USB hub. The problem I am facing is that each time I change the PC in which I am running the application, the name of the COM port changes. So I will have to change this in my code and recompile the code to run the application. At present following is the code I am using to initialize the serial port:

if ((comport = CreateFile("\\\\.\\COM7", GENERIC_WRITE, 0, 
        NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL)) == INVALID_HANDLE_VALUE)
    {
        return false;
    }

Here I am exclusively mentioning the name of the COM port. I would like to know if there is an API to know the status of the COM ports and on the fly recognize the COM port to which my convertor is connected ?

What is proper way to detect all available serial ports on Windows? That question might help you out, at least a bit. So it's probably not possible with an API, as the second answer implies. Serial ports aren't plug & play.

So it's possible to list all ports. The only possible way I think of, is by polling each device that is in the list. And wait till you get the response you are expecting. It's not that nice.

EDIT: Might be possible to get the friendly name, if that is what you want. How do I get the friendly name of a COM port in Windows?

Rather changing the COM port in your application you can set the COM port for your cable from

Device Manager - > Ports -> Right Click your cable name -> Properties -> Port Setting -> Advanced -> Com Port Number (You can select the port number according to the application)

No need to change anything in your application.

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