cancel
Showing results for 
Search instead for 
Did you mean: 

HAL_UART_Receive doesn't block execution

skon.1
Senior

Helllo,

I'm working on the NUCLEO-F722ZE EVB.

I want my code to wait for a character to be received from UART 3 and do nothing.

This is what I wrote:

unibt8_t received_character = 0 ;
HAL_UART_Receive(&huart3, received_character, 1,1000) ;

From what I understand "HAL_UART_Receive" is a blocking function so it should block the code execution until a character is received. But for some reason my code doesn't stop and proceeds to the next line although no data was sent to the UART.

What am I doing wrong ?

9 REPLIES 9
TDK
Guru

> until a character is received.

Or until the timeout occurs. You have specified a 1000ms timeout.

The return value will be HAL_TIMEOUT in this case, which you can catch and handle appropriately.

If you feel a post has answered your question, please click "Accept as Solution".
skon.1
Senior

How can I make it wait indefinitely ?

TDK
Guru

0xFFFFFFFE gives you a timeout of 50 days.

Otherwise you need a loop:

while (HAL_UART_Receive(&huart3, &received_character, 1, 1000) == HAL_TIMEOUT);

Your code also has typos.

unibt8_t received_character = 0 ; // <-- unibt8_t is not a type
HAL_UART_Receive(&huart3, received_character, 1,1000) ; // <-- this writes to memory address 0. missing a & character

If you feel a post has answered your question, please click "Accept as Solution".
skon.1
Senior

Thanks.

What did you mean by:

"<-- unibt8_t is not a type" ?

S.Ma
Principal

Unless you really do expect only a single byte, I would strongly recommend at least to use interrupts which anyway are part of normal practice in microcontroller world. If you don't want interrupts and don't care the latency, use DMA with cyclic buffer (say 1024 bytes) so you can see what you receive in the buffer. Size the buffer so that its size don't overflow with the worst case polling delay.

skon.1
Senior

Yes, I get your point.

But for this peripheral - the single byte is a requirement.

I want the user to press on a single keyboard character to navigate in an internal menu.

I have another UART in the design that's intended to send/receive chunks of data with another device.

For that UART it'll probably be wise to use a DMA.

Are there official ST examples that showcase the usage of HAL functions ?

S.Ma
Principal

Go for interrupts and fill up the callback isr portion. That's futureproof. In polling monitor for the rxne flag prior to read the data byte.

Can you please post an example for this ?

TDK
Guru

> Are there official ST examples that showcase the usage of HAL functions ?

Here are three of many:

https://github.com/STMicroelectronics/STM32CubeF7/tree/master/Projects/STM32746G-Discovery/Examples/UART

If you feel a post has answered your question, please click "Accept as Solution".