cancel
Showing results for 
Search instead for 
Did you mean: 

STM32 UART always times out

HamzaBeder
Associate

Hello,

I am testing UART via a loopback test. This shows that the expected data is being sent on TX and received on RX, but the receive function always times out.

This post stated to clear the OVR and RXNE flags before calling the receive function, but that did not fix the issue.

My program gets stuck in the while loop while ((__HAL_UART_GET_FLAG(huart, Flag) ? SET : RESET) == Status)inside stm32l4xx_hal_uart.c, where Flag = RXNE. While RXNE is set before calling HAL_UART_Receive, it gets reset on the line if (huart->RxState == HAL_UART_STATE_READY), so the while loop never exits. I am not sure why this line resets RXNE.

I have tried different UART peripherals (USART1,2,3) as well as different pins. I also tried using interrupts with UART. Doing this did not fix the issue either.

Any possible solutions would be appreciated. Thanks.

int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART3_UART_Init();
while (1)
{
uint8_t arr[3] = {2,4,6};
uint8_t buffer[3];
if(__HAL_UART_GET_FLAG(&huart3, UART_FLAG_RXNE)){
uint8_t temp = (uint8_t)(huart3.Instance->RDR);
}
HAL_UART_Transmit(&huart3, arr, sizeof(arr), HAL_MAX_DELAY);
if(__HAL_UART_GET_FLAG(&huart3, UART_FLAG_ORE)){
__HAL_UART_CLEAR_OREFLAG(&huart3);
}
HAL_UART_Receive(&huart3, buffer, sizeof(buffer), 100);
}
}

 

1 ACCEPTED SOLUTION

Accepted Solutions

There's no magic which would hold all the transmitted data until HAL_UART_Transmit() finishes to wait for the HAL_UART_Receive() to start. In other words, you have to simultaneously transmit and pick whatever data arrive at the UART receiver.

This is best accomplished using interrupt-driven UART receiver.

JW

View solution in original post

2 REPLIES 2

There's no magic which would hold all the transmitted data until HAL_UART_Transmit() finishes to wait for the HAL_UART_Receive() to start. In other words, you have to simultaneously transmit and pick whatever data arrive at the UART receiver.

This is best accomplished using interrupt-driven UART receiver.

JW


@HamzaBeder wrote:

This shows that the expected data is being sent on TX and received on RX


It's better to put the image in the post - where we can see it:

AndrewNeil_1-1736862780380.png

You can just copy & paste into the post, or upload the image file.

Note also that using the </> button will give syntax highlighting to your code - see:

https://community.st.com/t5/community-guidelines/how-to-write-your-question-to-maximize-your-chances-to-find-a/ta-p/575228

 

As @waclawek.jan said, your code sends 3 bytes then, only after that's all done and finished, it tries to receive 3 bytes - clearly, that's not going to work!

You might get away with sending 1 byte, then reading 1 byte from the UART's RX register - but I'm not sure the HAL_UART_Receive function works that way ...