Arduino Nano automatically switch between usb or battery

Hi All,

I am doing a school project that requires the use of Arduino Nano.
I need to make a really tiny GPS tracker.
The plan is when outside use a battery to power the circuit and have a Refresh Rate every 2 seconds,
When inside get refresh rate up to 20 seconds.
Now my problem is: how can I detect if Arduino is also powered via USB? because if I'm able to detect it I can plug into USB and charge the battery meanwhile Arduino automatically detects USB power and switch refresh every 20sec or if no USB detected back to 2 seconds.

any suggestions are welcome.

Thanks

Riccardo

The Nano has a back flow prevention Schottky diode in series with USB so the voltage at the 5V pin is only about 4.75V, if you're powering through the 5V or Vin pin the voltage will be (of course) 5V. If you use a voltage divider to lower the voltage from the 5V pin to 1V, then use the internal 1.1 volt analog reference you can read the 5V pin with analogRead() and determine if it's 4.8 or 5V.