开发者

C++ COM port Opening, Reading and Writing

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.


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.


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.


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!


Try this:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜