Electronic – STM32 USB: detecting connection and disconnection

stm32stm32f4usb

Using STM32F4 USB Mass Storage Controller example in Device Mode, how do you detect connections and disconnections with a host controller?

I tried polling the VBUS pin state yet it could be high from a wall adapter or high without any communication with the host.

Is there a register to check? I noticed DSTS (status I guess?) in the USB library structs but couldn't find its documentation nor any useful comments in the code.

Best Answer

You could detect the connection and disconnection from this file:

usbd_core.c

and the API for it is this

USBD_StatusTypeDef USBD_LL_DevConnected(USBD_HandleTypeDef  *pdev)
USBD_StatusTypeDef USBD_LL_DevDisconnected(USBD_HandleTypeDef  *pdev)

I am not sure about USB Mass Storage Class but in the CDC class, the 2 APIs above detect the USB connection and disconnection, maybe this helps

Things to note:

  • Connection > when the physical USB cable is plugged into the USB port
  • Disconnection > when the physical USB cable is unplugged from the USB port

I used STMCubeMX to generate the USB CDC class.