CreateFile() 串行通信问题

CreateFile() Serial Communication Issue

我正在尝试通过我的 USB 端口(名为 COM15)进行一些串行通信,但出现错误。这是发生错误的代码:

HANDLE myPortHandle = CreateFile("COM15",
                                  GENERIC_READ | GENERIC_WRITE,
                                  0,
                                  NULL,
                                  OPEN_EXISTING,
                                  0,
                                  NULL);

if (myPortHandle == INVALID_HANDLE_VALUE)
{
    DWORD lastError = GetLastError();
    cout<<"ERROR HERE! = "<<lastError<<endl;
}

我每次编译程序,打开串口的句柄==INVALID_HANDLE_VALUE。我在 CreateFile() msdn 文档中读到要使用 GetLastError() 以获得 "extended error information"。现在...当我 运行 代码时,GetLastError() returns 的值为:2

在 GetLastError() 的 msdn 文档中,它说:

"The Return Value section of the documentation for each function that sets the last-error code notes the conditions under which the function sets the last-error code."

我尝试在 CreateFile() msdn 文档的 Return 值部分查找“2”的含义,但在任何地方都找不到其含义。

问题:

1) 为什么会这样:myPortHandle == INVALID_HANDLE_VALUE?

2) 此外,如果有人能指导我到 msdn 文档中查找 GetLastError() 返回的“2”的含义,那就太棒了!

Windows 错误代码记录在此处:http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx

您的错误代码是 ERROR_FILE_NOT_FOUND。这意味着无法找到 COM15。根据 this article 您需要使用名称:"\\.\COM15".

CreateFile() can be used to get a handle to a serial port. The "Win32 Programmer's Reference" entry for "CreateFile()" mentions that the share mode must be 0, the create parameter must be OPEN_EXISTING, and the template must be NULL.

CreateFile() is successful when you use "COM1" through "COM9" for the name of the file; however, the message INVALID_HANDLE_VALUE is returned if you use "COM10" or greater.

If the name of the port is \.\COM10, the correct way to specify the serial port in a call to CreateFile() is as follows:

CreateFile(
  "\\.\COM10",     // address of name of the communications device
  fdwAccess,          // access (read-write) mode
  0,                  // share mode
  NULL,               // address of security descriptor
  OPEN_EXISTING,      // how to create
  0,                  // file attributes
  NULL                // handle of file with attributes to copy
);

NOTES: This syntax also works for ports COM1 through COM9. Certain boards will let you choose the port names yourself. This syntax works for those names as well.

或者从文档到 CreateFile 本身:

The CreateFile function can create a handle to a communications resource, such as the serial port COM1. For communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, the dwShareMode parameter must be zero (exclusive access), and the hTemplateFile parameter must be NULL. Read, write, or read/write access can be specified, and the handle can be opened for overlapped I/O.

To specify a COM port number greater than 9, use the following syntax: \.\COM10. This syntax works for all port numbers and hardware that allows COM port numbers to be specified.