Boris
Boris

Reputation: 8951

Reading from serial port via ReadFile is very slow

I'm using the Win32 API to read data from a serial port:

DWORD numRead = 0;
ReadFile(mPortHandle, mReceiveBuffer.get(), mReceiveBufferSize, &numRead, nullptr);

This call takes extremely long: 129ms to be accurate (measured via QueryPerformanceCounter).

I did the measurement with several different hardware devices:

Evvery of these devices gives me exactly the same delay: 129ms. Thus I don't think its the hardware or the driver's fault (each device should be using a totally different driver, right?).

I also fiddled around with timeouts, but that did not change anything.

What else could it be?

Upvotes: 2

Views: 1214

Answers (2)

Boris
Boris

Reputation: 8951

OK, problem solved :-)

Until now I set the timeouts like this:

COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 1;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.ReadTotalTimeoutConstant = 1;
timeouts.WriteTotalTimeoutMultiplier = 1;
timeouts.WriteTotalTimeoutConstant = 1;

This does not work. If I only set the constant, it works though:

COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 1;
timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 0;

Now ReadFile returns within 1ms.

Upvotes: 2

kunif
kunif

Reputation: 4360

Perhaps it is because you always readfile by specifying the total size of the receive buffer.

Is the receive buffer size large?

If you register an event handler for the DataReceived event and only read the data that arrives in the buffer of the device driver, the extra waiting time will be reduced.

Upvotes: 0

Related Questions