Enable printf() function to work with USB Virtual COM Port (STM32H743ZI)
STM32CubeMX
- Turn on USB_OTG_FS with mode Device_Only
- In the Middleware turn on USB_DEVICE with class Communication Device Class (Virtual Com Port)
- Default settings
- Generate Code
main.c
#include <stdio.h>
- Add code below between /* USER CODE BEGIN 4 */
int _write(int file, char *ptr, int len) {
CDC_Transmit_FS((uint8_t*) ptr, len); return len;
}
For cpp project:
extern "C" int _write(int file, char *ptr, int len) {
CDC_Transmit_FS((uint8_t*) ptr, len); return len;
}
That's it! Now you can use printf() anywere you want.
NOTICE! When I started to using FreeRTOS I've noticed that printf displays an incorrect value. Digging a bit, I found out that if you are enable the delay after CDC_Transmit_FS(), then everything works fine, so:
int _write(int file, char *ptr, int len) {
CDC_Transmit_FS((uint8_t*) ptr, len);
osDelay(1);
return len;
}
work's for me!