STM32
直播中

刘刚

8年用户 1117经验值
私信 关注
[问答]

C库中的printf函数要怎样才能正常使用呢

C库中的printf函数要怎样才能正常使用呢?有哪些操作步骤?

回帖(1)

郭静

2021-11-30 10:29:32
一、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;
}
   三、程序配置
   时钟使能
    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); // 检查发送数据寄存器空标志位;        
   }
   
}
   3、在main中添加
    printf("nrSTM32 USART2:%d n",10);
   即可实现C库printf函数的正常使用
  
                    
举报

更多回帖

发帖
×
20
完善资料,
赚取积分