C++ COM port Opening, Reading and Writing

我的未来我决定 提交于 2019-12-13 06:52:36

问题


I am trying to open a COM port using Win32's CreateFile function. I have read docs at MSDN as well as on several forums on how to do that but no matter what I do I still get Error code #2 (port does not exist). The code I currently have is:

m_hCom = CreateFile(
    "\\.\COM10",
    GENERIC_READ | GENERIC_WRITE,
    0,
    0,
    OPEN_EXISTING,
    FILE_FLAG_OVERLAPPED,
    NULL
);
if (m_hCom == INVALID_HANDLE_VALUE) {
    int error = GetLastError();
    return FALSE;
}

I am using Visual Studio 2010.

Please tell me what am I doing wrong.


回答1:


Try putting in some extra slashes like this:

"\\\\.\\COM10"

Because the backslash is a special character you have to insert two for each one you want in your string.




回答2:


I suggest writing some temporary code that iterates or lists the available COM ports.

There is a great chance that your COM port naming is not correct.




回答3:


I have written the same code you are trying to write not long ago. If you say there is a 10th COM port then it should work as long as you have the extra slashes. You can trying going the projects property window and changing the Character Set to multibyte characters. Good luck!




回答4:


Try this:

CreateFile(L"COM1", ...);



回答5:


Run the following code in a C++ Project and if the Comport let's say COMPORT 4 is taken by let's say TeraTerm it sends back an error otherwise it opens up the port.

HANDLE hComm;
hComm = CreateFile(
L"\\.\COM4",
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL
);
if (hComm == INVALID_HANDLE_VALUE) {
printf("The Comport is closed or taken by another hardware/software!\n\r");
}



来源:https://stackoverflow.com/questions/5955440/c-com-port-opening-reading-and-writing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!