STM32学习 printf串口输出 问题

164 阅读1分钟

keil

1.使用最新的cubemx生成keil项目,项目本身没有引用stdio.h,导致无法改造printf

之前的版本生成出来的项目是在 这里引用的,新版的,这个文件不引用的了

// Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_def.h
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_HAL_DEF
#define __STM32F4xx_HAL_DEF

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"
#include "Legacy/stm32_hal_legacy.h"
#include <stdio.h>

新的是

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_HAL_DEF
#define __STM32F4xx_HAL_DEF

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"
#include "Legacy/stm32_hal_legacy.h"
#include <stddef.h>

可以在这里引入,或者在main.h里引入stdio.h

  1. 以前的项目默认,使用Use MicroLIB, 新的并没有打开,导致即使上面加入了stdio.h 编译过了,但是还是无法输出,需要手动勾选

1701690299561.png

  1. 修改下载自动复位 options-> debug -> St-Link Debugger Settings -> Flash Download 勾选 Reset And Run 每个项目单独设置,不是全局的

1701690574648.png

  1. 在main.c中,增加函数
int fputc(int ch, FILE *p)
{
	while(!(USART1->SR & (1<<7)));
	USART1->DR = ch;
	return ch;
}

clueide

由于clue使用gun 编译 在main.c中重写

#ifdef __GNUC__
#define PUTCHAR_REDEFINE int __io_putchar(int ch)
#else
#define PUTCHAR_REDEINFE int fputc(int ch, FILE *f)
#endif

PUTCHAR_REDEFINE
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff);
return ch;
}

然后修改项目属性

image.png