Automatically switching power supply detection

Hi all,

Is it possible to detect if the power supply has been changed from USB to vin? or vin to USB? or a 1 vin source to another vin source (possibly though the use of relays and the use of digital pins to detect voltage)?

I'm looking to make sure that upon the removal of the main power supply, any data that is being written to SD card can be finalised and closed. Then the Arduino goes into sleep mode until the main power is restored (a few hours later). When the main power is restored it will also top up the rechargeable lipo

What would be the best way to go about doing this?

The bit which has pretty much got me stumped is the detection of the power change over.

It's worth noting that I plan to have the main power as a 9-12v and the 'backup' as 1S lipo (3.7v)


The best I can do is say "Not going to happen" as you have explained it. You need to have a system with a single power source. Then you need to include the ability for your system to not only write the last record, which will likely be just added to the SD card file buffer, but you must "close" the file so that last buffer is written and the SD card file information is updated and rewritten.
Generally people design a system with a battery that runs the system and is being recharged while external power is available. When not available, the system continued to run using the battery.
Good luck,

This might be of interest

talking about EEPROM, but something similar might give you time for the dying declaration to be saved.


I'm wondering if I could use feed from the main power to a digital pin to keep it high.

Once the power is removed it goes low, the battery takes over and the program says ok, time to save what I'm doing and go to sleep for a while.

Saying that maybe better to use an analog pin with a cap, as per 777s post, to detect if ADC is below a certain value then the program finishes up.

There must be a way, there is aways a way.

If you used a potential divider, then you could do this. You don't want to feed main power directly to a digital pin as you will exceed the manufacturers spec for the max voltage on a pin (Vcc + 0.5V) and damage/destroy the chip.

1 Like

That’s not exactly what the circuit in the thread I linked is doing.

The capacitor holds enough power to run the Arduino. See it attached at the power input to the Arduino.

Meanwhile a voltage divider on an analog input pin is used to see the sagging supply voltage and react.

The diode keeps the capacitor from powering the rest of the circuitry.


Apologies, you're right. I was referring to another thread and got mixed up.
There are a few threads on here asking similar questions.