一、printf()函数重定向
方法一:使用MicroLIB库
1. 勾选 Use MicroLIB
具体如下图所示:
2. 重定向 fputc 函数
具体代码如下:
- #include <stdio.h>//需要调用stdio.h文件
- /**********************printf重定向****************************/
- int fputc(int ch, FILE *f)
- {
- USART_SendData(USART1, ch); //发送数据
- while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);//等待发送完成
-
- return ch;
- }
复制代码
将此代码一般是添加在对应的串口通信文件中,我这里是添加在 Uart1.c 文件中。
方法二:不使用MicroLIB库
不用勾选 Use MicroLIB,直接在 Uart1.c 文件中添加以下代码:
- #include <stdio.h>//需要调用stdio.h文件
- /**********************printf重定向****************************/
- //取消ARM的半主机工作模式
- #pragma import(__use_no_semihosting)//标准库需要的支持函数
- struct __FILE
- {
- int handle;
- };
- FILE __stdout;
- void _sys_exit(int x) //定义_sys_exit()以避免使用半主机模式
- {
- x = x;
- }
- int fputc(int ch, FILE *f)
- {
- USART_SendData(USART1, ch); //发送数据
- while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);//等待发送完成
- return ch;
- }
复制代码
二、printf()输出数据
1. printf()函数详解
点击蓝色文字,可以跳转到printf()函数详解文章。
C语言:printf()—格式数据输出
2. printf()函数输出数据调试实验
我单片机中程序的功能是:每200ms发送一次 工欲善其事,必先利其器。
具体程序如下:
main.c
- #include "stm32f10x.h"
- #include <stdio.h>
- #include "delay.h"
- #include "Uart1.h"
- int main (void)
- {
- Uart1_init();//串口1初始化
-
- while(1)
- {
- printf("工欲善其事,必先利其器。");
- delay_ms(200); //延时200ms
- }
- }
复制代码
串口调试助手的现象如下:
————————————————
版权声明:根号五
|