How to implement “printf” for send message via USB on STM32 NUCLEO boards using KEIL

This example show the way to implement the printf on STM32 NUCLEO board for send data via USB to the PC.

Pre Requirements:

  • Install CUBE-MX
  • Install KEIL if you use STM32L0 or STM32F0 the free version of KEIL is here
  • Install the tools for use STM32, see here.

I suggest to use on the PC a terminal emulator like TeraTerm, configured has show below.

It’s possible use the USB connector present on the STM32 NUCLEO board for send data from NUCLEO to the PC thanks to the functionalities of the ST-LINK-v2 present on the NUCLEO boards.

If you look the schematics of the STM32 NUCLEO boards you see that the USART2 of the STM32xxx present on your NUCLEO board, is connect to the STM32F103CBT6 that implement the ST-LINK-v2 functionalities.

So for implement the printf via USB port is necessary configure the USART2 and redirect the PUTCHAR to USART.

For do this is necessary the C code show below.

Insert from:
/* USER CODE BEGIN 0 */
and
/* USER CODE END 0 */
the code below.

#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
 set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

Insert from:
/* USER CODE BEGIN 4 */
and
/* USER CODE END 4 */
the code below.

/**
 * @brief Retargets the C library printf function to the USART.
 * @param None
 * @retval None
 */
PUTCHAR_PROTOTYPE
{
 /* Place your implementation of fputc here */
 /* e.g. write a character to the USART2 and Loop until the end of transmission */
 HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xFFFF);

return ch;
}

Also are necessary some extra line of code for test the application.

Insert from:
/* USER CODE BEGIN PV */
/* Private variables ———————————————————*/
and
/* USER CODE END PV */
the code below.

uint32_t nLoop=0;

Insert from:
/* USER CODE BEGIN 3 */
and
/* USER CODE END 3 */
the code below.

 HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin); // PORTA, PA5
 HAL_Delay(500);
 nLoop++;
 printf("nLoop == %d \n\r", nLoop);

How to get the SW for this project

Please send us an email and ask us the password for: Printf-NU091-KEIL
Please specify also your country and your city, this are only for our personal statistics.

Get the SW clicking here, but remember to ask us the password for open it.

Note: the project contain also the file for CUBE-MX

Thanks to CUBE-MX is very easy transfer this example on other STM32 mcu.