Electronic – USB CDC flushing TX buffer

stm32usb

A brief introduction to this problem:

I have a STM32F767 which is configured for USB Device FS. USB interface is used to transmit a large array of data from MCU to computer. If, by any chance user closes the Virtual Com Port (USB) of MCU, next time user opens Virtual Com Port (USB), MCU will send remaining data it was transmitting to computer, creating a lot of troubles.

I want to flush TX buffer of USB Device mode or abort transmition progress whenever VCP is opened/closed in the computer. I've to mention that I use HAL libraries.

Best Answer

I'm using STM32Cube v1.16.0 and this is working for me:

#include "stm32f4xx_ll_usb.h"

...

PCD_HandleTypeDef *hpcd = hUsbDeviceFS.pData;
USB_FlushTxFifo(hpcd->Instance, 0x10U);

Flag 0x10U means "Flush all Tx buffers". See stm32f4xx_ll_usb.c for details.