Printf() with Nucleo Board
Objective
This page provides a solution to empower users using printf() function on some of the STM Nucleo boards for debugging purposes. This method though may not apply to every Nucleo board. I will discuss the prerequisites for using this printf() method later. Following this instruction should allow you to printf() in the code, and the message will be seen in the serial console with only the USB cable connection between the board and the computer, similar to the serial console in Arduino.
Theory Behind This
Many of the STM32 Nucleo boards support Virtual COM Port(VCP) functionality. VCP allows one of the MCU’s UART to connect to the ST-Link(programmer) and then forwards the serial message to the USB port on board. The USB will receive all the messages from VCP UART, similarly it also sends messages to the VCP UART. The printf() method we gonna be talking about is achieved by overriding the printf() function in the stm so that it sends the message to the VCP UART.
Step Towards Printf()
Look up the datasheet of your Nucleo board
The first thing we need to confirm is what UART is used at the VCP UART for this Nucleo board. Take Nucleo-L552ZE as an example, by looking at the datasheet we can see the virtual com port is LPUART1. This is different between nucleo boards. Nucleo-F401 has UART2 as its virtual com port.
ioc configuration
Now we know the VCP UART, we wanna know the baudrate configuration on that UART port so that we can open a console that listens to the serial input at the same baudrate. You can change the baudrate if the original number is not what you like.
Add the override function to your code
Add the following code somewhere in your code. The hlpuart1
can be replaced by the VCP UART in your board’s configuration. The function overrides the printf() to direct it to output the message into the uart port you specified here.
int __io_putchar(int ch)
{
HAL_UART_Transmit(&hlpuart1,(uint8_t*)&ch,1,HAL_MAX_DELAY);
return ch;
}
Printf
Now you can call printf anywhere in your!
You will have to include the “\r\n“ at the end of the message you wanna print for some reason. Otherwise it won’t work.
Check the output
You can use Putty or any software that can open a serial port monitor. But here I want to introduce the serial monitor in the STM32 IDE that is often overlooked by everyone. I was only able to notice this functionality in the stm32 ide by an ECE lab. Here is how you can open it.
Open console
in stm32 ide
By default, this opens the Debug and Download console. We instead want the serial console. To
do this we need to open a new console, so click the new console buƩon, then select “Command
Shell Console”.
Click New...
, provide the correct COM
port number and Baud rate
This will allow your to open a serial monitor in stm ide.
Below are some other tips.