cancel
Showing results for 
Search instead for 
Did you mean: 

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

SGonz.2
Associate II

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);
}

4 REPLIES 4
TDK
Guru

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
Associate II

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
Guru

>> 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
Up vote any posts that you find helpful, it shows what's working..