Skip to main content
Visitor II
April 17, 2020
Question

Hello, I have implemented the code for the USB VCP, but when debugging the code the "pdev->pClassData" is always null (0). Where is this class initialized? code line : USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef *)pdev->pClassData;

  • April 17, 2020
  • 3 replies
  • 1767 views

Cube MX 5.6.1 generated code:

void MX_USB_DEVICE_Init(void)

{

 /* USER CODE BEGIN USB_DEVICE_Init_PreTreatment */

  

 /* USER CODE END USB_DEVICE_Init_PreTreatment */

  

 /* Init Device Library, add supported class and start the library. */

 if (USBD_Init(&hUsbDeviceFS, &FS_Desc, DEVICE_FS) != USBD_OK)

 {

  Error_Handler();

 }

 if (USBD_RegisterClass(&hUsbDeviceFS, &USBD_CDC) != USBD_OK)

 {

  Error_Handler();

 }

 if (USBD_CDC_RegisterInterface(&hUsbDeviceFS, &USBD_Interface_fops_FS) != USBD_OK)

 {

  Error_Handler();

 }

 if (USBD_Start(&hUsbDeviceFS) != USBD_OK)

 {

  Error_Handler();

 }

 /* USER CODE BEGIN USB_DEVICE_Init_PostTreatment */

  

 /* USER CODE END USB_DEVICE_Init_PostTreatment */

}

to send data this is implemented

 while (1)

 {

  /* USER CODE END WHILE */

 USBD_CDC_SetTxBuffer(&hUsbDeviceFS, &buffer[0], sizeof(buffer));

 USBD_CDC_TransmitPacket(&hUsbDeviceFS);

 HAL_delay(1000);

  /* USER CODE BEGIN 3 */

 }

    This topic has been closed for replies.

    3 replies

    Super User
    April 17, 2020

    > Where is this class initialized?

    pdev->pClassData is initialized when you call USBD_RegisterClass.

    If it is 0 after successful return from USBD_RegisterClass, you probably have memory corruption.

    -- pa

    RPersAuthor
    Visitor II
    April 18, 2020
    Thanks for the reply. I will look into this
    Rex
    Super User
    April 19, 2020

    This field is only populated after the PC successfully enumerates the device, which is not instant. It also uses malloc, which is probably not what one would expect.

    Typically putting HAL_Delay(500) prior to using the USB functions works, although it's not an elegant solution.

    Super User
    April 19, 2020

    Please see here for example (STM32F0). No allocation, and the pointer to the class struct is stored immediately.

    Here is shown how USBD_RegisterClass is called.

    -- pa

    RPersAuthor
    Visitor II
    April 19, 2020
    Thanks Pavel
    Rex
    Graduate
    April 19, 2020

    If you use freeRTOS, also take a look here (in case of memory corruption...) :

    http://www.nadler.com/embedded/newlibAndFreeRTOS.html

    RPersAuthor
    Visitor II
    April 19, 2020
    Yes I do have FreeRtos implemented.
    Thanks for the hint
    Rex