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:
using osDelay function (click to expand)
int _write(int file, char *ptr, int len) {
CDC_Transmit_FS((uint8_t*) ptr, len);
osDelay(1);
return len;
}
There is a better solution suggested by Paunida:
int _write(int file, char *ptr, int len) {
static uint8_t rc = USBD_OK;
do {
rc = CDC_Transmit_FS(ptr, len);
} while (USBD_BUSY == rc);
if (USBD_FAIL == rc) {
/// NOTE: Should never reach here.
/// TODO: Handle this error.
return 0;
}
return len;
}
work's for me!