Serial Debugging
One of the most confusing things for developers coming from Arduino is that serial output is not defined by default. In the Arduino ecosystem, debugging is mostly done by printing stuff on the serial console.
On STM32s, debugging is usually done using in-circuit debugging (using an ST-Link or similar device), and a serial console is often not needed. There are however multiple ways a serial console can be implemented, either using a UART, a virtual serial port via USB or SWO (Serial Wire Output). All three are hooked up the same way: by telling the C library where the output of printf should go.
Video
You can watch the video on YouTube here: https://www.youtube.com/watch?v=y_KKHWecsj0 (full series here: https://www.youtube.com/playlist?list=PLVfOnriB1RjWT_fBzzqsrNaZRPnDgboNI).
How printf works on an STM32
printf comes from newlib (or newlib-nano), the C library that ships with the ARM GCC toolchain used by STM32CubeIDE. newlib formats the text and then hands it to a low-level function called _write(). newlib has no idea what hardware the board has, so it is up to the application to provide a _write() that sends the bytes somewhere useful.
STM32CubeIDE generates a file Core/Src/syscalls.c which contains a weak _write(). It calls __io_putchar() once for every character. That gives two options:
- Implement
__io_putchar(int ch), which sends one character at a time. It is simple and makes it trivial to turn every\ninto\r\n, but it is slower for long strings. - Implement
_write(int fd, char *ptr, int len), which overrides the weak one insyscalls.cand gets the whole buffer at once. This is usually faster, and it can tell stdout (fd 1) and stderr (fd 2) apart.
Implement one or the other, not both.
There are two gotchas that catch almost everybody:
- stdout is line buffered. Nothing is sent until a
\nis printed (or the buffer fills up). If output seems to be missing, check for a missing newline, or turn buffering off at the beginning ofmain():
setvbuf(stdout, NULL, _IONBF, 0);
- newlib-nano does not print floats by default.
printf("%f", x)prints nothing until "Use float with printf from newlib-nano (-u _printf_float)" is ticked under Project Properties → C/C++ Build → Settings → MCU Settings. This adds a few kB of flash.
Which method to use?
| U(S)ART | USB virtual COM port | SWO | |
|---|---|---|---|
| Extra hardware | USB-serial adapter (or the ST-Link VCP on Nucleo boards, the Jolt Connect or the Streamline Connect) | None, just a USB cable | ST-Link with the SWO pin connected |
| Pins used | TX (and RX for input) | USB D+ and D− | SWO (usually PB3) |
| Input from the PC | Yes | Yes | No, output only |
| Works without a debugger | Yes | Yes | No |
| Available on | Every STM32 | STM32s with a USB device peripheral | Cortex-M3/M4/M7/M33 (not M0/M0+) |
| Main drawback | Uses a UART and needs an adapter | USB must be free, output is lost until the PC opens the port | Only works while debugging |
U(S)ART Serial
The classic approach is to send the output out of a UART and convert it to USB with a cheap USB-serial adapter.
In STM32CubeMX, set the U(S)ART (USART1 in the examples below) to Asynchronous mode. 115200 baud, 8 data bits, no parity and 1 stop bit (8N1) is a sensible default, but most adapters go much faster.
Many Nucleo boards don't need an adapter at all. The on-board ST-Link has a virtual COM port, which on most Nucleo-64 boards is wired to USART2 (PA2/PA3).
The same goes for Streamline. The Streamline Connect provides a USB-serial port (a virtual COM port) which, by default, is wired to USART1 (PA9/PA10, backplane pins B45/B46) on the STM32 MCU blades and to UART0 (GPIO0/GPIO1) on the RP2354 blade. The examples on this page all use USART1, so they work on a Streamline STM32 blade as they are. See Streamline Header Mapping for the full pin mapping.
Both the Jolt Connect and the Streamline Connect run their virtual COM port at up to 2 Mbit/s (2000000 baud), and they are stable at that speed. This works with the ST-Link and DAPLink firmware as well as with Hybridlink, which any existing Connect can easily be upgraded to. Set the same baud rate on the U(S)ART and in the terminal.
There are two ways printf can be redirected to a UART. First, using the _write function:
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
// Send printf to uart1
int _write(int fd, char* ptr, int len) {
HAL_StatusTypeDef hstatus;
if (fd == 1 || fd == 2) {
hstatus = HAL_UART_Transmit(&huart1, (uint8_t *) ptr, len, HAL_MAX_DELAY);
if (hstatus == HAL_OK)
return len;
else
return -1;
}
return -1;
}
/* USER CODE END 0 */
Alternatively, using __io_putchar:
// Send printf to uart1
int __io_putchar(int ch) {
if (ch == '\n') {
HAL_UART_Transmit(&huart1, (uint8_t*)"\r", 1, HAL_MAX_DELAY);
}
if (HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, HAL_MAX_DELAY) != HAL_OK) {
return -1;
}
return ch;
}
The main benefit of the second approach is that one can automatically add a carriage return for every line feed.
On the PC side, any terminal program will do, for example:
microcom -s 115200 -p /dev/ttyUSB0
On Windows, use PuTTY or Tera Term with the COM port the adapter shows up as.
Virtual COM port over USB
Creating and using a virtual COM port over USB is really easy, provided the USB port is not used for anything else.
First step is to enable USB in device mode under Connectivity in STM32CubeMX:
Next, set the USB Device Middleware to Communication Device Class:
After generating code, the device should show up as a virtual COM port (/dev/ttyACM0 on Linux, a COM port on Windows).
The final step is to redirect output from printf to this virtual COM port rather than one of the UARTs. Unlike HAL_UART_Transmit, CDC_Transmit_FS does not wait for the data to be sent. It returns USBD_BUSY if the previous transfer is still in progress, so _write() has to retry until the USB stack is ready again:
#include "usbd_cdc_if.h"
int _write(int fd, char *ptr, int len) {
uint32_t start = HAL_GetTick();
// Retry while the previous transfer is still in progress
while (CDC_Transmit_FS((uint8_t*) ptr, len) == USBD_BUSY) {
if (HAL_GetTick() - start > 10) {
return -1; // Nobody is reading - give up rather than hang
}
}
return len;
}
The timeout matters. If no terminal has the port open, the PC never collects the data, and without a timeout the firmware would hang on the first printf. On parts where the device runs on the high-speed USB peripheral, the function is called CDC_Transmit_HS instead.
You can now use printf to print debugging statements, for example:
uint32_t then = 0, now = 0;
while (1) {
now = HAL_GetTick();
if (now % 1000 == 0 && now != then) {
printf("Tick (now = %lu)\n", now / 1000);
then = now;
}
}
The above while loop results in the following output on the virtual serial port:
lth@ncpws04:~$ microcom -f -s 921600 -p /dev/ttyACM0 connected to /dev/ttyACM0 Escape character: Ctrl-\ Type the escape character to get to the prompt. Tick (now = 1) Tick (now = 2) Tick (now = 3) Tick (now = 4) Tick (now = 5) Tick (now = 6) ...
The baud rate set in the terminal doesn't matter for a USB virtual COM port. The data always travels at USB speed, so any setting works.
Keep in mind that anything printed before the PC has enumerated the device and opened the port is lost. Messages printed right after reset will usually not be seen.
Using SWO
Using SWO for serial output is described in this video:
SWO (Serial Wire Output) is a single pin, next to the SWDIO and SWCLK debug pins, through which the core's ITM (Instrumentation Trace Macrocell) can stream data to the debugger. It is available on Cortex-M3, M4, M7 and M33 based STM32s, but not on the Cortex-M0/M0+ parts (F0, G0, L0, C0). If the SWO pin is hooked up to the ST-Link, printf output can be redirected using this snippet:
// Send printf to SWO
int _write(int fd, char *ptr, int len) {
for (int i = 0; i < len; i++) {
ITM_SendChar(ptr[i]); /* core_cm4.h */
}
return len;
}
To see the output in STM32CubeIDE:
- In STM32CubeMX, under System Core → SYS, set Debug to "Trace Asynchronous Sw". This enables the SWO pin (PB3 on most STM32s).
- In the debug configuration, on the Debugger tab, enable Serial Wire Viewer (SWV) and set the Core Clock to the actual HCLK frequency (for example 168 MHz on an STM32F4). If the clock is wrong, the output will be garbage or nothing at all.
- Start a debug session and open Window → Show View → SWV → SWV ITM Data Console.
- Click the "Configure trace" button, tick ITM Stimulus Port 0, then press "Start Trace" and resume the program.
ITM_SendChar() silently does nothing when no debugger has enabled tracing, so it is safe to leave in the code.
Using USART and SWO
If an STM32 is hooked up to an ST-Link including the Serial Wire Viewer, it might be advantageous to send one serial stream to the USART and another to the SWO. _write() receives the file descriptor, so stdout and stderr can go different ways:
// Send stdout to USART1 and stderr to SWO
int _write(int fd, char *ptr, int len) {
if (fd == 1) {
HAL_StatusTypeDef hstatus;
hstatus = HAL_UART_Transmit(&huart1, (uint8_t*) ptr, len, HAL_MAX_DELAY);
if (hstatus == HAL_OK)
return len;
else
return -1;
} else if (fd == 2) {
for (int i = 0; i < len; i++) {
ITM_SendChar(ptr[i]); /* core_cm4.h */
}
return len;
}
return -1;
}
Normal output is then printed with printf(...), and debug output with fprintf(stderr, ...).
Source Code
The complete examples are on GitHub:
- stm32world_serial_print: UART and USB virtual COM port
- stm32world_swo: USART and SWO

