简体   繁体   English

识别USB到RS422连接器的COM端口名称的逻辑(对于Windows应用程序)

[英]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. 我有一个应用程序,通过USB到RS422转换器将数据写入串行端口。 This convertor cable to connected to my PC through an USB hub. 该转换器电缆通过USB集线器连接到我的PC。 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. 我面临的问题是,每次更改运行应用程序的PC时,COM端口的名称都会更改。 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. 在这里,我仅提及COM端口的名称。 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 ? 我想知道是否有一个API可以知道COM端口的状态,并且可以即时识别转换器连接到的COM端口吗?

What is proper way to detect all available serial ports on Windows? 检测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. 因此,如第二个答案所示,API可能无法实现。 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? 如何获得Windows中COM端口的友好名称?

Rather changing the COM port in your application you can set the COM port for your cable from 可以在以下应用程序中设置电缆的COM端口,而不是在应用程序中更改COM端口:

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. 无需更改应用程序中的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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