STM32F103串口配置,并且使用printf进行打印
首先要配置串口时钟:
- // USART1 clock enable
- RCC_APB2PeriphClockCmd(
- RCC_APB2Periph_USART1 |
- RCC_APB2Periph_GPIOA |
- RCC_APB2Periph_AFIO, ENABLE);
然后再配置端口,在配置串口,再使能即可。
- void USART1_Init(void)
- {
- /////// config the gpio
- GPIO_InitTypeDef GPIO_InitStructure;
- /* PA9 USART1_Tx */
- 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);
- /* PA10 USART1_Rx */
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //配置接收端口
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//
- GPIO_Init(GPIOA, &GPIO_InitStructure);
- //////////////
- USART_InitTypeDef USART_InitStructure;//
- USART_InitStructure.USART_BaudRate = 115200;//配置波特率
- 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_Rx | USART_Mode_Tx;//
- //config clock
- USART_ClockInitTypeDef USART_ClockInitStructure;
- USART_ClockInitStructure.USART_Clock = USART_Clock_Disable;
- USART_ClockInitStructure.USART_CPOL = USART_CPOL_Low;
- USART_ClockInitStructure.USART_CPHA = USART_CPHA_2Edge;
- USART_ClockInitStructure.USART_LastBit = USART_LastBit_Disable;
- USART_ClockInit(USART1, &USART_ClockInitStructure);
- /* Configure USART1 */
- USART_Init(USART1, &USART_InitStructure);//
- /* Enable the USART1 */
- USART_Cmd(USART1, ENABLE);//??1?
- }
串口配置完毕,为了使得能够使用 printf 进行打印,需要进行重定向:
在 stm32f10x_usart.c 中添加如下代码:
- int fputc(int ch, FILE *f)
- {
- /* 给USART写一个字符 */
- USART_SendData(USART1, (uint8_t) ch);
- /* 循环直到发送完成 */
- while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
- return ch;
- }
在 stm32f10x_usart.h 中添加stdio.h头文件,然后,添加声明 int fputc(int ch, FILE *f);
最后,在设置里面 Target 下面 勾选“Use MicroLIB” 就可以了。