串口打印printf
1.配置串口
打开STM32CubeMX,创建工程,配置串口。
2.添加代码
重写fputc函数,需要包含头文件 #include <stdio.h>
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h> //第一步包含头文件
/* USER CODE END Includes */
......
......
......
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
int fputc(int c, FILE *stream) //重写fputc函数
{
/*
huart1是工具生成代码定义的UART1结构体,
如果以后要使用其他串口打印,只需要把这个结构体改成其他UART结构体。
*/
HAL_UART_Transmit(&huart1, (unsigned char *)&c, 1, 1000);
return 1;
}
/* USER CODE END 0 */
......
......
......
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
printf("串口打印printf\r\n"); //使用库的printf
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
3.使用MDK勾选Mircro LIB
不成功的话,检查一下下面这个√有没有勾上。
我用STM23CubeIDE,直接生成下载代码后,是无法打印的。换用的MDK,Mircro LIB,才能打印的。
目前还不知道 STM23CubeIDE 怎么才能打印出来。