5

我正在尝试通过我的 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() 来获取“扩展错误信息”。现在...当我运行代码时,GetLastError() 返回值:2

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

“设置最后一个错误代码的每个函数的文档的返回值部分记录了该函数设置最后一个错误代码的条件。”

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

问题:

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

2) 另外,如果有人可以指导我到我需要查看 msdn 文档以找到 GetLastError() 返回的“2”的含义,那将是非常棒的!

4

1 回答 1

11

Windows error codes are documented here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx

Your error code is ERROR_FILE_NOT_FOUND. Which means that COM15 cannot be found. According to this article you need to use the name: "\\\\.\\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.

Or alternatively from the documentation to CreateFile itself:

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.

于 2015-01-12T19:58:53.003 回答