I am working on a C++ program which can read from a serial port and write to a serial port. I have a problem at reading the data. If there is no new data, ReadFile()
is waiting until it receive new data.
My code to read the data:
while (!_kbhit())
{
if (!_kbhit())
{
if (ReadFile(hSerial, &c, 1, &dwBytesRead, NULL))
{
cout << c;
}
}
}
How can I check if there is no new data and skip the ReadFile()
line?
EDIT:
I was finally able to fix it. I changed my ReadFunction to this:
do
{
if (ReadFile(hSerial, &c, 1, &dwBytesRead, NULL))
{
if (isascii(c))
{
cout << c;
}
}
if (_kbhit())
{
key = _getch();
}
} while (key != 27);
And I added Timeouts like this:
serialHandle = CreateFile(LcomPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 1;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.ReadTotalTimeoutConstant = 1;
timeouts.WriteTotalTimeoutMultiplier = 1;
timeouts.WriteTotalTimeoutConstant = 1;
SetCommTimeouts(serialHandle, &timeouts);
// Call function to Read
...
If there is no new data,
ReadFile()
is waiting until it receive new data.
You can use SetCommTimeouts()
to configure a reading timeout so ReadFile()
will exit if no data arrives within the timeout interval.
Try ReadFileEx instead of
It is asynchronous function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.