STM32在IAR中调用之printf函数的一个方法

来源:互联网 发布:php淘宝互刷平台源码 编辑:程序博客网 时间:2024/06/06 03:14

原文地址:http://blog.sina.com.cn/s/blog_668bcb8f01018ect.html 
在串口都配置好的情况下,在main.c文件中加入

#include <stdio.h>#ifdef __GNUC__  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)#else  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)#endifPUTCHAR_PROTOTYPE{  USART_SendData(USART1, (u16) ch);  while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)  {}  return ch;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

之后如若编译出现identifier “FILE” is undefined,即将Options->GeneralOptions->Library Configuation中的Library选为full即可。

参考:http://blog.csdn.net/qcopter/article/details/51304361

搜索互联网上,关于此类问题的解决文章资料也比较丰富,不过按照其思路还是遇到了不少问题。

  首先,贴代码,大部分代码都是类似的方案,重写putchar或者fputc函数。

[plain] view plain copy
  1. #ifdef  USE_IAR  
  2. #define PUTCHAR_PROTOTYPE int putchar(int ch)  
  3. #else  
  4. #define PUTCHAR_PROTOTYPE int fputc(int ch,FILE *f)     
  5. #endif  
  6.   
  7. PUTCHAR_PROTOTYPE{  
  8.   HAL_UART_Transmit(&huart1, (char *)(&(ch)), 1, 10);  
  9.   return ch;  
  10. }   

  实际程序我定义了宏 USE_IAR,也就是实现了putchar()函数,不过实际调试,printf()函数会依次调用putchar()及fputs(),所以实际中实现其中任一一个函数即可。也就是上述的代码,即使我不定义USE_IAR,仍然是可用的。
  需要注意的一点是重写的putchar()函数必须要返回ch变量,否则只会打印首个字符一次。
  使用STM32的串口发送是阻塞的,也就是发送完一个字符程序才会继续运行发送下一个字符。
  记得配置IAR的环境 Options->General Options->Library Configuation的Library为Full。

  加入printf()函数在未使用IAR的优化功能前提下,会增加8.5KBytes左右的readonly  code memory,30Bytes的readonly  data memory,及2.4KBytes左右的readwrite data memory。


原创粉丝点击