STM32 Debugging with printf() by using SWV or OpenOCD

It is easier to follow a console with successful or error messages when debugging rather than check each value on watch expressions or memory sections. It is possible to debug with the use of printf statements in STM32. Also, there is a tempting point about this way of debugging that you don’t need any hardware or extra pins in your project. In this post, the debugging methods are explained by using STM32CubeIDE.

There are two ways that are going to explained in this post:

  • Serial Wire Viewer (SWV)
  • OpenOCD

Serial Wire Viewer (SWV)

In this method, writing the console is achieved by simply enabling the SWV option on debugging configurations.

Then, there must be changes in syscalls.c source file, the stm32f4xx.h header file must be included and _write() function must be revised as shown in images.

#include "stm32f4xx.h"
__attribute__((weak)) int _write(int file, char *ptr, int len)
{
	int DataIdx;

	for (DataIdx = 0; DataIdx < len; DataIdx++)
	{
		//__io_putchar(*ptr++);
		ITM_SendChar(*ptr++);
	}
	return len;
}

Then at the start of the debug session, Window->Show View->SWV->SWV ITM Data Console must be chosen. Selected window will be appeared, then Configure Trace button. At the ITM Stimulus Ports tick the Port 0, as the image.

After the setting, click Start Trace which is a red dot. Then, debugging can be proceed. The printf() results can be seen at the opened Port 0.

OpenOCD

Firstly, it is needed to open Debug Configuration section. There are two things should be done in this section.

  • Debug Probe should be selected as ST-LINK (OpenOCD) at Debugger part.
  • “monitor arm semihosting enable” must be added to Run Commands at Startup part.

Then, “-specs=rdimon.specs -lc -lrdimon” must be added to Project->Properties->C/C++ Build->Settings->Tool Settings->MCU GCC Linker->Miscellaneous->Other Flags->Add

After these steps we must add some code to main.c which are

extern void initialise_monitor_handles();

to main.c and calling the related function in main.

initialise_monitor_handles();

As a last step we should right click to syscalls.c Properties-> C/C++ Build then tick the Exclude resource from build.

Therefore, printf statements can be seen at Console when debugging project.

2 Replies to “STM32 Debugging with printf() by using SWV or OpenOCD”

  1. Verified on 29 July 2021 that the OpenOCD method above worked with STM32CubeIDE 1.7.0 on Linux Mint 20.2 Cinnamon configured for a NUCLEO-F767ZI over ST-LINK V2.1 This helped a lot. Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *