diff --git a/ports/stm32/usbd_conf.c b/ports/stm32/usbd_conf.c index da0e71a7e4..0c905e0dff 100644 --- a/ports/stm32/usbd_conf.c +++ b/ports/stm32/usbd_conf.c @@ -65,6 +65,30 @@ PCD_HandleTypeDef pcd_hs_handle; #define OTG_HS_IRQn USB1_OTG_HS_IRQn #endif +// Configure VBUS sensing for TinyUSB on STM32F4/F7. The DWC2 PHY init only +// sets the PWRDWN bit but doesn't configure VBUS sensing in the GCCFG register. +#if MICROPY_HW_TINYUSB_STACK && (defined(STM32F4) || defined(STM32F7)) +static inline void mp_usbd_configure_vbus_sensing(USB_OTG_GlobalTypeDef *USBx) { + #if defined(USB_OTG_GCCFG_VBDEN) + // Newer STM32F4/F7 with VBDEN register bit. + #if defined(MICROPY_HW_USB_VBUS_DETECT_PIN) + USBx->GCCFG |= USB_OTG_GCCFG_VBDEN; + #else + USBx->GCCFG &= ~USB_OTG_GCCFG_VBDEN; + #endif + #else + // Older STM32F4 with separate VBUSASEN/VBUSBSEN/NOVBUSSENS register bits. + #if defined(MICROPY_HW_USB_VBUS_DETECT_PIN) + USBx->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; + USBx->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; + #else + USBx->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; + USBx->GCCFG &= ~(USB_OTG_GCCFG_VBUSBSEN | USB_OTG_GCCFG_VBUSASEN); + #endif + #endif +} +#endif + #if MICROPY_HW_USB_FS static void mp_usbd_ll_init_fs(void) { { @@ -172,20 +196,8 @@ static void mp_usbd_ll_init_fs(void) { HAL_NVIC_EnableIRQ(OTG_FS_IRQn); #endif - #if MICROPY_HW_TINYUSB_STACK - // Configure VBUS sensing for TinyUSB on STM32F4/F7 which have separate GCCFG register - // The DWC2 PHY init only sets PWRDWN bit, but doesn't configure VBUS sensing - #if defined(STM32F4) || defined(STM32F7) - #if defined(MICROPY_HW_USB_VBUS_DETECT_PIN) - // Enable VBUS sensing in "B device" mode (using PA9) - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; - #else - // Force VBUS valid (no VBUS detect pin configured) - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG &= ~(USB_OTG_GCCFG_VBUSBSEN | USB_OTG_GCCFG_VBUSASEN); - #endif - #endif + #if MICROPY_HW_TINYUSB_STACK && (defined(STM32F4) || defined(STM32F7)) + mp_usbd_configure_vbus_sensing(USB_OTG_FS); #endif } } @@ -306,6 +318,10 @@ static void mp_usbd_ll_init_hs(void) { #endif + #if MICROPY_HW_TINYUSB_STACK && (defined(STM32F4) || defined(STM32F7)) + mp_usbd_configure_vbus_sensing(USB_OTG_HS); + #endif + #else // !MICROPY_HW_USB_HS_IN_FS // Configure USB HS GPIOs