usart-printf.c

STM32H7 Nucleo-144 (flagship: NUCLEO-H743ZI) · File : usart-printf.c · Language : C · Use case : Envoyer des mesures sur le port série (USART) avec printf

Redirecting printf() to the USART in three lines: the board sends readings over the USB virtual serial port, visible in a terminal at 115200 baud. The retargeting pattern is the same across the STM32 range with HAL.

Hardware

A Nucleo H7 board (STM32H743ZI, Cortex-M7 @ 480 MHz) programmed via ST-LINK (USB), 3.3 V pins. A USB cable on the board connector (ST-LINK virtual serial port or built-in converter).

Wiring

No wiring needed: the console UART3 (PD8/PD9) is routed to the ST-LINK virtual serial port..

How it works

__io_putchar() is called by printf for each character; it forwards it through HAL_UART_Transmit. The serial terminal (minicom, PuTTY, CubeIDE monitor) shows the lines at 115200 8N1.

Running it

STM32CubeIDE project based on the Nucleo-H743ZI: drop the code into main.c, declare peripherals in the .ioc, then Run over ST-LINK. The ST-LINK serial monitor shows printf at 115200.

Variants

Use HAL_UART_Transmit_DMA to avoid blocking the CPU, or add interrupt reception + sscanf for a mini protocol.

usart-printf.c

// printf vers USART (le port serie virtuel de la carte).
#include "main.h"
#include <stdio.h>

extern UART_HandleTypeDef huart2; // genere par CubeMX (USART2)

// Redirection de printf vers le HAL (retarget).
int __io_putchar(int ch) {
  HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
  return ch;
}
// Variante recentree sur newlib (selon la toolchain) :
// int _write(int f, char *p, int n){ HAL_UART_Transmit(&huart2,(uint8_t*)p,n,100); return n; }

uint32_t t0 = 0;

int main(void) {
  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init();
  MX_USART2_UART_Init();  // 115200 8N1 dans le .ioc

  for (;;) {
    if (HAL_GetTick() - t0 >= 1000) {
      t0 = HAL_GetTick();
      float mesure = 3.3f * (float)HAL_GetTick() / 100000.0f; // exemple
      printf("t=%lu ms  mesure=%.2f V\r\n",
             (unsigned long)HAL_GetTick(), mesure);
    }
  }
}

← Back to the board