STM32在使用串口時,有時需要使用串口輸出來觀察程序運行狀態。這時,我們需要將printf進行重定向。
具體重定向方法為:
1、 添加printf的頭文件 #include <stdio.h>
2、重寫int fputc(int ch, FILE *f)函數
int fputc(int ch, FILE *f);
函數
int fputc(int ch, FILE *f)
{
USART_SendData(USART1, (uint8_t) ch);
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
return ch;
}
3、修改一下選中Use MicroLIB Target——Code Generation——選中Use MicroLIB
方法2,也可以避免使用半主機模式進行操作。
#if 1 #pragma import(__use_no_semihosting)
//標准庫需要的支持函數
struct __FILE
{
int handle;
};
FILE __stdout; //定義_sys_exit()以避免使用半主機模式
_sys_exit(int x)
{
x = x;
}
//重定義fputc函數
int fputc(int ch, FILE *f)
{
while((USART1->SR&0X40)==0);//循環發送,直到發送完畢
USART1->DR = (u8) ch;
return ch;
}
#endif
需要注意的還有自己的波特率,在stm32f10x.h中修改
#define HSE_VALUE ((uint32_t)8000000) /*寫自己板子的波特率即可,默認是沒有的 */
#if !defined HSE_VALUE
#ifdef STM32F10X_CL
#define HSE_VALUE ((uint32_t)25000000) /*!< Value of the External oscillator in Hz */
#else
#define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */
#endif /* STM32F10X_CL */
#endif /* HSE_VALUE */
