C++ COM port Opening, Reading and Writing

2019-08-18 17:46发布

问题:

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");
}