Detect Unplugging of USB Cable in Firmware

Version 1
    Question: How can we perform unplug detection in firmware?



    This can be done by monitoring the SOF interrupts. SOFs are sent from the host to the device at the beginning of every frame,(microframe for a highspeed device). The FX2LP core will generate SOFs on its own when it detects missing or garbled SOFs. To prevent this set the NOSYNSOF bit in the USBCS register. Setting this bit will prevent the core from synthesizing the missing frames.

    Also, enable the SOF interrupt in the USBIE register.

    In your Td_Init routine set up and initialize a variable to zero . Increment this variable by 1 in your Td_Poll().

    Hence everytime the Td_Poll() function is executed, this variable will be incremented by one.

    In your SOF interrupt routine, reset this variable to Zero.

    void ISR_Sof(void) interrupt 0
    NoFrame=0; //Reset the variable that is getting incremented in TD_Poll()
    USBIRQ = bmSOF; // Clear SOF IRQ

    In this way, TD_Poll wil keep on trying to increment the variable and the SOF interrupt will reset it every microframe.
    When we unplug the USB cable, FX2LP will neither receive any more SOFs from the host nor generate SOFs internally as we have set the NOSYNSOF bit in USBCS to 1.

    This way the variable will keep on getting incremented as no SOF interrupt will be triggered to reset it.

    You can check in the TD_Poll loop whether the variable has reached a particular value. When it does, you can confirm that the device has been unplugged.
    void TD_Poll(void) // Called repeatedly while the device is idle
    WORD i;
    WORD count;

    If (NoFrame < 0xFFFF) //so that the variable does not overflow.
    {NoFrame = NoFrame + 0x01;

    if(NoFrame > 16)
    PC0=1; // set GPIO PC0 high

    Here, when TD_Poll gets executed 16 times without the variable NoFrame getting reset by the SOF interrupt routine, we set the GPIO pin high. One disadvantage of this method is that since we have set the NOSYNSOF bit in the USBCS register, the core will not generate SOFs on its own if it finds missing or garbled SOF packets.