stm32 ->HAL库重定向printf,实现串口打印

步骤

  • 在CubeMX中初始化uart引脚
MX_USART1_UART_Init();
  • 包含printf函数的头文件stdio.h

  • 重定义printf函数

int fputc(int ch, FILE *f)
{
	HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff); 
  return ch;
}
  • 勾选Use MicroLIB

stm32 ->HAL库重定向printf,实现串口打印_第1张图片

  • 编译烧录

实现代码

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
/* USER CODE END Includes */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
int fputc(int ch, FILE *f)
{
	HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff); 
  return ch;
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
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 */
  GPIO_PinState pinState = NULL;
 
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_1);
    pinState = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_1);
    
    if(pinState == GPIO_PIN_SET) {
        printf("PA1 is high\n");
    } else {
        printf("PA1 is low\n");
    }
    
    HAL_Delay(1000); 

  }
  /* USER CODE END 3 */
}

测试

stm32 ->HAL库重定向printf,实现串口打印_第2张图片

你可能感兴趣的:(STM32,stm32,单片机,嵌入式硬件)