二、实例演示 本实例采用CW32L083V8T6的StartKit单板,MCU的串口引脚(PA08/ PA09)和CH340对接,CH340通过USB接口和PC机对接,实现PC机软件和MCU通过UART双向通信功能。 单板启动后,处于等待数据接收状态,当有数据接收到后,产生UART接收中断,在中断中读取接收到的数据,然后将数据通过UART再发送回来,并清除中断标志位,然后等待接收下一个数据。 1.配置RCC系统时钟 void RCC_Configuration(void) { //SYSCLK = HSI = 8MHz = HCLK = PCLKRCC_HSI_Enable(RCC_HSIOSC_DIV6);//外设时钟使能RCC_AHBPeriphClk_Enable(DEBUG_UART_GPIO_CLK, ENABLE);DEBUG_UART_APBClkENx(DEBUG_UART_CLK, ENABLE);} 2.GPIO配置 void GPIO_Configuration(void) { GPIO_InitTypeDef GPIO_InitStructure = {0};//UART TX RX 复用DEBUG_UART_AFTX;DEBUG_UART_AFRX;GPIO_InitStructure.Pins = DEBUG_UART_TX_GPIO_PIN;GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;GPIO_Init(DEBUG_UART_TX_GPIO_PORT, &GPIO_InitStructure);GPIO_InitStructure.Pins = DEBUG_UART_RX_GPIO_PIN;GPIO_InitStructure.Mode = GPIO_MODE_INPUT_PULLUP;GPIO_Init(DEBUG_UART_RX_GPIO_PORT, &GPIO_InitStructure);} 3.UART配置 void UART_Configuration(void) { UART_InitTypeDef UART_InitStructure = {0};UART_InitStructure.UART_BaudRate = DEBUG_UART_BaudRate;UART_InitStructure.UART_Over = UART_Over_16;UART_InitStructure.UART_Source = UART_Source_PCLK;UART_InitStructure.UART_UclkFreq = DEBUG_UART_UclkFreq;UART_InitStructure.UART_StartBit = UART_StartBit_FE;UART_InitStructure.UART_StopBits = UART_StopBits_1;UART_InitStructure.UART_Parity = UART_Parity_No ;UART_InitStructure.UART_HardwareFlowControl = UART_HardwareFlowControl_None;UART_InitStructure.UART_Mode = UART_Mode_Rx | UART_Mode_Tx;UART_Init(DEBUG_UARTx, &UART_InitStructure);} 4.配置NVIC void NVIC_Configuration(void) { //优先级,无优先级分组NVIC_SetPriority(DEBUG_UART_IRQ, 0);//UARTx中断使能NVIC_EnableIRQ(DEBUG_UART_IRQ);} 5.中断函数处理UART2/UART5 void UART2_UART5_IRQHandler(void) { /* USER CODE BEGIN */uint8_t TxRxBuffer;if(UART_GetITStatus(CW_UART5 UART_IT_RC) != RESET)// 获取UARTx中断标志位{ TxRxBuffer = UART_ReceiveData_8bit(CW_UART5;// 通过UARTx接收一个数据(8bit) UART_SendData_8bit(CW_UART5 TxRxBuffer);// 通过UARTx发送一个数据(8bit) UART_ClearITPendingBit(CW_UART5 UART_IT_RC);// 清除UARTx中断标志位}/* USER CODE END */} 6.定义常量define //UARTx #define DEBUG_UARTx CW_UART5 #define DEBUG_UART_CLK RCC_APB1_PERIPH_UART5 #define DEBUG_UART_APBClkENx RCC_APBPeriphClk_Enable1 #define DEBUG_UART_BaudRate 9600 #define DEBUG_UART_UclkFreq 8000000 //UARTx GPIO #define DEBUG_UART_GPIO_CLK RCC_AHB_PERIPH_GPIOB #define DEBUG_UART_TX_GPIO_PORT CW_GPIOB #define DEBUG_UART_TX_GPIO_PIN GPIO_PIN_8 #define DEBUG_UART_RX_GPIO_PORT CW_GPIOB #define DEBUG_UART_RX_GPIO_PIN GPIO_PIN_9 //GPIO AF #define DEBUG_UART_AFTX PB08_AFx_UART5TXD() #define DEBUG_UART_AFRX PB09_AFx_UART5RXD() //中断 #define DEBUG_UART_IRQ UART2_UART5_IRQn 7.UART中断方式接收数据 int32_t main(void) { //配置RCCRCC_Configuration();//配置GPIOGPIO_Configuration();//配置UARTUART_Configuration();//配置NVICNVIC_Configuration();//使能UARTx RC中断UART_ITConfig(DEBUG_UARTx, UART_IT_RC, ENABLE);UART_SendString(DEBUG_UARTx, "\r\nCW32L083 UART Interrupt\r\n");while(1){ //中断收发}} 8、测试结果如下:当MCU收到上位机发送的数据后,再回传到上位机,UART功能正常。
|