I am developing an application that reads a fixed packet of data from a com port at regular intervals of 50ms. I am using
CreateFile
and
ReadFile
to open and read from the port respectively. There is a tiny amount of processing that happens with the data that is read.
Because timing is vital in such an application, I decided to check how long each of the separate tasks was taking. The
ReadFile
function was called at every 50ms or whenever the
EV_RXCHAR
event happened. The processing takes hardly a millisecond. This is all good. But the
ReadFile
function takes on an average 15ms to return. This seems like an awful lot of time to read data from a port. I am sending data to the port through a third-party application that writes data as packets, so it can't (I think) be because of its write speed.
This becomes an issue because of the following: I did the above tests with virtual com ports. When I test it with some physical hardware, the time taken can vary from 47ms to 127ms. The hardware is a card designed to package data and send them as packets. This amount of delay causes my application to go out of sync pretty quickly.
So any suggestions as to how I can speed this up, or maybe try a different strategy would be highly appreciated.
PS: I am doing non-overlapped read and write on purpose.
What I have tried:
I don't know what to add here, so I am adding my read function code. It is in an infinite loop until instructed otherwise.
void CGCUGUIDlg::fnRead()
{
while(m_bCount==true)
{
{
WaitCommEvent(m_hComm,&dwEventMask,NULL);
if(dwEventMask==EV_RXCHAR)
{
DWORD NoBytesRead;
BYTE abBuffer[100];
if(ReadFile((m_hComm),&abBuffer,sizeof(abBuffer),&NoBytesRead,0)) {
midTime1 = GetTickCount();
if(NoBytesRead==45)
{
if(abBuffer[0]==0x10&&abBuffer[1]==0x10||abBuffer[0]==0x80&&abBuffer[1]==0x80)
{
this->fnSetData(abBuffer);
}
else
{
CString value;
value.Append("Header match failed");
this->SetDlgItemText(IDC_RXRAW,value);
}
}
else if (NoBytesRead<45 && NoBytesRead>0)
{
CString value;
value.Append(LPCTSTR(abBuffer),NoBytesRead);
value.Append("\r\nInvalid Packet Size");
this->SetDlgItemText(IDC_RXRAW,value);
}
}
else
{
DWORD dwError2 = GetLastError();
CString error2;
error2.Format(_T("%d"),dwError2);
this->SetDlgItemText(IDC_RXRAW,error2);
}
}
}
}
CloseHandle(m_hComm);
}
PS: I apologise for the horrible formatting and random brackets.