STM32的串口调试经验


  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 */


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM