I had a similar obstacle recently on a project that uses a microcontroller (ATTiny84
in fact) to detect the loss of mains power and switch over to a rechargeable cell seamlessly.
I used a dedicated IC that takes two independent voltage sources (one primary and one backup) and outputs 3.6 - 5 V for the microcontroller to run from. It also has single digital output that indicates which of the two input supplies is being used.
The part I used is a Texas Instruments TPS2114. It is extremely simple to use and even allows you to set an output current limit by choosing an appropriate resistor.
My mains supply was converted down by first using a generic 10 V DC wall adapter and then that was regulated down to 5 V using a jelly-bean regulator like a generic 1117-5V
. This was used as the Primary 5 V supply. So when the mains power was available, the system just runs from the mains.
When the mains power was lost, the TPS2114
IC sees the primary supply dipping down below the voltage of the secondary supply (in this case a 4.2 V Li-Ion cell). The TPS2114
switches over to the cell and the microcontroller detects the changeover using the digital signal provided.
When mains power is restored all of that happens in reverse. At no point does the microcontroller suffer any ill effects and there is no brown-out or glitch on it's VCC rail. All that happens is that the 5 V quickly (but smoothly) falls to 4.1 V or so which is the cell voltage at the time.
There's nothing special about the TPS2114
particularly, there are many similar chips that might suit your purpose better. This one just happened to be ideal for me. (Apart from the fact that it's tiny and hard to solder!).
The other nice thing about this method is that I didn't need to have a Li-Ion cell charging circuit. When the system runs from mains, I can just yank the cell, replace it with a freshly recharged one, without the system being interrupted.