【N32L43x评测】3、利用串口接收中断和空闲中断,实现不定长数据接收
[复制链接]
1、实现思路
本文利用串口接收中断和空闲中断,实现串口不定长数据接收
接收中断:实现数据的接收;
空闲中断:判断一帧数据完成。
2、硬件
本文使用串口1,引脚为PA9和PA10,同时,PA9和PA10直接连接到了NS-LINK的usb转串口上,因此可以直接在电脑上查看。
3、代码实现
(1)串口初始化
void SerialInit(void)
{
/* Enable GPIO clock */
RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOA , ENABLE);
/* Enable USARTy and USARTz Clock */
RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_USART1, ENABLE);
NVIC_InitType NVIC_InitStructure;
/* Enable the USART Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
GPIO_InitType GPIO_InitStructure;
/* Initialize GPIO_InitStructure */
GPIO_InitStruct(&GPIO_InitStructure);
/* Configure USARTx Tx as alternate function push-pull */
GPIO_InitStructure.Pin = GPIO_PIN_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Alternate = GPIO_AF4_USART1; //GPIO_Mode_AF_PP
GPIO_InitPeripheral(GPIOA, &GPIO_InitStructure);
/* Configure USARTx Rx as alternate function push-pull and pull-up */
GPIO_InitStructure.Pin = GPIO_PIN_10;
GPIO_InitStructure.GPIO_Pull = GPIO_Pull_Up;
GPIO_InitStructure.GPIO_Alternate = GPIO_AF4_USART1;
GPIO_InitPeripheral(GPIOA, &GPIO_InitStructure);
USART_InitType USART_InitStructure;
USART_StructInit(&USART_InitStructure);
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 USART*/
USART_Init(USART1, &USART_InitStructure);
/* Enable USARTy Receive and Transmit interrupts */
USART_ConfigInt(USART1, USART_INT_RXDNE, ENABLE);
USART_ConfigInt(USART1, USART_INT_IDLEF, ENABLE);
USART_Enable(USART1, ENABLE);
}
(2)串口中断
void USART1_IRQHandler(void)
{
if(RESET != USART_GetIntStatus(USART1, USART_INT_RXDNE))
{
SerialRecv(USART_ReceiveData(USART1));
}
if(RESET !=USART_GetIntStatus(USART1, USART_INT_IDLEF))
{
USART_ReceiveData(USART1);
SerialStr.Idle=1;
}
}
(3)接收应用代码
void SerialRecv(uint8_t data)
{
if(SerialStr.RecvLen<UART_MAX_LEN)
{
SerialStr.RecvBuff[SerialStr.RecvLen++]=data;
}
}
void SerialSend(uint8_t *data,uint8_t len)
{
for(uint8_t i=0; i<len;i++)
{
while (RESET == USART_GetFlagStatus(USART1, USART_FLAG_TXDE ));
USART_SendData(USART1, data[i]);
}
}
void SerialPro(void)
{
if(SerialStr.Idle&&SerialStr.RecvLen)
{
printf("Recv:%d,[",SerialStr.RecvLen);
SerialSend(SerialStr.RecvBuff,SerialStr.RecvLen);
printf("]\r\n");
SerialStr.RecvLen=0;
SerialStr.Idle=0;
}
}
int fputc(int ch, FILE *f)
{
while (RESET == USART_GetFlagStatus(USART1, USART_FLAG_TXDE )) {};
USART_SendData(USART1, (uint8_t) ch);
return ch;
}
4、测试
|