Showing results for 
Search instead for 
Did you mean: 

Validating received UART message


Sorry if this is a rookie question. I have set up USART 2 to receive a UART command. If the sent command is "<EN>", I need to toggle the value of a global state variable. When transmitting the received data via the callback interrupt, I have no issues, so I know that UART is receiving the data no problem. My issue is with checking that the value of the data received is indeed "<EN>".  I've attached the contents of my callback function as it currently stands.

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){
if (huart->Instance == USART2 && strncmp((char*)huart->pRxBuffPtr, "<EN>", 4) == 0)
state = !state; //Toggle state variable
memset(rx_data, 0, 1); //Clear data buffer
  HAL_UART_Receive_IT(&huart2, rx_data, 1); //Receive next command


I believe that I might have to use a larger buffer, and fill it with every character, then perform a check on that. As it currently stands, the code runs, but the state variable isn't changed upon receiving the "<EN>" command. Any help is appreciated.

ST Employee

Hello @willgordge ,

I'm missing some context about the product series you are using but from you description i understand that you are facing troubles with received buffer comparison so i recommend implementing the following function and calling it instead of strcmp :

  * @brief  Compares two buffers.
  * @param  pBuffer, pBuffer1: buffers to be compared.
  * @param  uwBufferLenght: buffer's length
  * @retval 1: pBuffer identical to pBuffer1
  *         0: pBuffer differs from pBuffer1
static TestStatus Buffercmp(uint8_t* pBuffer, uint8_t* pBuffer1, uint32_t uwBufferLenght)
  uint32_t counter = 0;
    if(*pBuffer != *pBuffer1)
      return FAILED;


  return PASSED;
In order to give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.

It is not reading a string, the buffer isn't NUL terminated.

There's no guarantee that the characters in the buffer will start as expected. You need to synchronize the flow, to recognize the first character.

You'll want to accumulate the data in a buffer, reset the index to zero when the '<' arrives, and check the buffer once you've accumulated four characters.

Watch for errors, clear overflow, noise or framing errors if they occur.

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