There are times when your program needs to react to your device being turned off, for example to save the current state of an Arduino sketch to EEPROM before shutting down, or to disengage relays in a power module to ensure there is a clean shutdown.
Usually, the power loss detector is designed as part of the power supply, so here I’ve put together an example power supply that we can study, note that this is not intended as an exemplar of power supply design, and is rather incomplete, but to serve as a crude model that we can study to see how to detect power loss.
In the circuit above, the DC input is simulated using V1 (with Label Vin) which has a steady voltage for 6 seconds, after which the voltage drops to 0V, simulating the power turning off.
When the voltage at Vin is at 9V, the NPN transistor Q1 is fully on, this drops the whole voltage across R3 and means that V_FAIL will be low. In the mean time our (somewhat incomplete and makeshift) regulator R2, D4, Q2 delivers around 5V to our logic boards.
However, when Vin drops to 0V, the NPN transistor Q1 pretty much immediately switches off, leaving almost the entire Vcc at V_FAIL, so it is essentially HIGH. The diode D2 stops C1 from keeping Q1 turned on.
In the mean time, C1 being quite a large capacitor will stay charged long enough for the micro-controller (simulated as R4 in the circuit) to shutdown safely.
Take a look at the example simulation graphs below from LTSpice.
In the graph above we see that while Vin is at 9V, V_FAIL is LOW. However, as soon as Vin drops off, V_FAIL almost immediately goes HIGH. We then get a short amount of time to run our shutdown code.
We must act on V_FAIL going HIGH as quickly as possible, therefore, we need to either attach it to an interrupt pin, or check and act on its value very frequently.