问题描述:

This question already has an answer here:

  • How to open COMXX files(serial port)

    1 answer

网友答案:

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.

相关阅读:
Top