Skip to main content
SGonz.2
Associate III
April 7, 2022
Question

How to receive a variable length data using USART and DMA?

  • April 7, 2022
  • 4 replies
  • 1513 views

Hello!

I'm trying to receive a varible length data in USART2 and then send by USART1, but I receive the data and then a lot of spaces or newline characters.

Also, i tried to use callbacks but the output characters are wrong. I even have read about a ring buffer to work better with DMA, but I dont understand, I'm quite new to STM32 and don't know the best way to accomplish my work. Can you help me?

#define DATA_LENGTH 1 
uint8_t received_data;
 
while(1){
 HAL_UART_Receive_DMA(&huart2, received_data, DATA_LENGTH);
 HAL_UART_Transmit_DMA(&huart1, received_data, DATA_LENGTH);
}

This topic has been closed for replies.

4 replies

TDK
April 7, 2022

Using HAL_UARTEx_ReceiveToIdle_DMA is the supported HAL way of doing this. You can use it in circular mode but will need to handle the case in which the message wraps around the end of the buffer.

"If you feel a post has answered your question, please click ""Accept as Solution""."
SGonz.2
SGonz.2Author
Associate III
April 7, 2022

Thank you for your answer!

So, Do I need to use HAL_UARTEx_ReceiveToIdle_DMA and check the first and last element of my message and buffer?

And what about HAL_UART_Transmit_DMA? I should use something like HAL_UART_Transmit_DMA(&huart1, received_data[first], last-first );

TDK
April 7, 2022
Tesla DeLorean
Guru
April 7, 2022

>> I'm quite new to STM32 and don't know the best way to accomplish my work.

Which STM32?

Any other MCU experience from which to compare/contrast approaches?

HAL_UART_Receive_DMA();

HAL_UART_Transmit_DMA();

Both those return immediately, how's that going to work?

Think of the callback as a prequalified and specific interrupt driven service task;

You're going to need to do some management and pacing, so you only dispatch a Transmit when you have actual data to work with. Perhaps moving what's been received into a ring-buffer, so you can then reuse the receiver buffer, and then push out available data at each subsequent Transmit call back.

Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..