沁恒 RISC-V 32 位单片机串口中断实验。
实验目的:串口收到数据时可以触发中断。
代码如下:
// 加作者微信:jiyuyun18,交流电子技术
#include "ch32v20x.h" // 导入 RCC_APB1Periph_USART2 定义
// 不加这句,中断只会触发一次
void USART2_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
/*********************************************************************
* @fn USART2_Init
*
* @brief Initializes the USART2 peripheral.
*
* @param baudrate - USART communication baud rate.
*
* @return None
* -------------------------
* USART2_TX | PA2
* -------------------------
* USART2_RX | PA3
* -------------------------
*/
void USART2_Init(uint32_t baudrate)
{
GPIO_InitTypeDef GPIO_InitStructure = {0};
USART_InitTypeDef USART_InitStructure = {0};
//NVIC_Init 函数调用时需定义一个 NVIC_InitTypeDef 结构体类型变量
NVIC_InitTypeDef NVIC_InitStrue = {0};
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; // TX
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; // RX
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
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;
NVIC_InitStrue.NVIC_IRQChannel=USART2_IRQn; //串口2对应的中断名称
NVIC_InitStrue.NVIC_IRQChannelCmd=ENABLE; //使能该中断通道
NVIC_InitStrue.NVIC_IRQChannelPreemptionPriority=1;//抢占优先级为1, 数值越小优先级越高
NVIC_InitStrue.NVIC_IRQChannelSubPriority=1;//响应优先级为1
NVIC_Init(&NVIC_InitStrue); //中断初始化
USART_Init(USART2, &USART_InitStructure);
// 使能串口中断,也叫开启串口中断,第二个参数是设置具体开启哪种中断,具体为寄存器SR
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
USART_Cmd(USART2, ENABLE);
}
/*********************************************************************
* @fn USART2_IRQHandler
*
* @brief This function handles USART2 global interrupt request.
*
* @return none
*/
void USART2_IRQHandler()
{
unsigned char data;
//判断如果收到了数据,收到数据CR1中RXNE位为1,该函数的返回值为1,则执行if包含的语句
if(USART_GetITStatus(USART2,USART_IT_RXNE) != RESET)
{
data = USART_ReceiveData(USART2);//读取数据
//USART_SendData(USART1,data); //发送读到的数据到调试串口
pt_analyze_data(data);
}
}