在上篇文章将内部时钟设置为48M后,下面学习下串口1的输出。
一、串口硬件电路
1.1、串口端口
电路图有关串口1的部分,使用的PA8和PA9管脚。
1.2、USB转串口部分
开发板上自带了一个USB转串口模块,在使用的时候需要将VDDU连接到单片机的电源上,否则PC找不到USB,同时将TX和RX连接到相应的PA9和PA8引脚。
二、程序部分
2.1、usart.c
这里将串口1的时钟源改成48M。
- #include "cw32f030.h"
- #include "cw32f030_uart.h"
- #include "cw32f030_rcc.h"
- #include "cw32f030_gpio.h"
- #include "usart.h"
- int fputc(int ch, FILE *f)
- {
- USART_SendData_8bit(CW_UART1, (uint8_t)ch);
- while (USART_GetFlagStatus(CW_UART1, USART_FLAG_TXE) == RESET);
- return ch;
- }
-
- void uart_init(uint32_t bound)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
- USART_InitTypeDef USART_InitStructure;
-
- RCC_AHBPeriphClk_Enable(RCC_AHB_PERIPH_GPIOA, ENABLE);
- RCC_APBPeriphClk_Enable2(RCC_APB2_PERIPH_UART1, ENABLE);
-
- PA08_AFx_UART1TXD();
- PA09_AFx_UART1RXD();
- GPIO_InitStructure.Pins = GPIO_PIN_8;
- GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
- GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
- GPIO_Init(CW_GPIOA, &GPIO_InitStructure);
-
- GPIO_InitStructure.Pins = GPIO_PIN_9;
- GPIO_InitStructure.Mode = GPIO_MODE_INPUT_PULLUP;
- GPIO_Init(CW_GPIOA, &GPIO_InitStructure);
-
- USART_InitStructure.USART_BaudRate = bound;
- USART_InitStructure.USART_Over = USART_Over_16;
- USART_InitStructure.USART_Source = USART_Source_PCLK;
- USART_InitStructure.USART_UclkFreq = 48000000;
- USART_InitStructure.USART_StartBit = USART_StartBit_FE;
- 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_Rx | USART_Mode_Tx;
- USART_Init(CW_UART1, &USART_InitStructure);
- }
2.2、usart.h
- #ifndef __USART_H
- #define __USART_H
- #include "stdio.h"
- void uart_init(uint32_t bound);
- #endif
2.3、main.c
- #include "main.h"
- #include "cw32f030_flash.h"
- #include "led.h"
- #include "delay.h"
- #include "usart.h"
- void rcc_config(void)
- {
- uint8_t res = 0U;
- RCC_AHBPeriphClk_Enable(RCC_AHB_PERIPH_FLASH, ENABLE); //打开FLASH时钟
- RCC_HCLK_OUT(); //通过PA04观察HCLK频率
- RCC_HSE_Enable( RCC_HSE_MODE_OSC, 16000000, RCC_HSE_DRIVER_NORMAL, RCC_HSE_FLT_CLOSE ); //开启外部高速时钟HSE,实际频率需要根据实际晶体频率进行填写
-
- RCC_PLL_Enable( RCC_PLLSOURCE_HSEOSC, 16000000, RCC_PLL_MUL_3 ); //开启PLL,PLL时钟来源为HSE
- FLASH_SetLatency(FLASH_Latency_2); //频率大于24M需要配置FlashWait=2
- res = RCC_SysClk_Switch( RCC_SYSCLKSRC_PLL ); //切换系统时钟到PLL
- if( res == 0x0U ) //切换系统时钟成功
- {
- RCC_HSI_Disable(); //切换时钟到PLL后关闭源时钟HSI
- }
- }
- int32_t main(void)
- {
- rcc_config();
- delay_init();
- uart_init(115200);
- init_led();
-
- while (1)
- {
- led1_tog();
- printf("\r\nCW32F030 UART Printf Example\r\n");
- delay_ms(100);
- }
- }
2.4、软件配置
需要在软件上选择下面选项
三、程序运行
串口输出打印信息。
|