2017-03-16 02:48 AM
Good morning, I'm making a program that should receive from the UART a variable length message. The message ends with '\n'
I tried it with this
uint8_t rxChar=0;
int main() {
HAL_UART_Receive_IT(&huart2, &rxChar, 1);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
/ /appendCharToBuffer
rxChar
HAL_UART_Receive_IT(&huart2, &rxChar, 1);
}
but after receiving two bytes I have a 'overrun error'.
using
HAL_UART_Receive_IT(&huart2, serial_command_buffer, COMMAND_BUFFER);
works, but the message must be at least
COMMAND_BUFFER char length.
Is possile to generate an interrupt when UART receives an '\n' although have not yet been receivedCOMMAND_BUFFER
characters? Or can I use an approach like the previous one without causing an overrun error?or what is the proper way to handle the need to receive a variable length message?
Thanks in advance
2017-03-24 05:07 AM
After several attempts I found a solution.
In the main I simply add this line
HAL_UART_Receive_IT(&huart2, rxBuffer, RX_BUFFER_SIZE)
then in the 'STM32L4xx_it.c' file I modified the
function
'USART2_IRQHandler' in this way:/* 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 != '\n'&& buffer_index < huart2.RxXferSize) {
huart2.pRxBuffPtr[buffer_index++] = tmp; } else{ MyCallback(huart2.pRxBuffPtr, buffer_index); buffer_index = 0; memset(huart2.pRxBuffPtr, '\0', 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 */I do not know if this is the best way, but it works.