STM32: Reading multi-byte sentence through UART (HAL) until the \n delimiter

New to embedded programming, coming from the world of backend development. In high-level programming, we have something like .ReadBytes("\n"), which returns a byte list/vector/slice or a string as whole. However, with UART/HAL in STM32, I see that the only option is to read a fixed amount of bytes, which doesn’t work in my case. How can I implement that .ReadBytes("\n") in STM32 w/ HAL?

I tried the following:

uint8_t buf[256];

int i = 0;

for (i = 0; i < 256; i++) {
    HAL_UART_Receive(&huart1, &buf[i], 1, HAL_MAX_DELAY);
    if (buf[i] == '\n') {

HAL_UART_Transmit(&huart2, &buf[0], i, HAL_MAX_DELAY)

And the code above kind of works; however, I see malformed data sent to the other UART interface, which makes me think that reading byte by byte is incredibly inefficient and the controller is just missing/dropping some of transmitted data.

Any help is greatly appreciated. :slight_smile:


We are looking into this and should have an answer soon.

Thank you

1 Like

Thank you! Eagerly waiting for a response :slight_smile:

Never used an STM32 but based on other 8 and 16 bit processors I guessed that the problem was trying to do anything useful in polled mode.

Had some time to look around and sure enough those are the polled mode commands which from the FAQ:

1. STM32 HAL UART supports 3 modes for transmitter (TX) / receiver (RX):

  • Polling mode (no DMA, no IRQ)
    • only possible for low baud rates, blocking

I suspect you’ll need to use interrupt driven or DMA mode for good reliability at any useful baud rate.

1 Like

Switching to interrupts for both UART interfaces worked. Nothing is lost now. Thanks a lot!

At this point I’m kind of surprised why they supply polling mode as the default. Interrupts are much better and they are as easy to deal with.

I wonder about that as well.

The only reason I could come up with was for educational use. I could see an instructor having the students start with polling @ 75 baud, moving higher, seeing the failure, then teaching the reasons why. It would help teach the inner workings of microcontrollers which was, maybe still is, essential for successful engineering of embedded systems.

When I learned back in the 90s we did some obviously outdated, now obsolete things to learn the inner working details e.g. program in machine code (no assembler), burn a rom with a 9V batteries