STM32F103串口配置,并且使用printf进行打印


 

 首先要配置串口时钟:
  1.       // USART1 clock enable 
  2.       RCC_APB2PeriphClockCmd(
  3.       RCC_APB2Periph_USART1 |
  4.       RCC_APB2Periph_GPIOA |
  5.       RCC_APB2Periph_AFIO, ENABLE);

然后再配置端口,在配置串口,再使能即可。

  1.   void USART1_Init(void)
  2.   {
  3.   /////// config the gpio
  4.   GPIO_InitTypeDef GPIO_InitStructure;
  5.    
  6.   /* PA9 USART1_Tx */
  7.   GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //配置发送端口
  8.   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  9.   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //
  10.   GPIO_Init(GPIOA, &GPIO_InitStructure);
  11.   /* PA10 USART1_Rx */
  12.   GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //配置接收端口
  13.   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//
  14.   GPIO_Init(GPIOA, &GPIO_InitStructure);
  15.    
  16.   //////////////
  17.    
  18.   USART_InitTypeDef USART_InitStructure;//
  19.    
  20.   USART_InitStructure.USART_BaudRate = 115200;//配置波特率
  21.   USART_InitStructure.USART_WordLength = USART_WordLength_8b;//
  22.   USART_InitStructure.USART_StopBits = USART_StopBits_1;//
  23.   USART_InitStructure.USART_Parity = USART_Parity_No;//
  24.   USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  25.   USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//
  26.    
  27.   //config clock
  28.   USART_ClockInitTypeDef USART_ClockInitStructure;
  29.    
  30.   USART_ClockInitStructure.USART_Clock = USART_Clock_Disable;
  31.   USART_ClockInitStructure.USART_CPOL = USART_CPOL_Low;
  32.    
  33.   USART_ClockInitStructure.USART_CPHA = USART_CPHA_2Edge;
  34.   USART_ClockInitStructure.USART_LastBit = USART_LastBit_Disable;
  35.    
  36.   USART_ClockInit(USART1, &USART_ClockInitStructure);
  37.    
  38.   /* Configure USART1 */
  39.   USART_Init(USART1, &USART_InitStructure);//
  40.    
  41.   /* Enable the USART1 */
  42.   USART_Cmd(USART1, ENABLE);//??1?
  43.    
  44.   }

串口配置完毕,为了使得能够使用 printf 进行打印,需要进行重定向:

在 stm32f10x_usart.c 中添加如下代码:

  1.   int fputc(int ch, FILE *f)
  2.   {
  3.   /* 给USART写一个字符 */
  4.   USART_SendData(USART1, (uint8_t) ch);
  5.    
  6.   /* 循环直到发送完成 */
  7.   while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
  8.    
  9.   return ch;
  10.   }

在 stm32f10x_usart.h 中添加stdio.h头文件,然后,添加声明 int fputc(int ch, FILE *f);

最后,在设置里面 Target 下面 勾选“Use MicroLIB” 就可以了。

相关