前言:
最近在调试STM32L152芯片的USART配置程序,实现STM32串口打印功能,本文总结下STM32L152芯片USART的使用方法。
硬件平台:STM32L152
软件平台:keil v5+cubeMX
函数库:HAL库
1:usart初始化
UART_HandleTypeDef huart3;
uint8_t rxbuf;
void MX_USART3_UART_Init(void)
{
huart3.Instance = USART3;
huart3.Init.BaudRate = 115200;
huart3.Init.WordLength = UART_WORDLENGTH_8B;
huart3.Init.StopBits = UART_STOPBITS_1;
huart3.Init.Parity = UART_PARITY_NONE;
huart3.Init.Mode = UART_MODE_TX_RX;
huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart3.Init.OverSampling = UART_OVERSAMPLING_16;
HAL_UART_Init(&huart3);
}
//串口gpio初始化
void HAL_UART_MspInit(UART_HandleTypeDef* huart)
{
GPIO_InitTypeDef GPIO_InitStruct;
if(huart->Instance==USART3)
{
/* Peripheral clock enable */
__HAL_RCC_USART3_CLK_ENABLE();
/**USART3 GPIO Configuration
PB10 ------> USART3_TX
PB11 ------> USART3_RX
*/
GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART3;;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* Peripheral interrupt init */
HAL_NVIC_SetPriority(USART3_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(USART3_IRQn);
}
}
//串口反初始化
void HAL_UART_MspDeInit(UART_HandleTypeDef* huart)
{
if(huart->Instance==USART3)
{
/* Peripheral clock disable */
__HAL_RCC_USART3_CLK_DISABLE();
HAL_GPIO_DeInit(GPIOB, GPIO_PIN_10|GPIO_PIN_11);
/* Peripheral interrupt DeInit*/
HAL_NVIC_DisableIRQ(USART3_IRQn);
}
}
//串口中断回调函数(响应事件)
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance==USART3)
{
//加入处理事件
//如:printf("\GET data!\n");
HAL_UART_Receive_IT(&huart3,&rxbuf,1);//重新使能串口中断
}
}
在STM32L1XX_it.c中加入中断函数
void USART3_IRQHandler(void)
{
HAL_UART_IRQHandler(&huart3);
}
主函数示例代码:
int main(void)
{
HAL_Init( );
SystemClock_Config( );
MX_GPIO_Init( );
MX_USART3_UART_Init();
HAL_UART_Receive_IT(&huart3,&rxbuf,1);//使能串口中断,有串口中断便进入中断回调函数
while(1)
{
}
}