I’m trying to set the communication with an arduino nano.
I’m exploring the use of overlapped I/O, this is just a test and I am aware that I have no interest in using overlapped I/O in this state.
I’m using an arduino nano that sends a character (“p”) every seconds with the Serial.print
.
I’m calling the WaitCommEvent
in a loop.
My issue is, if I remove the call to the Sleep
before the WaitCommEvent
, the character sent by the arduino isn’t displayed anymore.
Here is an abstract of how my code works :
- Open the comm port by calling
CreateFile
with theFILE_FLAG_OVERLAPPED
flag. - Call the
setCommMask
,setCommTimeout
- Create the appropriate event in the Overlapped structure
- Call
WaitCommEvent
with the overlapped structure. - Then
WaitForSingleObject
on the event. - ReadFile when the event is signaled.
while (1) {
Status = SetCommMask(hComm, EV_RXCHAR); // | EV_CTS | EV_DSR | EV_TXEMPTY | EV_ERR | EV_RLSD
if (Status == FALSE)
{
printf_s("nError to in Setting CommMasknn");
CloseHandle(hComm);
}
//Setting WaitComm() Event
dwEventMask = NULL;
char ReadData[100] = { 0 }; //temporary Character
Sleep(500);
Status = WaitCommEvent(hComm, &dwEventMask, &o); //Wait for the character to be received
if (GetLastError() != ERROR_IO_PENDING) {
printf("IO_NOT_PENDING %dn", GetLastError());
}
DWORD lpModemStat;
dwRes = WaitForSingleObject(o.hEvent, INFINITE);
switch (dwRes) {
case WAIT_OBJECT_0:
if (!GetOverlappedResult(hComm, &o, &dwRead, FALSE)) {
DWORD err = GetLastError();
printf("OVERLAPPED ERROR %dn", err);
}
printf("n read %dn", dwRead);
if (dwEventMask & EV_RXCHAR) {
Status = ReadFile(hComm, &ReadData, sizeof(ReadData), &NoBytesRead, &o);
ResetEvent(o.hEvent);
for (int i = 0; i < 100; i++) {
std::cout << ReadData[i];
}
}
break;
case WAIT_TIMEOUT:
break;
default:
break;
}
}
I put the setCommMask in the loop because if I don’t, I get an error on the WaitCommeEvent that returns the code 87 – The parameter is incorrect.
I think there is something wrong with the way I use the functions or in my understanding.