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?
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.
Try using
char *szPort = _T("COM1"); // Change port number to your unused existing port
_T
forces to keep szPort in ASCII.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With