stm32的Hal库函数,串口卡死解决方法
HAL库中强制对串口进行了半双工限制,其实STM32的串口是全双工的,很多时候卡死,是因为我们做了全双工操作导致的卡死,卡死在HAL_LOCK(huart)。
初始化如下:
/* USART2 init function */
void MX_USART2_UART_Init(void)
{huart2.Instance = USART2;huart2.Init.BaudRate = 2400;huart2.Init.WordLength = UART_WORDLENGTH_8B;huart2.Init.StopBits = UART_STOPBITS_1;huart2.Init.Parity = UART_PARITY_NONE;huart2.Init.Mode = UART_MODE_TX_RX;huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;huart2.Init.OverSampling = UART_OVERSAMPLING_16;huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;if (HAL_UART_Init(&huart2) != HAL_OK){Error_Handler();}SET_BIT(USART2->CR1, USART_CR1_RXNEIE);//使能 RX中断
}
//HAL_UART_Init 函数调用 HAL_UART_MspInit函数
void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{GPIO_InitTypeDef GPIO_InitStruct;if(uartHandle->Instance==USART2){__HAL_RCC_USART2_CLK_ENABLE();__HAL_RCC_GPIOA_CLK_ENABLE();/**USART2 GPIO Configuration PA2 ------> USART2_TXPA3 ------> USART2_RX */GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;GPIO_InitStruct.Pull = GPIO_NOPULL;GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;GPIO_InitStruct.Alternate = GPIO_AF4_USART2;HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);/* USART2 interrupt Init */HAL_NVIC_SetPriority(USART2_IRQn, 0, 0);HAL_NVIC_EnableIRQ(USART2_IRQn);}
}
//发送函数
#define COUNTOF(__BUFFER__) (sizeof(__BUFFER__) / sizeof(*(__BUFFER__)))void My_Send(UART_HandleTypeDef *huart, uint8_t *pData)
{uint16_t i;for(i=0;i<(COUNTOF(aTxBuffer) - 1);i++){huart->Instance->TDR = (uint8_t)(*(pData++)& 0xFFU);while (!(huart->Instance->ISR & UART_FLAG_TC)){};}
}//接收中断
//void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)函数不使用
//直接使用void USART2_IRQHandler(void)进入中断
void USART2_IRQHandler(void)
{//接收中断,接收数据if(USART2->ISR&(1<<5)) { RXBuff[RXCnt++]=USART2->RDR; }//溢出错误时(接收下一次数据前未读取数据),清除标志位if(USART2->ISR&(1<<4)) { USART2->ICR&=0x08;}
}