Reputation: 589
I'm testing serial port communication by connecting COM port RD and TD pins together. The COM port has been initialized before the code below is executed.
CString cs_Send = "F: 5000000 Hz, SF: 1.0, Phase: 10, Position: 50, on sample 1";
BOOL bWriteRC = false;
BOOL bReadRC = false;
DWORD iBytesWritten = 0;
char readBuffer[256] = {"\0"};
DWORD read;
bWriteRC = WriteFile(hPort,cs_Send.GetBuffer(10),cs_Send.GetLength(),&iBytesWritten,NULL);
**Sleep(1000);// Thanks for the advice!!! this Sleep() will fix this error.**
bReadRC = ReadFile(hPort,readBuffer,sizeof(readBuffer),&read,NULL);
if(bWriteRC)
{
if(bReadRC)
{
AfxMessageBox(readBuffer, MB_OK);
}
}
The bWriteRC and bReadRC always return true. But the first message is completely blank. And if I run this more than twice, every message after the 1st is exactly same as what I sent. I wonder why the first one is always blank.
Upvotes: 2
Views: 1697
Reputation: 1923
Typically the WriteFile
and WriteFileEx
functions write data to an internal buffer that the operating system writes to a disk or communication pipe on a regular basis. The FlushFileBuffers
function writes all the buffered information for a specified file to the device or pipe.
call FlushFileBuffers
after calling WriteFile
.
See FlushFileBuffers for more details.
Upvotes: 2