1.USART的参数初始化(见查询方式)
2.开启串口接收中断
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
3.配置NVIC中的USART的等级
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_x); //嵌套优先级分组为
NVIC_InitStructure.NVIC_IRQChannel = USARTx_IRQn; //嵌套通道为USART1_IRQn
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = x; //抢占优先级为
NVIC_InitStructure.NVIC_IRQChannelSubPriority = x; //响应优先级为
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //通道中断使能
NVIC_Init(&NVIC_InitStructure);
4.定义一个串口中断发送指针
如char *USART_Send_Buf;
5.把要发的字符串的指针赋给串口中断发送指针,开启串口发送中断(可以打包成一个函数)(只是个演示,逻辑有问题,有bug,如果一个字符串还没发送完成,再给发送指针赋值,会把前面的挤掉)
如
void USART1_Puts(char * str)
{
USART_Send_Buf = str;
USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
}
6.编写中断服务程序
如
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_TXE) == SET)
{
USART_SendData(USART1, *USART_Send_Buf);
USART_Send_Buf++;
if(*USART_Send_Buf=='\0')
USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
}
if (USART_GetITStatus(USART1, USART_IT_RXNE) == SET)
{
USART_SendData(USART1, USART_ReceiveData(USART1));
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
}
}
|