打印
[应用相关]

STM32中映射 C库函数printf

[复制链接]
546|4
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
一、MDK设置
在工程的 Target中MicroLib


二、main函数之前添加如下编译代码:
#define COM USART1  //串口选择初始化,USART1为串口1,USART2为串口2
#ifdef __GNUC__

  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
PUTCHAR_PROTOTYPE
{
  USART_SendData(COM, (uint8_t) ch); //此处用到了 COM宏定义为了 USART1
//注意:这里可以定义printf()使用板载的任意USART(COM1或者COM2均可)

  while (USART_GetFlagStatus(COM, USART_FLAG_TC) == RESET)
  {}
  return ch;
}

沙发
huangcunxiake|  楼主 | 2016-8-27 12:06 | 只看该作者
三、程序配置
时钟使能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB,ENABLE);
   
   RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);   //串口2时钟初始化
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);   //串口1时钟初始化
IO脚配置
void GPIO_Configuration(void)
{
   GPIO_InitTypeDef GPIO_InitStructure;
   //USART1管脚初始化
  //USART1发送TX=PA9管脚初始化
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);
   //USART1接收RX=PA10管脚初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
   GPIO_Init(GPIOA, &GPIO_InitStructure);
//USART2管脚初始化
//USART2发送TX=PA2管脚初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
   GPIO_Init(GPIOA, &GPIO_InitStructure);
  //USART2接收RX=PA3管脚初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
   GPIO_Init(GPIOA, &GPIO_InitStructure);
}
串口参数设置
void USART_Configuration(void)
{
    USART_InitTypeDef USART_InitStructure;
  
   USART_InitStructure.USART_BaudRate = 115200; // 设置了USART传输的波特率 ;
   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;// RTS和CTS失能 ;
   USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; // 接收发送使能 ;
USART_Init(COM, &USART_InitStructure); // 根据USART_InitStruct中指定的参数初始化外设USART寄存器 ;
  
USART_Cmd(COM, ENABLE); // 使能USART外设,此处COM为USART1,在宏定义中,可以设置
   while(NbrOfDataToTransfer--) //测试用,初始化发送数据,NbrOfDataToTransfer为输出字符串的长度
   {
     USART_SendData(USART2, TxBuffer[TxCounter++]); // 通过外设USART发送单个数据 ;
     while(USART_GetFlagStatus(COM, USART_FLAG_TXE) == RESET); // 检查发送数据寄存器空标志位;        
   }

}

使用特权

评论回复
板凳
huangcunxiake|  楼主 | 2016-8-27 12:08 | 只看该作者
3、在main中添加
printf("\n\rSTM32 USART2:%d \n",10);
即可实现C库printf函数的正常使用

使用特权

评论回复
地板
天灵灵地灵灵| | 2016-8-27 15:02 | 只看该作者
没想到串口是这么使用的,而且GUN的和那个其他的不同。

使用特权

评论回复
5
hello_galaxy| | 2016-8-27 19:37 | 只看该作者
直接使用串口打印函数就好,自己写一个就OK。或者可以用半主机调试输出信息

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

194

主题

3453

帖子

10

粉丝