Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateFile returns error INVALID_HANDLE_VALUE (for COM port), and GetLastError returns "can't find file specified"

I'm opening a port to communicate with a device and control the device, but the CreateFile() function returns INVALID_HANDLE_VALUE.

GetLastError() returns 2 which means it can't find the specified file.

My code is shown below:

wsprintf( szPort, "COM%d", nPort );
m_hIDComDev = CreateFile(szPort,
                         GENERIC_READ | GENERIC_WRITE, 
                         0, 
                         NULL, 
                         OPEN_EXISTING, 
                         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 
                         NULL);
if (m_hIDComDev == INVALID_HANDLE_VALUE)
{
    DWORD err=GetLastError();
}

Why does this problem occur?

like image 478
user1964417 Avatar asked Jan 31 '13 20:01

user1964417


2 Answers

The problem is that you're not specifying the correct value for lpFileName for your serial port. You should be using this format:

"\\\\.\\COM%d"

Which will result in a string that looks like \\.\COM1, which is the correct format.

like image 181
Adam Maras Avatar answered Sep 30 '22 12:09

Adam Maras


Try using

char *szPort = _T("COM1"); // Change port number to your unused existing port

_T forces to keep szPort in ASCII.

like image 30
Andrew Rokicki Avatar answered Sep 30 '22 13:09

Andrew Rokicki