In CubeMX generated USB code HAL_PCD_ResetCallback() always calls Error_Handler
Because of a mismatch in the enumeration of USB speeds the HAL_PCD_ResetCallback() can not determine the correct USB speed and calls Error_Handler().
In this example it occurs in CubeIDE v1.0.1 on STM32F767VIT6 with the USB-FS interface configured as CDC-ACM device. But it also happens with different targets and on CubeMX 5.1.0, 5.2.0 and 5.2.1.
Here's a copy of the HAL_PCD_ResetCallback() function in "usbd_conf.c":
void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd)
{
USBD_SpeedTypeDef speed = USBD_SPEED_FULL;
if ( hpcd->Init.speed == PCD_SPEED_HIGH)
{
speed = USBD_SPEED_HIGH;
}
else if ( hpcd->Init.speed == PCD_SPEED_FULL)
{
speed = USBD_SPEED_FULL;
}
else
{
Error_Handler();
}
/* Set Speed. */
USBD_LL_SetSpeed((USBD_HandleTypeDef*)hpcd->pData, speed);
/* Reset Device. */
USBD_LL_Reset((USBD_HandleTypeDef*)hpcd->pData);
}When I debug I can see that "hpcd->Init.speed" is set to 3, while the only valid options here are 0 (USBD_SPEED_HIGH) and 1 (USBD_SPEED_FULL), so it ends up calling Error_Handler().
The problem is that the values in hpcd->Init.speed are set using the defines in "stm32f7xx_ll_usb.h", where you can see that value 3 corresponds to "full speed" :
#define USB_OTG_SPEED_HIGH 0U
#define USB_OTG_SPEED_HIGH_IN_FULL 1U
#define USB_OTG_SPEED_FULL 3UWhile the variable is compared to values as defined in "stm32f7xx_hal_pcd.h", where "full speed" has value 2 and 3 is not defined at all:
#define PCD_SPEED_HIGH 0U
#define PCD_SPEED_HIGH_IN_FULL 1U
#define PCD_SPEED_FULL 2UFinally in "usbd_def.h" it's again different and you can find this:
typedef enum
{
USBD_SPEED_HIGH = 0U,
USBD_SPEED_FULL = 1U,
USBD_SPEED_LOW = 2U,
}USBD_SpeedTypeDef;
This should be fixed by either getting rid of the different enumerations or at least properly matching them e.g.:
SPEED_HIGH = 0U;
SPEED_HIGH_IN_FULL = 1U;
SPEED_LOW = 2U;
SPEED_FULL = 3U;
Related forum posts with same issue on different targets:
https://community.st.com/s/question/0D50X0000AVU8zXSQT/cubemx-usb-bug
Please fix this in the next release of CubeMX/CubeIDE.