在STM32开发当中,会经常使用系统自带的printf函数来查看调试输出,通常是将系统的printf输出内容发往串口,具体实现如下:
#include <stdio.h> //定义标准库头文件
int fputc(int ch, FILE *f)
{
/* 将Printf内容发往串口 */
USART_SendData(USART1, (unsigned char) ch);
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
return (ch);
}
上面是使用了串口1 作为printf函数的输出,如果只是查看调试输出,只需要初始化部分功能:
void USART1_Init(void)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA |RCC_APB2Periph_USART1|RCC_APB2Periph_AFIO , ENABLE);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Configure the USART1_Rx as input floating
GPIO_InitStructure.GPIO_Mode =GPIO_Mode_IN_FLOATING ;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 115200;
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_Tx;
/* Configure the USARTx */
USART_Init(USART1, &USART_InitStructure);
/* Enable the USARTx */
USART_Cmd(USART1, ENABLE);
}
设置为输出 115200波特率 然后在主程序中调用
int main (void){//主程序
USART1_Init();
printf("USART1_Init OK");
while(1);
}
然后编译
0错误0警告
马上下载到板子上,结果等半天串口输出还是没有,后面往程序前后加入了LED灯的状态改变,也是毫无变化,可以确定程序彻底死了。。。
然后找了半天错误才发现
是这个奥东西没选 导致引用了标准库的printf函数。。。
再次编译
结果出来的程序大小。。。小了接近一倍。。。
下载运行就一切OK了
以上编译软件:KEIL MDK525
MCU:STM32F103C8T6