How to detect the power source when multiple power sources are available?
One very simple way is to use diodes (use Schottky diodes for smaller voltage drops) for each power source, and have a pull-down resistor on the source side. You can then use an IO pin per supply source on your MCU to detect which is plugged in.

For example, say you have a 3V battery and 3.3V MCU. This circuit will reduce the 5V from the USB to an acceptable level for the IO pins.







simulate this circuit &ndash; Schematic created using CircuitLab