1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
// Note as it's just a quick test I'm using -A entrypoints
// to avoid TCHAR confusion...
#define WIN32_LEAN_AND_MEAN
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdio.h>
class RUSerial
{
private:
HANDLE portHandle;
public:
RUSerial() : portHandle(INVALID_HANDLE_VALUE)
{
}
~RUSerial()
{
if(portIsOpen())
closePort();
}
DWORD openPort(const char* comPort, const char flag155);
void closePort();
bool portIsOpen()
{
return (INVALID_HANDLE_VALUE != portHandle);
}
};
int main()
{
RUSerial port;
for(int N = 0; 16 > N; ++N)
{
char portName[16] = "";
sprintf(portName, "COM%d", N);
char portPath[16] = "";
sprintf(portPath, "\\\\.\\%s", portName);
DWORD retCode = port.openPort(portPath, 1); //call in main body to open port
if(port.portIsOpen()) // could/should check retCode, too
{
printf("%s opened successfully\n", portName);
port.closePort();
}
else
{
printf("%s could not be opened\n", portName);
char* errMsg = NULL;
FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, retCode, 0, (char*)&errMsg, 1024, NULL);
printf("openPort returned %d : %s", retCode, errMsg);
LocalFree(errMsg);
}
printf("\n");
}
return 0;
}
DWORD RUSerial::openPort(const char* comPort, const char /*flag155*/)
{
DWORD retCode = NOERROR;
//Open the serial port device driver
portHandle = CreateFileA(comPort, GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);
if(portHandle == INVALID_HANDLE_VALUE)
{
retCode = GetLastError();
}
return retCode;
}
void RUSerial::closePort()
{
CloseHandle(portHandle);
portHandle = INVALID_HANDLE_VALUE;
}
|