这几天在学习使用STM32的UART的使用。参照的例程中直接使用了printf函数来从串口输出数据。
照着葫芦画瓢,写了个简单的串口发送程序,可是在调试的时候,程序好像在执行启动代码的时候卡死在某个地方了,老是进不了main函数。而在正常情况下,黄色箭头应该停在main函数的第一条指令处,等待我输入调试指令。我试了试不使用printf函数,直接使用STM32库函数发送串口数据,没问题。说明问题出在使用printf函数上。在网上一搜,果然。
原来这个C语言里熟到不能再熟的printf函数,背后还有一些我不知道的事,在此之前,这printf函数用得实在是太无知了。
以下是网上的一段非常不错的解释。
/******************************************************************************************/
#ifdef __GNUC__ /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf set to 'Yes')calls__io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */ /* e.g. write a character to the USART */
USART_SendData(USART1, (uint8_t) ch);
/* Loop until the end of transmission */
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)
{
}
return ch;
}