2
votes

I recently tried to get access to a serial communication using a Bluetooth usb dongle. I used the C code below, and keep getting error 5, which is “Access denied”. I am the administrator for the system (which seemed to be the common solution to this problem on the forums) and no other application is accessing the same port I am using (also another common solution). I’m running on a Windows Vista Home Basic 32bit system. I was wondering if anyone had a solution for this My C code is:

HANDLE hComm;

hComm = CreateFile( _T("\\.\COM3"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

if (hComm == INVALID_HANDLE_VALUE)
    printf("Error number: %ld\n", GetLastError());
else
    printf("success\n");
5
+1 for an example that correctly shows use of the _T macro on the string constant so that the code is independent of the compile-time choice of ANSI or UNICODE build. - RBerteig
As an additional data point, I'd recommend verifying the COM port is actually accessible by a simple terminal application like HyperTerminal. Is it? - Hexagon

5 Answers

4
votes

I don't know if this is your problem or not, but I suspect you need to escape the backslashes in the path, like so: "\\\\.\\COM3"

1
votes

That does look like you have to escape your backslashes again. You can also verify that the COM port you're targeting exists on your system by using an object viewer, such as WinObj (http://technet.microsoft.com/en-us/sysinternals/bb896657.aspx), although I don't know if WinObj runs on Vista.

0
votes

In my experience the backslashes are not needed

hComm = CreateFile( _T("COM3"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
0
votes

Thanks for the tips but it turns out the bluetooth passkey was not set properly and therefore it was denying access to the serial port.

0
votes

Just replace your COM# with \.\COM# in your code,

  hComm = CreateFile("\\\\.\\COM15",

              GENERIC_READ | GENERIC_WRITE,
              0,
              0,
              OPEN_EXISTING,
              0,
              0);