串口2中断+IDLE接收不定长数据
1、根据手册可查PA6 PA7可复用usart2功能
2、复用功能配置如图
3、串口初始化代码:
#define USARTz USART2
#define USARTz_CLK RCC_APB1_PERIPH_USART2
#define USARTz_GPIO GPIOA
#define USARTz_GPIO_CLK RCC_AHB_PERIPH_GPIOA
#define USARTz_RxPin GPIO_PIN_7
#define USARTz_TxPin GPIO_PIN_6
#define USARTz_Rx_GPIO_AF GPIO_AF11_USART2
#define USARTz_Tx_GPIO_AF GPIO_AF11_USART2
#define USARTz_APBxClkCmd RCC_APB1_Peripheral_Clock_Enable
void usart_init(void)
{
GPIO_InitType GPIO_InitStructure;
USART_InitType USART_InitStructure;
NVIC_InitType NVIC_InitStructure;
RCC_AHB_Peripheral_Clock_Enable(RCC_AHB_PERIPH_GPIOA);
/* Enable USARTy and USARTz Clock */
RCC_APB1_Peripheral_Clock_Enable(RCC_APB1_PERIPH_USART2);
/* Enable the USARTy Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Initializes(&NVIC_InitStructure);
/* Initialize GPIO_InitStructure */
GPIO_Structure_Initialize(&GPIO_InitStructure);
/* Configure USARTz Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Mode = GPIO_MODE_AF_PP;
GPIO_InitStructure.Pin = USARTz_TxPin;
GPIO_InitStructure.GPIO_Alternate = USARTz_Tx_GPIO_AF;
GPIO_Peripheral_Initialize(USARTz_GPIO, &GPIO_InitStructure);
/* Configure USARTz Rx as alternate function push-pull */
GPIO_InitStructure.Pin = USARTz_RxPin;
GPIO_InitStructure.GPIO_Alternate = USARTz_Rx_GPIO_AF;
GPIO_Peripheral_Initialize(USARTz_GPIO, &GPIO_InitStructure);
/* USARTy and USARTz configuration ------------------------------------------------------*/
USART_InitStructure.BaudRate = 115200;
USART_InitStructure.WordLength = USART_WL_8B;
USART_InitStructure.StopBits = USART_STPB_1;
USART_InitStructure.Parity = USART_PE_NO;
USART_InitStructure.HardwareFlowControl = USART_HFCTRL_NONE;
USART_InitStructure.Mode = USART_MODE_RX | USART_MODE_TX;
/* Configure USARTy and USARTz */
USART_Initializes(USARTz, &USART_InitStructure);
/* Enable USARTz Receive and Transmit interrupts */
USART_Interrput_Enable(USARTz, USART_INT_RXDNE);
USART_Interrput_Enable(USARTz, USART_INT_IDLEF);
//USART_Interrput_Enable(USARTz, USART_INT_TXDE);
/* Enable the USARTy and USARTz */
USART_Enable(USARTz);
}
4、中断处理函数
我们将电脑端发送过来的数据 返还回电脑
/**
*\*\name USARTz_IRQHandler.
*\*\fun This function handles USARTz global interrupt request.
*\*\param none
*\*\return none
**/
static uint8_t RxBuffer1[128];//接收数据缓存区
static uint32_t RxCounter1 = 0;//接收数据长度
void USART2_IRQHandler(void)
{
if (USART_Interrupt_Status_Get(USART2, USART_INT_RXDNE) != RESET)
{
/* 读取数据并清除标志 */
RxBuffer1[RxCounter1++] = USART_Data_Receive(USART2);
}
else if (USART_Interrupt_Status_Get(USART2, USART_INT_IDLEF) != RESET)
{
/* 清除IDLE标志*/
USART_Interrupt_Status_Clear(USART2,USART_INT_IDLEF);
Usart_SendString((char *)RxBuffer1,RxCounter1);
RxCounter1 = 0;
}
}
5、main.cpp调用usart_init后,make烧录进板卡,电脑端串口助手发送数据现象如图: