STM32H7系列其二

本文介绍了如何在STM32单片机上重定向printf函数,以便通过串口输出数据。根据ARM Compiler6文档,通过自定义__FILE、fputc()和ferror(),可以实现printf家族函数的串口输出。文中以STM32为例,展示了重定向printf到串口3的具体步骤,并给出了测试程序及其成功输出的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

尘归尘、土归土,老夫有酒二两五

printf重定向介绍

在学C语言的时候,会经常用标准库<stdio.h>中printf(), scanf()这两个函数, 来实现数据的输入与输出. 格式化输入输出的功能还是挺强大的, 那已经有了现成的轮子, 就要寻思一下如何进一步在单片机上使用它.
下面是ARM Compiler6文档中对printf的介绍:

The printf family consists of _printf(), printf(), _fprintf(), fprintf(), vprintf(), and vfprintf().
All these functions use __FILE opaquely and depend only on the functions fputc() and ferror(). The functions _printf() and _fprintf() are identical to printf() and fprintf() except that they cannot format floating-point values.
The standard output functions of the form _printf(…) are equivalent to:
fprintf(& __stdout, …)where __stdout has type __FILE.

大致是说printf家族有这么些函数<_printf(), printf(), _fprintf(), fprintf(), vprintf(), and vfprintf()>, 这些函数都隐式的使用__FILE<文件流>, 并且只依靠fputc(), ferror()这两个函数.

If you define your own version of __FILE, your own fputc() and ferror() functions, and the __stdout object, you can use all of the printf() family, fwrite(), fputs(), puts() and the C++ object std::cout unchanged from the library.

重新定义__FILE, fputc(), ferror(), __stdout, 就可以使用printf()家族的各种函数了.

STM32中printf重定向

下面是官方给出的重映射模板:
<遇到不会的先看看文档往往能得到最直接的答案>

#include <stdio.h>
struct __FILE
{
   
   
  int handle;
  /* Whatever you require here. If the only file you are using is */
  /* standard output using printf() for debugging, no file handling */
  /* is required. */
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值