Skip to main content
Graduate
September 1, 2025
Solved

USB received data interrupt callback

  • September 1, 2025
  • 1 reply
  • 354 views

I'm using the STM32F401RE in a new design and trying connect the USB CDC device interface to FreeRTOS_CLI. I modified its _write function to call CDC_Transmit_FS, but I don't see a received data callback where I can add a xTaskNotifyFromISRfor to send data to the CLI task.

It looks like I call CDC_Receive_FS to get the data, but I need an interrupt to trigger the call to that function. Where can I hook in a callback function?

    This topic has been closed for replies.
    Best answer by Karl Yamashita

    In the callback, you call your own function to save the data that's in Buf. Then in your main loop you can parse the data as you don't want to do any processing in the callback.

    static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
    {
     /* USER CODE BEGIN 6 */
     USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
     USBD_CDC_ReceivePacket(&hUsbDeviceFS);
    
     USB_AddRxBuffer(&usb_msg, Buf, *Len); // you own function to save the Buf/Len data and set a flag that indicaes you have new data
    
     return (USBD_OK);
     /* USER CODE END 6 */
    }

     

    Transmitting if pretty simple. You just pass your buffer and size

    uint8_t dataBuf[128] = {0};
    // update dataBuf with your data
    
    // send your data
    status = CDC_Transmit_FS(dataBuf , dataLen);

     

    1 reply

    Super User
    September 1, 2025

    CDC_Receive_FS is called from an interrupt context when new data comes in. You don't call it directly.

    Be aware that CDC_Transmit_FS will fail if the USB is still busy from the previous call to it. Also, the data needs to remain valid until the operation is complete. It's generally not compatible with how _write is called due to these reasons.

    Graduate
    September 1, 2025

    Thanks for the quick response! I don't understand how the USB interface works. Could you please point me to a document that explains its use? In particular, I'm looking for a function to call to write a byte or string to the USB port, along with a callback when data is received.

    Technical Moderator
    September 2, 2025

    Hi @jlthompson 

    You can check this user manual. However, it may not provide all detailed implementation for each USB class.