Electrical – How to know UART DMA TX is finished for RS485 enable process in STM32F4 CubeMX

hal-libraryrs485stm32stm32f4uart

I am using STM32F4 series MCU with STM32CubeMX enviroment. I can send and receive data without problem in RS232 physical layer.

My problem is that when I use with it in RS-485 physical layer, I should know when transmission process is finished, last bit is sent from shift register and I am ready to terminate transmit function and enable receive function of RS-485 chip.

What is the flag convention of UART_Busy_Flag or related flag with this process.

Best Answer

You should use the following function:

HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)

and make sure that the UART and the DMA interrupts are enabled.

If you look into the implementation, (only a part of it):

/* Set the UART DMA transfer complete callback */
huart->hdmatx->XferCpltCallback = UART_DMATransmitCplt;

/* Set the UART DMA Half transfer complete callback */
huart->hdmatx->XferHalfCpltCallback = UART_DMATxHalfCplt;

/* Set the DMA error callback */
huart->hdmatx->XferErrorCallback = UART_DMAError;

/* Enable the UART transmit DMA Stream */
tmp = (uint32_t*)&pData;
HAL_DMA_Start_IT(huart->hdmatx, *(uint32_t*)tmp, (uint32_t)&huart->Instance->DR, Size);

The DMA will be started in IT mode, and there are three HAL_UART callbacks which will be called by the callback functions above.

  1. Transmit complete callback: HAL_UART_TxCpltCallback
  2. Half of the bytes are sent: HAL_UART_TxHalfCpltCallback
  3. Error: HAL_UART_ErrorCallback

All of these have weak declaration so you have to implement them. For example:

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1)  // change USART instance
    {
       // Transmit complete handle RS-485 related stuff
    }
}