need to receive data from serialport. I wrote a program with Windows.h library, using C++, Visual Studio 2010..
I receive all datas from an electronic card, we communicate by handshaking...
I've made the necessary adjustments for handshaking as shown below:
DCB dcb;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fOutxCtsFlow = TRUE;
dcb.fOutxDsrFlow = TRUE;
dcb.fBinary = TRUE;
dcb.fParity = FALSE;
dcb.fNull = FALSE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
Then I set RTS and DTR bits to say I'm ready to receive data as shown below. This one is the function I call:
bool ImSeriAygit::setHardwareControl(bool hardwareControl)
{
DCB dcb;
myHardwareControl = hardwareControl;
if (getStatus() != STATUS_OPEN)
return true;
if (!GetCommState(myPort, &dcb))
{
printf("ImSeriAygit::setHardwareControl: Could not get port Data.\n");
return false;
}
if(myHardwareControl == 0)
{
dcb.fRtsControl = RTS_CONTROL_ENABLE;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
}
else
{
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
}
if (!SetCommState(myPort, &dcb))
{
printf("ImSeriAygit::setHardwareControl: Could not set port Data.\n");
return false;
}
return true;
}
This is how I call it:
ser.setHardwareControl(false); // ser is the ImSeriAygit object.
After that I read the serial port using ReadFile function as shown below:
int ImSeriAygit::read(const char *data, unsigned int size,
unsigned int msWait)
{
COMSTAT stat;
unsigned long ret;
unsigned int numToRead;
if (myPort != INVALID_HANDLE_VALUE && myStatus == STATUS_OPEN)
{
if (!ClearCommError(myPort, &ret, &stat))
return -1;
if (stat.cbInQue == 0)
return 0;
if (stat.cbInQue > size)
numToRead = size;
else
numToRead = stat.cbInQue;
if(get
if (ReadFile( myPort, (void *)data, numToRead, &ret, NULL))
{
return (int)ret;
}
else
{
printf("ArSerialConnection::read: Read failed.\n");
return -1;
}
}
printf("ArSerialConnection::read: Connection invalid.\n");
return -1;
}
When I debug my program, I realised that sometimes the data I read is corrupted, which is in fact in a suitable form, but sometimes there is no corruption...
I guess I don't catch the incoming data properly although I'm handshaking...
Any suggestions to know if the data comes in time? My best regards...