A toggle switch to call a function and then turn off the Arduino

Hello :slight_smile:

I would like to know if it's possible that if I press a toggle switch (to turn on/off the Arduino power), to first call a function in the sketch, such as "SaveBeforeShutDown()", and only turn off the Arduino one second after to let the function enough time to finish, or better if possible, turn off immediately when the function has exited.

It must be possible, but how?

You'll need external hardware to control the Power. The arduino board has no control over its power source.

Yes that's why I posted here and not in Programming :slight_smile:

What external hardware would be required?

You will need a switch to turn off the power. Something like this:

  if (button_pressed(power_off)) { //power off button pressed
    do_something();
    //wait(duration_1s); //wait for a second
    turn_power_off(); //turn off power
  }

The switch is turned off by a pin, activated by turn_power_off().

A more interesting case is to use one button to turn on / off to the mcu. Here, you need a switch (or a switch-able power source), and a self-locking mechanism (implemented in software).

A while ago somebody posted a solution which used a capacitor+diode on the power supply to keep the Arduino running for a moment after the power supply was disconnected, and monitored the supply voltage upstream of the cap so that it had advance warning when the power supply was about to fail. It only ran on for a moment, but that was apparently long enough to save its state to EEPROM so that it could be reloadedwhen the power supply was restored.

This was the first thing that came to my mind when I read the subject. :slight_smile:

There are plenty of cases where you want a machine to perform certain tasks and then turn itself off: a coffee maker, an oven, a washer, etc.

dhenry:
There are plenty of cases where you want a machine to perform certain tasks and then turn itself off: a coffee maker, an oven, a washer, etc.

My example has 8 channels and uses an ATMega8 to boot! :slight_smile:

guix:
Yes that's why I posted here and not in Programming :slight_smile:

What external hardware would be required?

Could be as simple as using a single coil 5vdc latching relay to allow a sketch to turn off it's power source.

http://img25.imageshack.us/img25/563/08miq7.jpg