usart-printf.c
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 F4 board (STM32F401RE/F411RE, Cortex-M4) 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: USART2 (PA2/PA3) is routed to the ST-LINK serial converter, visible on the USB 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
Create a STM32CubeIDE project (pick Nucleo-F401RE or F411RE), paste the code into main.c, configure peripherals in the .ioc, then Run. The ST-LINK serial terminal 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);
}
}
}