|
void ReportCommError(LPTSTR lpszMessage);
DWORD WINAPI CommReadThreadFunc(LPVOID lpParam);
BOOL SendText(HWND hWnd);
HANDLE hCommPort = INVALID_HANDLE_VALUE;
void Listing9_1()
{
hCommPort = CreateFile (_T("COM1:"),
GENERIC_READ | GENERIC_WRITE,
0, // COM port cannot be shared
NULL, // Always NULL for Windows CE
OPEN_EXISTING,
0, // Non-overlapped operation only
NULL); // Always NULL for Windows CE
if(hCommPort == INVALID_HANDLE_VALUE)
{
ReportCommError(_T("Opening Comms Port."));
return;
}
// set the timeouts to specify the behavior of
// reads and writes.
COMMTIMEOUTS ct;
ct.ReadIntervalTimeout = MAXDWORD;
ct.ReadTotalTimeoutMultiplier = 0;
ct.ReadTotalTimeoutConstant = 0;
ct.WriteTotalTimeoutMultiplier = 10;
ct.WriteTotalTimeoutConstant = 1000;
if(!SetCommTimeouts(hCommPort, &ct))
{
ReportCommError(_T("Setting comm. timeouts."));
Listing9_2(); // close comm port
return;
}
// Get the current communications parameters,
// and configure baud rate
DCB dcb;
dcb.DCBlength = sizeof(DCB);
if(!GetCommState(hCommPort, &dcb))
{
ReportCommError(_T("Getting Comms. State."));
Listing9_2(); // close comm port
return;
}
dcb.BaudRate = CBR_19200; // set baud rate to 19,200
dcb.fOutxCtsFlow = TRUE;
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fOutxDsrFlow = FALSE;
dcb.fOutX = FALSE; // no XON/XOFF control
dcb.fInX = FALSE;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if(!SetCommState(hCommPort, &dcb))
{
ReportCommError(_T("Setting Comms. State."));
Listing9_2(); // close comm port
return;
}
// now need to create the thread that will
// be reading the comms port
HANDLE hCommReadThread = CreateThread(NULL, 0,
CommReadThreadFunc, NULL, 0, NULL);
if(hCommReadThread == NULL)
{
ReportCommError(_T("Creating Thread."));
Listing9_2(); // close comm port
return;
}
else
CloseHandle(hCommReadThread);
}
void ReportCommError(LPTSTR lpszMessage)
{
TCHAR szBuffer[200];
wsprintf(szBuffer,
_T("Communications Error %d \r\n%s"),
GetLastError(),
lpszMessage);
cout ? szBuffer ? endl;
}
|
|