UART questions

I have a serial device that sends a 348 bytes data block upon reset.

Using the following code :

private void Uart_DataReceived(UartController sender, DataReceivedEventArgs e)
    Debug.WriteLine($"BTR = {_uart.BytesToRead}");
    Debug.WriteLine($"e.Count = {e.Count}");
    var btr = _uart.BytesToRead;
    var _buffer = new Byte[btr];
    while (btr != 0)
        _uart.Read(_buffer, 0, btr);
        btr = _uart.BytesToRead;

I get the following result(s) :

BTR = 348
e.Count = 1
BTR = 0
e.Count = 112
BTR = 0
e.Count = 141
BTR = 0
e.Count = 51
BTR = 0
e.Count = 43

Launching the program many times (like 10 times), I always get BTR= 348 (expected) and many DataReceived events (generally 5 or 6 events), with first one always giving e.Count = 1.
Last event e.Count value of 43 is not systematic, although it appears to be the same 90% of the time.

So my questions are :

  • why e.Count is not equal to _uart.BytesToRead() in the first event ?
  • why e.Count is always 1 in the first event received ?
  • why are there so many DataReceived events thrown even though there are no more BytesToRead after first read ? (I’ve tried to ClearReadBuffer() but it does not change anything)

The events come IN before ByteToRead, but come OUT later.

1 Like

The uart driver is building and queuing multiple events as the data arrives. By the time the first event is handled, all the data has been queued. Instead of just reading the data indicated by the e.count, you are reading all the data in the first event. When the additional events arrive, there is nothing left to read.


This indeed explains points 1 & 3 and I understand. Thank you !
Point 2 is still a mistery to me but I don’t really care, in fact.

That is because, the first event is always in ready state, as soon as first byte come.

So, when the first byte comes and the event is trigered, you must read the data wait some miliseconds before analyse it, i more data come in this interval you must ‘concatenate it’ with previous received data.
In my programs i have some methods to do this, and the data is only analysed after a time gap without data (tipically 200mS)

I have no problem dealing with data coming in chunks. :wink:
My questions were more related to the number of events thrown and the fact the BytesToRead info was known in the first of those events.