[产品应用] 在CW32F030C8T6中处理UART错误中断完整示例代码

[复制链接]
17|0
茉璃夏 发表于 2025-10-24 13:43 | 显示全部楼层 |阅读模式
c
#include "cw32f030.h"
#include <string.h>

volatile uint8_t rxBuffer[256];
volatile uint16_t rxIndex = 0;

void UART_Configuration(void) {
    USART_InitTypeDef USART_InitStruct;
   
    USART_InitStruct.BaudRate = 115200;
    USART_InitStruct.WordLength = USART_WL_8BIT;
    USART_InitStruct.StopBits = USART_STPBITS_1;
    USART_InitStruct.Parity = USART_PRARITY_EVEN; // 启用奇偶校验
    USART_InitStruct.HardwareFlowControl = USART_HWCONTROL_NONE;
    USART_InitStruct.Mode = USART_MODE_RX | USART_MODE_TX;
    USART_Init(USART1, &USART_InitStruct);
    USART_Cmd(USART1, ENABLE);
}

void NVIC_Configuration(void) {
    NVIC_InitTypeDef NVIC_InitStruct;
    NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2);
    NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
}

void UART_Error_Interrupt_Enable(void) {
    USART_ITConfig(USART1, USART_IT_PE, ENABLE);
    USART_ITConfig(USART1, USART_IT_FE, ENABLE);
    USART_ITConfig(USART1, USART_IT_NE, ENABLE);
    USART_ITConfig(USART1, USART_IT_ORE, ENABLE);
}

void USART1_IRQHandler(void) {
    if (USART_GetITStatus(USART1, USART_IT_PE) != RESET) {
        uint8_t data = USART_ReceiveData(USART1);
        printf("PE Error: 0x%02X\n", data);
    }
   
    if (USART_GetITStatus(USART1, USART_IT_FE) != RESET) {
        uint8_t data = USART_ReceiveData(USART1);
        printf("FE Error!\n");
    }
   
    if (USART_GetITStatus(USART1, USART_IT_ORE) != RESET) {
        volatile uint16_t temp = USART1->SR;
        temp = USART1->DR;
        printf("ORE Error!\n");
        memset(rxBuffer, 0, sizeof(rxBuffer));
        rxIndex = 0;
    }
}

int main(void) {
    SystemInit();
    UART_Clock_Enable();
    GPIO_Configuration();
    UART_Configuration();
    NVIC_Configuration();
    UART_Error_Interrupt_Enable();
   
    while (1) {
        // 主循环逻辑
    }
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则

4

主题

13

帖子

0

粉丝
快速回复 在线客服 返回列表 返回顶部