How to correctly use HAL_UART_Receive_IT when sending&receiving data?
I try to use UART to transmit and receive from the same port (transmit query to device, receive response). I receive 1 byte at time, because of unknown message length.
Problem is that I first needed to flush uart RX to clear interrupt status, otherwise interrupt will fire immidiately. Then when I flush it, I get overrun error, and need to clear that flag as well.
These problems indicate that I must use HAL UART incorrectly.
Currently I use HAL UART like this:
When sending:
//disable uart RX before transmitting
HAL_UART_AbortReceive(myUart);
//send data over usart
if (HAL_UART_Transmit_IT(myUart, data, len) != 0)
{
//TODO: handle error
}
...
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *UartHandle)
{
if (UartHandle->Instance == huart7.Instance)
{
//I need to clear overrun flag
__HAL_UART_CLEAR_OREFLAG(myUart);
//I need to flush rx data, otherwise RX interrupt will fire immidiately
__HAL_UART_SEND_REQ(myUart, UART_RXDATA_FLUSH_REQUEST);
//enable receive after transmit
if (HAL_UART_Receive_IT(myUart, &RxBuffer, 1) != 0)
{
//TODO: handle error
}
}
}When receiving:
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)
{
if (UartHandle->Instance == huart7.Instance)
{
//store data
...
//I need to clear overrun flag
__HAL_UART_CLEAR_OREFLAG(myUart);
//I need to flush rx data, otherwise RX interrupt will fire immidiately
__HAL_UART_SEND_REQ(myUart, UART_RXDATA_FLUSH_REQUEST);
//reactivate uart interrupt for 1 byte
if (HAL_UART_Receive_IT(myUart, &RxBuffer, 1) != 0)
{
//TODO: handle error
}
}
}I have many questions how to use this HAL UART;
- Is it valid to re-activate UART interrupt by calling HAL_UART_Receive_IT in HAL_UART_RxCpltCallback, within interrupt context?
- Should I use HAL_UART_Receive_IT to reactivate interrupts for UART? Or some other function?
- Am I appropriately stopping UART receive with HAL_UART_AbortReceive?
- Is it necessary to clear any USART flags before reactivating HAL_UART_Receive_IT?
I cannot find any good examples of using HAL UART in such scenario (transmit&receive from same uart), and keep encountering problems if try to use this HAL myself.
TL;DR: How to use HAL UART in interrupt mode when sending & transmitting data?
