User987123
User987123

Reputation: 97

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

Upvotes: 1

Views: 1443

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595402

 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.

Upvotes: 2

Thomas
Thomas

Reputation: 1

Try ReadFileEx instead of

It is asynchronous function

Upvotes: -1

Related Questions