1. STM32串口默认是打开Overrun、DMA on RX Error
2. 使用HAL库,打开Overrun
如果出现错误,HAL库函数会关闭接收,再调用错误回调函数(用户需实现,不然串口接收不再工作,从外部看串口死机)
void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
{
errorcode = huart->ErrorCode;
if ((HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) ||
((errorcode & (HAL_UART_ERROR_RTO | HAL_UART_ERROR_ORE)) != 0U))
{
/* Blocking error : transfer is aborted
Set the UART state ready to be able to start again the process,
Disable Rx Interrupts, and disable Rx DMA request, if ongoing */
UART_EndRxTransfer(huart); //关闭接收
HAL_UART_ErrorCallback(huart); //调用错误回调函数
}
}
HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart)
{
if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT)
{
UART_AdvFeatureConfig(huart);
}
}
所以需在错误回调中重新开启接收
uint8_t buf[10];
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
if(huart == &huart1)
{
__HAL_UNLOCK(huart);
HAL_UART_Receive_IT(&huart1,buf,1);
}
}
/**
* @brief Configure the UART peripheral advanced features.
* @param huart UART handle.
* @retval None
*/
void UART_AdvFeatureConfig(UART_HandleTypeDef *huart)
{
/* Check whether the set of advanced features to configure is properly set */
assert_param(IS_UART_ADVFEATURE_INIT(huart->AdvancedInit.AdvFeatureInit));
/* if required, configure RX overrun detection disabling */
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXOVERRUNDISABLE_INIT))
{
assert_param(IS_UART_OVERRUN(huart->AdvancedInit.OverrunDisable));
MODIFY_REG(huart->Instance->CR3, USART_CR3_OVRDIS, huart->AdvancedInit.OverrunDisable);
}
/* if required, configure DMA disabling on reception error */
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DMADISABLEONERROR_INIT))
{
assert_param(IS_UART_ADVFEATURE_DMAONRXERROR(huart->AdvancedInit.DMADisableonRxError));
MODIFY_REG(huart->Instance->CR3, USART_CR3_DDRE, huart->AdvancedInit.DMADisableonRxError);
}
}