cstm32stm32f4discoverystm32f1

Why does UART keep continuing to write my 25 byte buffer which byte it left off?


I have an interrupt (RXNE) based receive cycle running on STM32F1. I do only use receive command which is:

HAL_UART_Receive_IT(&huart3, RxBuffer, sizeof(RxBuffer));

Thus I receive a message then write my buffer which is:

uint8_t RxBuffer[25];

After using RxBuffer's content, I am clearing this array using this function:

memset(RxBuffer, '\0', sizeof(RxBuffer));

The incoming data is never bigger than 24 byte btw. It's all OK until another data is received and written to RxBuffer. When next data is received something strange is happening and HAL_UART_Receive_IT(&huart3, RxBuffer, sizeof(RxBuffer)); function is starting to fill the data to my RxBuffer which byte it left off on last receive.

For example;

1 -> RxBuffer is normally initialized with NULL

RxBuffer = {'\0', '\0', '\0', '\0', ... '\0'} (25 bytes NULL)

2 -> After receiving first data it becomes like this

RxBufer = "xc32 CMD1 400 200 50" (it's 20 bytes total and last 5 bytes are still NULL)

RxBuffer = {'x', 'c', '3', '2', ' ', 'C' ... '\0', '\0', '\0'}

3 -> Then I clear the buffer content using memset(...) function.

RxBuffer = {'\0', '\0', '\0', '\0', ... '\0'} (25 bytes NULL again)

4 -> After receiving another data like "xc32 CMD2":

RxBuffer = {'C', 'M', 'D', '2', '\0', '\0', '\0' ... 'x', 'c', '3', '2', ' '} (still 25 bytes of data but UART begins to write data which byte it left off last time, and it becomes some shifted shit..)

It's behaving like a ring buffer. How to properly do this receive process to make it begin 0th index of buffer every single receive?


Solution

  • The problem can be solved by receiving data byte-by-byte using DMA.

    char rx_buff[10];
    HAL_UART_Receive_DMA(&huart1, (uint8_t*)rx_buff, 1);
    
    void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
    {
        ...
        array[i++] = rx_buff[0];
        /* Then reset buffer using bzero() or memset() */
    }