问题
In serial communication, ReadFile
doesn't return until reading as many as sizeToRead
parameter.
It is so weird, because actually until yesterday, it works normally with same code, same laptop, returning though it doesn't receive as many as sizeToRead
but any bytes.
But today my code show weird symptom like this.
serialHandle = CreateFile(L"\\\\.\\COM1",
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
DCB serialInfo = {0};
GetCommState(serialHandle, &serialInfo)
serialInfo.DCBlength = sizeof(DCB);
serialInfo.BaudRate = CBR_19200;
serialInfo.fBinary = TRUE;
serialInfo.fParity = TRUE;
serialInfo.fErrorChar = TRUE;
serialInfo.fNull = TRUE;
serialInfo.fAbortOnError = FALSE; //TODO
serialInfo.ByteSize = 8;
serialInfo.Parity = SPACEPARITY;
serialInfo.StopBits = ONESTOPBIT;
serialInfo.ErrorChar = 0xFF;
SetCommState(serialHandle, &serialInfo
ReadFile(serialHandle, buffer, numberOfBytesToRead, &numOfBytesRead, NULL)
numberOfBytesToRead is 256, So ReadFile return after getting 256 bytes
回答1:
ReadFile can return before reading numOfBytesRead based on a timeout, see SetCommTimeouts. If you have not initialized the timeout settings then you inherit whatever was set by other programs. So for consistent behavior 1you should call this API when you open the COM port.
来源:https://stackoverflow.com/questions/26947356/windows-readfile-doesnt-return-until-reading-sizetoread-value