0

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 ?

Lol4t0
  • 12,444
  • 4
  • 29
  • 65
vik22
  • 9
  • 4
  • Can't you keep port name in some kind of config file? This way you won't have to recompile your program, just change some text in config file. – Kamil Klimek Apr 09 '13 at 07:29
  • It is possible to do that but I would like this to be automatic and happen during initialization process of the application. – vik22 Apr 09 '13 at 07:41

2 Answers2

1

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?

Community
  • 1
  • 1
Eric Smekens
  • 1,602
  • 20
  • 32
0

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.

Shaikh Farooque
  • 2,620
  • 1
  • 19
  • 33