Wed Jan 09, 2013 11:53 am
I would use a small NiCd or Lead-Acid rechargeable battery, trickle-charging when the power is on. If NiCd, the capacity must be 500mA * 10 = 5000mAh or larger.
Charge the battery with a constant voltage (for Lead-Acid) or current of capacity/10 mA (for NiCd) while the power is on (of course). Supply at least 500mA, so the Pi will be able to run and not discharge the battery faster than it is being charged.
(NiCd batteries can be charged constantly using a current of no more than capacity/10. Any more than that and you risk damaging the battery.)
Then power the Pi from the battery through a (variable input range) DC-DC converter and then two relays in parallel.
One relay is switched by the mains power.
One relay is switched by a GPIO output.
When the Pi boots it switches on that GPIO. Now even if the mains power is switched off, the Pi is still connected to the battery.
The mains relay also switches on a GPIO input.
A process in the Pi runs every second to detect the mains power going away.
When the mains power is switched off, the process halts the Pi.
As the final action of the halt, the GPIO output is cleared, and the second relay opens, switching the Pi off.
This reminds me of an old friend who in each toilet in the house, had a big old radio, a car battery, and a microswitch attached to the toilet lid. While the lid was lifted, Radio 2 played.