Search code examples
c++winapiserial-portreadfile

C++: How to ignore ReadFile() if there is no new data from the serial port?


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
...

Solution

  •  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.