原理
C 语言中 printf 函数默认输出设备是显示器,如果要实现在串口或者 LCD 上显示,必须重定义标准库函数里调用的与输出设备相关的函数。
重定向:重写库函数,对原函数进行覆盖,编译时优先调用重定向的用户函数,在 KEIL 中使用 printf 一定要勾选“微库”选项。
在 STM32 程序开发中 printf 应用非常广,当我们需要查看某些变量数值或者其他信息等,都可以通过 printf 打印到串口调试助手上查看。
步骤
- 编写USART驱动程序(STM32F1系列通用)
- 将固件库文件stm32f10x_usart.c添加至工程
- 编写头文件:函数声明
- 编写驱动文件:
- 初始化函数:
- 使能端口时钟,串口时钟:RCC_APB2PeriphClockCmd
- 配置GPIO口Tx、Rx引脚:GPIO_InitTypeDef
- 配置串口:波特率、字长、停止位、校验位
- 使能串口:USART_Cmd(USART1, ENABLE)
- fputc函数覆写:printf中循环调用fputc
- 主函数:初始化串口,调用printf()输出
代码
//usart.h
#ifndef _usart_H
#define _usart_H
#include "system.h"
void USART1_Init(u32 bound);
#endif
//usart.c
#include "usart.h"
#include "stdio.h"
//printf重定向,printf中循环调用fputc
int fputc(int ch, FILE* p)
{
USART_SendData(USART1, (u8)ch);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE)==RESET);//发送数据寄存器为空,已传至发送移位寄存器,但不一定发送完成
return ch;
}
void USART1_Init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
//开启端口时钟、串口时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
//配置Tx引脚
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);
//配置Rx引脚
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
GPIO_Init(GPIOA, &GPIO_InitStructure);
//配置串口
USART_InitStructure.USART_BaudRate = bound;//波特率
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长
USART_InitStructure.USART_StopBits = USART_StopBits_1;//停止位
USART_InitStructure.USART_Parity = USART_Parity_No;//校验位
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//硬件流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx|USART_Mode_Tx;//工作模式
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);//使能串口
}
//main.c
#include "usart.h"
#include "Systick.h"
int main()
{
USART1_Init(115200);//初始化串口
SysTick_Init(72);//初始化滴答定时器
while(1)
{
printf("11111\r\n");
delay_ms(500);
printf("22222\r\n");
delay_ms(500);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)