//中断函数程序
uint8_t USART2_RX_BUF[10]={0x00}; // 缓存最大10个字节,第1个字节为接收帧字节数量
void USART2_IRQHandler(void)
{
uint8_t res;
uint8_t clear = 0; // 清除空闲中断标志位标志
static uint8_t Rx_Sta = 1; // 计数器
if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) // 接收到字节
{
res = USART2->DR; // 读取接收到的字节,清除接收中断标志位
USART2_RX_BUF[Rx_Sta++] = res; // 缓存接收到的字节
}
else if(USART_GetITStatus(USART2, USART_IT_IDLE) != RESET) // 检测到空闲
{
clear = USART2->SR;
clear = USART2->DR; // 清除空闲中断标志位(请参照芯片参考手册)
USART2_RX_BUF[0] = Rx_Sta - 1; // 一帧字节数计算
Rx_Sta = 1;
}
}
//引脚配置
// USART2 通信模式 RX->PA3 TX->PA2
void USART2_NVIC_Configuration ( void )
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig ( NVIC_PriorityGroup_2 );
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void USART2_Config ( void )
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
/* config USART clock */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA| RCC_APB2Periph_AFIO, ENABLE);
/* USART GPIO config */
/* Configure USART Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Pin = USART2_TX ;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(USART_GPIO_PORT, &GPIO_InitStructure);
/* Configure USART Rx as input floating */
GPIO_InitStructure.GPIO_Pin =USART2_RX;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init( USART_GPIO_PORT, &GPIO_InitStructure);
/* USART2 mode config */
USART_InitStructure.USART_BaudRate = USART2_BaudRate;
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( USART2, &USART_InitStructure);
USART2_NVIC_Configuration( );
/* 中断配置 */
USART_ITConfig ( USART2, USART_IT_RXNE, ENABLE ); //使能串口接收中断
USART_ITConfig ( USART2, USART_IT_IDLE, ENABLE ); //使能串口总线空闲中断
// USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
USART_Cmd(USART2, ENABLE);
}
void USART2_Init ( void )
{
USART2_Config();
USART2_NVIC_Configuration();
}