How to use Win32 API to talk to a com port (RS232)

10,859

Solution 1

Try _T("COM1") instead of LPCWSTR("COM1"). It's called Generic-Text Mapping. I don't actually know whether that is the problem, but using _T is the right way to it.

Also, when Windows API calls return an error condition (like -1) you can use the Last-Error Code (using GetLastError and FormatMessage) to get a more detailed description of the error.

Solution 2

For a Unicode build, CreateFile maps to CreateFileW which expects "wide" character strings. You can solve the immediate problem by prefixing your string constant with L, like this:

CreateFile(L"COM1", ...);

Some people would suggest explicitly using the wide version:

CreateFileW(L"COM1", ...);

Or you can explicitly use the "ANSI" version, even in a Unicode build:

CreateFileA("COM1", ...);

If you want to be able to build Unicode and ANSI builds, you can use a macro that optionally includes the L prefix. There are two versions of this macro: TEXT(x) and _T(x). If I recall correctly, the former comes from the Windows API via <tchar.h> and the latter comes from Microsoft's implementation of the C runtime library. Since this is a Windows API, I'd use the TEXT version.

CreateFile(TEXT("COM"), ...);

Nowadays, it's probably not worth keeping the backward compatibility for ANSI. All versions of Windows released in the past decade use Unicode internally, so if you try to use the ANSI versions, the strings are going to be widened at run time. So I wouldn't worry about the macros and just prefix string literals with L except in very special circumstances.

Share:
10,859
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to use win32 API to talk to a com port I found this http://www.robbayer.com/files/serial-win.pdf

    hSerial = CreateFile("COM1",
    GENERIC_READ | GENERIC_WRITE,
    0,
    0,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    0);
    

    I use VS2008 and it complains error C2664: 'CreateFileW' : cannot convert parameter 1 from 'const char [5]' to 'LPCWSTR'

    OK, I guess it doesn't like "COM1" to be char* type,

    I tried casting it LPCWSTR("COM1"), then it compiles with no problem.

    However, it returns "ERROR opening serial port -1", so it doesn't find the com port successfully. I guess direct casting is not the right way?

    Please tell me what I should do to make this work.

    the msdn is not that helpful http://msdn.microsoft.com/en-us/library/ms810467.aspx

    I don't know what the "gszPort" means there