debuggingusbstm32cdc

STM32 printf over USB CDC


Currently I am developing software and I am stuck. I need some help.

I am using STM32F103, HAL and library FreeRTOS.

I wrote a little serial debugger function that sends characters over UART or USB CDC.

Here is my definitions:

In the header file:

#if ( DEBUG == DEBUG_ENABLE )
    /* printf definition */
    #define DEBUG_MSG( FLAG, fmt, ...)
    do
    {
        if( FLAG )
            printf( "[%08d]%s:%d:%s(): " fmt "\r\n", HAL_GetTick(), __FILE__, __LINE__, __func__, ##__VA_ARGS__);
    }while( 0 );
#else
    #define DEBUG_MSG( FLAG, fmt, ... )
#endif

And in the C file:

#define PUTCHAR_PROTOTYE int fputc( int ch, FILE *f )

PUTCHAR_PROTOTYE
{
#if DEBUG_PORT == USB_DEBUG
    CDC_Transmit_FS((uint8_t *)&ch, 1);
#elif DEBUG_PORT == UART_DEBUG
    HAL_UART_Transmit( pDEBUG_PORT, ( uint8_t * )&ch, 1, 0xFFFF );
#else
    #error "Define a debug port!"
#endif
    return ch;
}

I am using this like: DEBUG_MSG(MAIN_DEBUG, "Gsm manager thread started!");

When the debugger port is uart_debug, there isn't any problem at all. Everything runs perfectly.

But whenever I select usb_debug port, there is something happening.

While the debug port is USB CDC, I am getting some text like below:

"[0[0[0[0[6"

But in the debug mode, in the putc function I am putting a breakpoint at CDC_Transmit_FS((uint8_t *)&ch, 1); line, and pressing F5 and I am getting:

[00010046]../Src/main.c:633:gsmmanager_handler(): Gsm manager thread started!

string just like as I am expecting. And if I put CDC_Transmit_FS((uint8_t *)"test", strlen("test")); lines right after CDC_Transmit_FS((uint8_t *)&ch, 1); and I am getting:

[0[0test

string.

So I don’t understand anything. What could it be?


Solution

  • I did write the code below and it runs for me:

    PUTCHAR_PROTOTYPE
    {
        //while(!(CDC_Transmit_FS((uint8_t*)&ch, 1) == USBD_OK))
        //    ;
        while(!(CDC_Transmit_FS((uint8_t*)&ch, 1) == USBD_BUSY))
            ;
    
        return ch;
    }
    

    The reason could be that when the second character is passed to the function, the first one is still on the way so the second one is discarded because the line is busy. I'm not sure if this is your problem.

    It could be useful to add a timeout check to avoid infinite loops.