STM32 serial port redirection supports Printf function CubeIDE and MDK (HAL library)

This tutorial is for HAL library, CubeIDE MDK

Preparation before experiment

Use CubeMx to create an STM32 project and open serial port 1
Insert image description here

MDK

Open the created project.
Insert image description here
Open the magic wand and check UseMicroLIB.
Insert image description here
Add the redirection function and add the header file #include "stdio.h"

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

Insert image description here
This is OK. You can test it. I won’t test it here.

CubeIDE

Added in usart.c

#ifdef __GNUC__
/* With GCC, 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__ */

PUTCHAR_PROTOTYPE
{
    
    
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART3 and Loop until the end of transmission */
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);//------->根据串口更改
  return ch;
}

Open settings project->properties
Insert image description here

You can use the printf function by adding #include "stdio.h" where it is used.

Summarize

HAL_UART_TransmitIt sends a buffered data in a leasing manner, and returns after the sending is completed or times out.

Guess you like

Origin blog.csdn.net/Systemmax20/article/details/132238152