Receiving Characters From UART Corrupts Memory
While attempting to debug missing characters in a string received through the UART interface, I found possible memory corruption in a temporary global variable used for debugging.
// pUART2Rx[2] is global:
uint8_t pUART2Rx[2]; /**< UART2 Rx DMA buffer for receiving commands */
// Executed in an initialization function:
HAL_UART_Receive_DMA( &huart2, pUART2Rx, 2 );
// Temporary global to determine which callback
// is called first
volatile unsigned int uiUART_Count = 0;
/**
* @brief Rx Half Transfer completed callbacks.
* @param huart: UART handle
* @retval None
*/
void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart)
{ volatile portBASE_TYPE xHigherPriorityTaskWoken;
if( huart == &huart2 )
{ uiUART_Count++;
if( uiUART_Count >=2 )
// A convenient statement to break on:
xHigherPriorityTaskWoken = pdFALSE;
/* Code removed here to find out if it is taking too long to execute.
*/
}
}
/**
* @brief Rx Transfer completed callbacks
* @param huart: uart handle
* @retval None
*/
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{ volatile portBASE_TYPE xHigherPriorityTaskWoken;
if( huart == &huart2 )
{ uiUART_Count++;
if( uiUART_Count >= 2 )
// A convenient statement to break on:
xHigherPriorityTaskWoken = pdFALSE;
/* Code removed here to find out if it is taking too long to execute.
*/
}
}
In the above code uiUART_Count is a temporary variable used to determine which callback is called first. Right up until the time some characters are sent to the processor’s UART the uiUART_Count variable is equal to zero, which is its initialzed value. As soon as characters are received by the UART and the first callback is called, and before the uiUART_Count++ statement is executed, the uiUART_Count value is 0xffffff00 according to the expressions tab.
The address of uiUART_Count is 0x200007c8. The Memory tab shows values of 0xffffff00 from 0x20000680 right up to and including where uiUART_Count is at 0x200007c8. Right after that address the memory values are 0x00000000 up to and including the 0x2000081C address.
This looks like memory is being filled with a test pattern between the time the characters are received and the callback is called. This test pattern is corrupting uiUART_Count. What could be doing this?
I am receiving the characters one at a time because the received characters are commands of varing length, and so it is necessary to test for a line terminator as each character is received. When the line terminator is received the command is executed. Another reason for receiving them one at a time is to echo the characters as they are received.


