stm32串口usart的使用
扫描二维码
随时随地手机看文章
一、串口的定义
用来与外界交互数据。
二、usart的配置:
1、开启时钟。
stm32的usart1挂载在apb2上,USART2、usart3挂载在apb1上。
2、串口的基本配置。
void USART1_Configuration(void)
{
USART_InitTypeDef USART_InitStructure;
USART_DeInit (USART1 );
USART_InitStructure .USART_BaudRate =9600;
USART_InitStructure .USART_WordLength =USART_WordLength_8b ;
USART_InitStructure .USART_StopBits =USART_StopBits_1 ;
USART_InitStructure .USART_Parity =USART_Parity_No ;
USART_InitStructure .USART_HardwareFlowControl =USART_HardwareFlowControl_None ;
USART_InitStructure .USART_Mode =USART_Mode_Rx |USART_Mode_Tx ;
USART_Init (USART1 ,&USART_InitStructure );
USART_ClearFlag (USART1 ,USART_FLAG_TC );
USART_ITConfig (USART1 ,USART_IT_RXNE ,ENABLE );
USART_Cmd (USART1 ,ENABLE );
}
3、中断向量表的配置。
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig (NVIC_PriorityGroup_1);
NVIC_InitStructure .NVIC_IRQChannel =USART1_IRQn ;
NVIC_InitStructure .NVIC_IRQChannelPreemptionPriority =0;
NVIC_InitStructure .NVIC_IRQChannelSubPriority =1;
NVIC_InitStructure .NVIC_IRQChannelCmd =ENABLE ;
NVIC_Init(&NVIC_InitStructure );
}
4、串口中断函数的书写。
void USART1_IRQHandler(void )
{
if(USART_GetFlagStatus (USART1 ,USART_IT_RXNE) !=RESET )
{
USART_ClearITPendingBit (USART1 ,USART_IT_RXNE );
USART1_RX_Buffer=USART_ReceiveData (USART1 );
GPIO_SetBits (GPIOC ,GPIO_Pin_12 );
}
}