嵌入式 Printf Scanf 重新定义
/*
Init
CPU的小缺陷:串口配置好,如果直接Send,则第1个字节发送不出去
如下语句解决第1个字节无法正确发送出去的问题:
清发送完成标志,Transmission Complete flag
*/
USART_ClearFlag(USART1, USART_FLAG_TC);
/*
*********************************************************************************************************
* 函 数 名: fputc
* 功能说明: 重定义putc函数,这样可以使用printf函数从串口1打印输出
* 形 参: 无
* 返 回 值: 无
*********************************************************************************************************
*/
int fputc(int ch, FILE *f)
{
/* 写一个字节到USART1 */
USART_SendData(USART1, (uint8_t) ch);
/* 等待发送结束 */
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)
{}
return ch;
}
/**
* 函数功能: 重定向c库函数printf到DEBUG_USARTx
* 输入参数: 无
* 返 回 值: 无
* 说 明:无
*/
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&husart_debug, (uint8_t *)&ch, 1, 0xffff);
return ch;
}
/*
*********************************************************************************************************
* 函 数 名: fgetc
* 功能说明: 重定义getc函数,这样可以使用scanff函数从串口1输入数据
* 形 参: 无
* 返 回 值: 无
*********************************************************************************************************
*/
int fgetc(FILE *f)
{
/* 等待串口1输入数据 */
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);
return (int)USART_ReceiveData(USART1);
}
/**
* 函数功能: 重定向c库函数getchar,scanf到DEBUG_USARTx
* 输入参数: 无
* 返 回 值: 无
* 说 明:无
*/
int fgetc(FILE * f)
{
uint8_t ch = 0;
HAL_UART_Receive(&husart_debug,&ch, 1, 0xffff);
return ch;
}
作者:EnzoSun
微信关注:勿忘初兴
本文出处:http://sunduoze.github.io/post/2017/Printf_Scanf_Redefine/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
Sun's Blog