5.2 Detection of Universal Serial Bus (USB) Attach or Detach

If the device can be powered either using the Universal Serial Bus (USB) or battery having lower voltage than USB, the HLVD module could be periodically enabled to detect USB attach or detach. An attach would indicate a high-voltage detect from 3.3V (battery voltage) to 5V (the voltage on USB) and vice versa for a detach. This feature could save few extra components for a design and an attach signal (input pin). HLVDSEL=b'1011' provides a trip point of 4V. Thus, to detect if USB is attached, the INTH bit can be set while to detect the USB detach, INTL bit will be set. The timing diagram is shown in Figure 5-4:

Figure 5-4. Timing Diagram USB Attach Detach
  • After the device is powered up for the very first time, set both INTH and INTL bits. Also, enable the HLVD module. (event t1 in the timing diagram above).
  • After the HLVD module is ready, it will generate an interrupt (t2). In the ISR, monitor the OUT bit status to determine whether the microcontroller is powered with USB or battery. If the microcontroller is powered with a 3.3V battery, then the supply voltage is below the trip point (i.e., 4V) so the OUT bit would have been set.
  • The INTH bit should be kept set to detect USB attach and the INTL bit should be cleared (t3).
  • When the USB is attached, the supply voltage (5V) is above the trip point (e.g., 4V) so the OUT bit will be cleared and the HLVD module will generate an interrupt for INTH (t4).
  • In the ISR, the INTL bit should be set and INTH should be cleared to detect the USB detach (t5).
  • When USB is detached (t6), the supply voltage (3.3V) is below the trip point (i.e., 4V) so the OUT bit will be set and the HLVD module will generate an interrupt for INTL (t6).
  • In the ISR, the INTH bit should be set to detect the next USB attach (t7) event.

The HLVD configuration in MCC for the detection of USB attach detach is shown in Figure 5-5:

Figure 5-5. HLVD Configuration in MCC for USB Attach or Detach Detection
After the first power-on and first HLVD interrupt, check the status of the HLVD OUT bit using MCC generated API HLVD_OutputStatusGet (). If the OUT bit is set, the USB is detached, and the device is powered using the battery. Clear the INTL bit and keep the INTH bit set using HLVD_TripPointSetup API (bool Negative_Trip, bool Positive_Trip, HLVD_TRIP_POINTS trip_points). Use the same HLVD_TripPointSetup API for setting either the INTH or INTL bits to detect USB attach and detach events, subsequently.
Note: The code example for the usage of the HLVD module can be found at the following page: https://mplabxpress.microchip.com/mplabcloud/example.