AnsweredAssumed Answered

STM32L4: how to read from UART without knowing message length?

Question asked by Sven Köhler on Mar 16, 2018
Latest reply on Mar 18, 2018 by Sven Köhler

I am trying to use USART2 of my Nucleo L476RG board. It is connected to the UART of the ST-LINK on the board. 

I'm trying to implement a simple line-based protocol (every message is terminated by \r or \n). For starters, I try to implement a simple "echo server" which sends every received line back to the sender. 


I get the feeling that the HAL is completely unsuitable here. One would expect, that the HAL_UART_Receive function (receive without callbacks) would return the number of bytes received. That is not the case. When using HAL_UART_Receive_IT, one would expect that the HAL_UART_RxCpltCallback callback would receive some information about how many bytes were received. That is not the case.


In fact, HAL_UART_Receive returns only after the specified number of bytes have been received. In fact, HAL_UART_Receive_IT only calls the callback, after the specified number of bytes have been received.


After my simple echo server is complete, my next step would be to implement a simple software FIFO buffer. Any data received via USART2 would go into that buffer. Whatever is received via the UART is transferred into the software buffer until the buffer is full.Any operating system has such a buffer, as the hardware buffers are usually not big enough. Again, the HAL UART interface doesn't seem to allow to implement that.


I googled and it seems that STM microcontrollers implement some sort of "idle detection". When no data is received for some time, the U(S)ART interrupt is triggered even if there's just a single byte in the hardware buffer.


Some people claimed that HAL simply does neither enable nor support that idle detection. If that was true, HAL would be useless for any sort of generic buffering (as described above) and it would be useless for any protocol with variable-length messages (such as line-based protocols). To be honest, I can't believe it. Some Modem from the 1980s supports a line-based protocol via RS232, but my HAL-based STM32 application in 2018 can't.


Are those people correct? Am I missing some API here, that would enable this idle detection? I find it mentioned nowhere in the HAL code. Also, the API does not even seem to be prepared. No information about how many bytes have been received can be returned by any of the receive functions. To do so, is a pretty standard way of designing any sort of receive/read function.


Reading byte by byte in the main loop is not an option. Reading byte by byte via interrupts would cause way to many interrupts (if it would work at all).