The only universally reliable way of detecting when the USB host is attached and powered or not is to sense the voltage level on the VBUS pin of the USB connector (ex: typically B, Mini-B or Micro-B for non-OTG USB device applications). If the VBUS pin of the USB connector has been connected to the VBUS pin of the microcontroller (and doesn’t go to any other pins, either directly or through a resistor divider), then the only way for the firmware to directly sense the voltage is to look at the values of the USB OTG VBUS comparators (namely the U1OTGSTAT<SESVD> comparator which has a suitable threshold for host VBUS boolean presence detection). These comparators are documented as being host or OTG only features but they are enabled in the hardware and generate valid output values in USB device application as well, whenever:
- The USB module is enabled (ex: U1PWRC<USBPWR> is set).
- The USB module is not suspended.
- A sufficiently long settling time (ex: a few milliseconds) has elapsed since the last transition from a USB module disabled or suspended state to a USB module enabled and active state.
Therefore, it might be possible to implement some kind of firmware that conceptually does something like this:
USB Detached State
Periodically enable the USB module, wait the required settling time, then poll the U1OTGSTAT<SESVD> bit. If it is set (implying VBUS is present, USB cable is attached, and the host is powered), then the firmware should transition to the USB attached state described below. If the SESVD bit is clear, the firmware should promptly disable the USB module altogether and resume using the USBID/RB5/CN27 pin normally.
USB Attached State
Keep the USB module enabled continuously and the USB stack running. Periodically check the U1OTGSTAT<SESVD> bit or enable and use the associated SESVDIF interrupt flag. If after a suitable settling time has elapsed since enabling the USB module (or transitioning from a suspended to active state) and the SESVD is detected as 0, then this means the USB cable has been unplugged (or the USB host fully powered itself down). In this case, the firmware should fully disable the USB module and transition back to the USB detached state.