参考: CubeMx教程
前言
- 我的板子是:STM32ZGT6
配置
1.打开STM32CubeMX新建工程,选择STM32ZGT6
2.配置外部高速时钟
RCC设置,选择HSE(外部高速时钟)为Crystal/Ceramic Resonator(晶振/陶瓷谐振器),我的开发板外部时钟是25MHZ。
3.配置串行通信
选择Asynchronous异步通信。
串口配置设置波特率为115200 Bits/s。传输数据长度为8 Bit。奇偶检验无,停止位1.其他参数默认。
生成报告以及代码,编译程序(最好单独生成.c和.h文件)。在usart.c文件中可看到串口1的初始化函数MX_USART1_UART_Init(void),以及管脚配置函数HAL_UART_MspInit()。
4.重新定义printf函数
在usart.c文件后面添加如下代码,代码中添加了#ifdef宏定义进行条件编译,如果使用GUNC编译,则PUTCHAR_PROTOTYPE 定义为int __io_putchar(int ch)函数,否则定义为int fputc(int ch, FILE *f)函数。
/* USER CODE BEGIN 1 */
#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 EVAL_COM1 and Loop until the end of transmission */
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
/* USER CODE END 1 */
5.使用
这个时候可以使用printf打印东西