CH32V307尝试1--串口IDLE中断调试
在CH32V307的官方例程中,给出了printf函数,默认使用串口1 进行打印,但官方未给出串口接收函数。按照以前编程习惯,串口需能接收任意长度的数据,且不能规定传输数据中必须有结束字符。因此考虑使用IDLE中断接收。编写时参考了以下博客:https://blog.csdn.net/weixin_43150094/article/details/113823073。此博客内容为STM32的串口中断编写,对于实际代码徐做少量改动。
修改详情:1、定义修改:在debug.c中添加以下定义:
uint8_t U1_RxBuffer[64]={0};//接收缓存
uint8_t U1_RxCounter=0;//
void USART1_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast")));//定义中断,CH32V307不像stm32,直接使用即可,在CH32V307中需自己定义。
2、修改初始化函数:
void USART_Printf_Init(uint32_t baudrate)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure = {0};
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 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_Tx|USART_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
//---------------------------------------------------------------------------------------------------------------------------------//自己添加部分
USART_ITConfig(USART1,USART_IT_IDLE, ENABLE);
USART_ITConfig(USART1,USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//--------------------------------------------------------------------------------------------------------------------------------- USART_Cmd(USART1, ENABLE);
}
3、编写中断服务函数
void USART1_IRQHandler(void)
{
uint8_t clear=clear;
if(USART_GetITStatus(USART1,USART_IT_RXNE)!=RESET)
{
U1_RxBuffer[U1_RxCounter++]=USART_ReceiveData(USART1);
}else if(USART_GetITStatus(USART1,USART_IT_IDLE)!=RESET)
{
clear=USART_ReceiveData(USART1);
//---------------------------------------------------------------------------------------------------------------------------------
//用户处理
printf("get data=%d:%s\r\n",U1_RxCounter,U1_RxBuffer);
//---------------------------------------------------------------------------------------------------------------------------------
U1_RxCounter=0;
}
}
补充说明:
1、在中断服务函数中没有对中断标志进行清除,由系统自动清除,
原因如下:

2、注意读取中断标志的顺序
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律