A simplified example and descriptions can be found at
Serial Communications[
^].
When using overlapped I/O, you have to pass an overlapped structure to all
ReadFile()
and
WriteFile()
calls. For each operation that might be in a pending state you have to create an event, place the event handle in the corresponding overlapped structure, call
WaitForSingleObject()
/
WaitForMultipleObjects()
and
GetOverlappedResult()
when the event occured.
But with serial receiving it is often not predictable how many bytes may be received. Then you might also use serial events to be notified when data has been arrived. To do this call
SetCommMask()
with
EV_RXCHAR
and optionally
EV_ERR
, and in the receive loop
WaitCommEvent()
passing another overlapped structure. I have provided sample code once in this CP solution:
Serial Communication issue[
^]
Upon the
EV_RXCHAR
and
EV_ERR
events call then
ClearCommError()
to check for errors and get the number of available bytes. When passing the number of available bytes from the above to
ReadFile()
, you can simple use an empty overlapped structure there because the call will return immediately (no pending). When using the code from my above solution it should look like:
OVERLAPPED ovRead = {0};
if (nEvent & (EV_RXCHAR | EV_ERR))
{
DWORD dwComErrors = 0;
COMSTAT tComStat;
::ClearCommError(m_hCom, &dwComErrors, &tComStat);
if (dwComErrors)
{
}
if (tComStat.cbInQue)
{
DWORD dwRead;
::ReadFile(m_hCom, pBuf, tComStat.cbInQue, &dwRead, &ovRead);
}
}
Quote:
To receive safely, I was recommened that "using overlapped variable" in the ReadFile() do not lost any character in the serial commnication - is this right?
That is not right because the internal receive buffer may still overrun when receive events are not handled in time.