HAL CDC Transmit dropping and duplicating data
I have an issue where CDC transmission from an STM32L4 is dropping or duplicating data.
Here is a simple test case that runs from main.c
extern USBD_HandleTypeDef hUsbDeviceFS;
static uint8_t UserTxBufferFS[100];
void TestSerial()
{
// connect USB during this delay
HAL_Delay(5000);
USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData;
while(1)
{
while (hcdc->TxState != 0);
// usb no longer till transmitting
memcpy(UserTxBufferFS, "01234567890", 11);
uint8_t ret = CDC_Transmit_FS(UserTxBufferFS, 11);
if (ret != USBD_OK)
{
// data not sent, so retry
}
while (hcdc->TxState != 0);
// usb no longer till transmitting
memcpy(UserTxBufferFS, "12345678901", 11);
ret = CDC_Transmit_FS(UserTxBufferFS, 11);
if (ret != USBD_OK)
{
// data not sent, so retry
}
while (hcdc->TxState != 0);
// usb no longer till transmitting
memcpy(UserTxBufferFS, "23456789\r\n", 10);
ret = CDC_Transmit_FS(UserTxBufferFS, 10);
if (ret != USBD_OK)
{
// data not sent, so retry
}
HAL_Delay(100);
}
}This simply posts an expected line out of the USB UART in three chunks, waiting for the TxState to indicate transmission is complete before sending the next block.
From the PC end the terminal shows an occasional either dropped or extended message:
I've pulled this test case out of a very large product code base down to a boot time example of CDC not working. It looks like the buffers are being overwritten or pointers are being corrupted on the next frame transmission, but there is nothing going on here except a loop of basic serial over USB transmission.

I've tested changing the CDC_Transmit_FS size and around 8 bytes length is a sweet spot for least corruption, but it appears to corrupt whatever the size.
I've tried 100ms delays after TxState becomes 0 but it still randomly corrupts on send!
Any ideas?
Many thanks.