Skip to main content
Visitor II
June 18, 2020
Question

How to tell when USB has connected to Host?

  • June 18, 2020
  • 2 replies
  • 777 views

When my code  (STM32F303VC) starts up, it initializes the USB as a peripheral device. At this point the USB has not completed its connection with the Host. The Host still has to recognize the USB device and connect to it. If I try to communicate with the Host before it is connected, this causes problems.

I have found that if I add a 500 msec delay after initializing, my device is connected to the host. This method does not seem like a good idea, because it is dependent on timing for my Host computer, which is not necessarily the same as another Host computer.

Where in the code can I determine that the Host has completed its connection? I tried adding a flag that is set the first time CDC_Control_FS() is called. This is called about 340 msecs after initialization. But this does not seem to work reliably to signal the Host is ready.

What is the best way to determine that the Host has connected to my peripheral and is ready to receive data?

    This topic has been closed for replies.

    2 replies

    Super User
    June 18, 2020

    Look at pdev->pClassData. If it's NULL, initialization hasn't happened yet. Make sure it's initialized to NULL on startup, not sure if it is by default. This gets done in USBD_CDC_Init.

    Super User
    June 19, 2020

    > What is the best way to determine that the Host has connected to my peripheral and is ready to receive data?

    The host is ready to receive when it sends you IN request on the appropriate endpoint.

    Consider that this may never happen, for example when you're connected to USB charger.

    -- pa