cancel
Showing results for 
Search instead for 
Did you mean: 

Tx to Rx UART DMA loopback

skon.1
Senior

Hello,

The Tx and Rx pins of UART 4 in my code are shorted. 

I want to send an incrementing array from the Tx pin and receive it back from the Rx pin.

For this I wrote a for loop that increments every element of the array. The for loop is run from the callback function of HAL_UART_Receive_DMA. 

But I receive "uart4_rx_buffer" only once.

What's wrong with my code ?

uint8_t uart4_tx_buffer [ 8 ] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 } ;
uint8_t uart4_rx_buffer [ 8 ] = { 0 } ;
 
int main(void)
{
  HAL_Init();
  SystemClock_Config();
  MX_DMA_Init();
  MX_UART4_Init();
 
  HAL_UART_Receive_DMA ( & huart4 , uart4_rx_buffer , 8 ) ;
  HAL_UART_Transmit_DMA ( & huart4 , uart4_tx_buffer , 8 ) ;
  while ( 1 ) ;
}
 
void HAL_UART_RxCpltCallback ( UART_HandleTypeDef * huart )
{
  for ( int index = 0 ; uart4_tx_buffer < 8 ; index ++ )
  {
    uart4_tx_buffer [ index ] = uart4_tx_buffer [ index ] + 8 ;
    HAL_UART_Transmit_DMA ( & huart4 , uart4_tx_buffer , 8 ) ;
  }
}  

3 REPLIES 3
TDK
Guru

One you receive the first 8 characters, the reception is done. If you want to receive data again, you need to call HAL_UART_Receive_DMA again.

Also, you're calling HAL_UART_Transmit_DMA repeatedly with no delay within HAL_UART_RxCpltCallback. First, calling it within its own interrupt will prevent any callbacks from happening. Second, calling it when it's already busy doing the previous transmit isn't going to work. There are other logic errors at work here as well.

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

Thanks,

Can you please explain how IT SHOULD be done ?

skon.1
Senior

Hi, I did some modifications to the code.

  1. I'm calling HAL_UART_Transmit_DMA from the callback of HAL_UART_Receive_DMA
  2. I'm calling HAL_UART_Receive_DMA from it's own callback

But is still doesn't work. Data is received only once.

uint8_t uart4_tx_buffer [ 8 ] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 } ;
uint8_t uart4_rx_buffer [ 8 ] = { 0 } ;
 
int main(void)
{
 HAL_Init();
 SystemClock_Config();
 MX_DMA_Init();
 MX_UART4_Init();
 HAL_UART_Receive_DMA ( & huart4 , uart4_rx_buffer , 8 ) ;
 HAL_UART_Transmit_DMA ( & huart4 , uart4_tx_buffer , 8 ) ;
 while ( 1 ) ;
}
void HAL_UART_RxCpltCallback ( UART_HandleTypeDef * huart )
{
	for ( int index = 0 ; index < 8 ; index ++ )
	{
		uart4_tx_buffer [ index ] = uart4_tx_buffer [ index ] + 8 ;
	}
 HAL_UART_Receive_DMA ( & huart4 , uart4_rx_buffer , 8 ) ;
 HAL_UART_Transmit_DMA ( & huart4 , uart4_tx_buffer , 8 ) ;
}