STM32重定向printf

本人最近项目代码移植时候,需要将printf定向到串口调试使用。用的是Keil+stm32f103 过程如下:

第一步,把相关代码移植过来。用的是串口1,PA9和PA10作为TX和RX。

//uart1.c文件

#include "uart1.h"
#include <stdarg.h>

void USART1_Config(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;

	/* 使能 USART1 时钟*/
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE); 

	/* USART1 使用IO端口配置 */    
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStructure);    
  
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;	//浮空输入
  GPIO_Init(GPIOA, &GPIO_InitStructure);   //初始化GPIOA
	  
	/* USART1 工作模式配置 */
	USART_InitStructure.USART_BaudRate = 115200;	//波特率设置:115200
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;	//数据位数设置:8位
	USART_InitStructure.USART_StopBits = USART_StopBits_1; 	//停止位设置: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(USART1, &USART_InitStructure);  //初始化USART1
	USART_Cmd(USART1, ENABLE);// USART1使能
}


 /* 描述  :重定向c库函数printf到USART1*/ 
int fputc(int ch, FILE *f)
{
/* 将Printf内容发往串口 */
  USART_SendData(USART1, (unsigned char) ch);
  while (!(USART1->SR & USART_FLAG_TXE));
 
  return (ch);
}

当然,头文件和声明必不可少。

//uart1.h 文件

#include "stm32f10x.h"
#include <stdio.h>

void USART1_Config(void);
int fputc(int ch, FILE *f);	

第二步,在main函数中测试

//main.c 文件

#include "uart1.h"

int main(void)
{

  SystemInit();

  USART1_Config();
  
  while(1)
  {
	printf("\r\n芯片初始化完成 \r\n"); 	
  }

}

第三步,需要在工程的配置

该步骤是必须的。如果没有的话,程序不会正常打印。我就是缺少此步骤,一直没有输出,找了很久才找到原因,之前以为重定向没什么。

最后,编译完烧录到板子里,就可以看到输出了。

发布了12 篇原创文章 · 获赞 4 · 访问量 6383

猜你喜欢

转载自blog.csdn.net/yilizhihu/article/details/104610848