STM32重定向printf的两种方法,并解决在TIMER2中printf只能打印double类型的整数部分

方法一:直接在工程中添加以下代码,然后那个c文件要使用,直接用 #include "stdio.h" 即可使用printf

/**************加入以下代码,支持printf函数,而不需要选择use MicroLIB***************/ 
#if 0
#pragma import(__use_no_semihosting)                         
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. */ 
}; 
/* FILE is typedef¡¯ d in stdio.h. */ 
FILE __stdout;         
_sys_exit(int x) 
{ 
	x = x; 
} 
//Öض¨Òåfputcº¯Êý 
int fputc(int ch, FILE *f)
{    
	//while((USART1->SR&0X40)==0);//Ñ­»··¢ËÍ,Ö±µ½·¢ËÍÍê±Ï   
	//USART1->DR = (u8) ch;  
	USART_SendData(USART1,(u8)ch);
	while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
	return ch;
}
#endif 
/********************************************************************************/

这种方法发现了一个很奇怪的问题,在定时器2TIMER2中,打印double类型数据时,只能打印整数部分,无法打印小数点和小数部分。例如 double test = 5.6789;

用printf("%f",test);只能输出5

尝试各种办法,后来尝试下述第二种方法解决这个问题。

方法二:

参考链接   https://blog.csdn.net/menghubei/article/details/50761588

(1/3)在usart.c文件中添加以下代码

int fputc(int ch, FILE *f)
{    
USART_SendData(USART1,(u8)ch);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
return ch;
}

(2/3)在usart.h文件添加声明

int fputc(int ch, FILE *f);


(3/3)在设置中勾选Use MicroLIB选项

此时就能在TIMER2中打印double函数了。






猜你喜欢

转载自blog.csdn.net/mashang123456789/article/details/80612687