AnsweredAssumed Answered

Receive variable length buffer on UART (Interrupt)

Question asked by massimi.federico.001 on Apr 30, 2018

Hello,
in my project I have to receive commands from the serial port (UART), these commands are of variable length and end with carriage return (\r).
what I would like to do is generate an interrut when the \r is received and process the received buffer with "MyCallback".

looking on the internet I found this solution:

void USART2_IRQHandler(void)
{
  /* USER CODE BEGIN USART2_IRQn 0 */
     if(((READ_REG(huart2.Instance->ISR) & USART_ISR_RXNE) != RESET) && ((READ_REG(huart2.Instance->CR1) & USART_CR1_RXNEIE) != RESET)) {
          static uint8_t buffer_index = 0;
          uint8_t tmp = (uint8_t)((uint16_t) READ_REG(huart2.Instance->RDR) & (uint8_t)huart2.Mask);

          if(tmp != '\r' && buffer_index < huart2.RxXferSize) {
               huart2.pRxBuffPtr[buffer_index++] = tmp;
          } else{
               MyCallback((const char *)huart2.pRxBuffPtr, buffer_index);
               buffer_index = 0;
               memset(huart2.pRxBuffPtr, NULL_CHAR, huart2.RxXferSize); // clear buffer
          }
          
          CLEAR_BIT(READ_REG(huart2.Instance->ISR), USART_ISR_RXNE);
     } else {
  /* USER CODE END USART2_IRQn 0 */
  HAL_UART_IRQHandler(&huart2);
  /* USER CODE BEGIN USART2_IRQn 1 */
     }
  /* USER CODE END USART2_IRQn 1 */
}

 

 

at first sight it seems a little complicated, I wanted to ask first if this is the correct way to do what I need and if there are simpler ways to have the same result.

Thanks in advance.

Outcomes