Arduino save output last state and remember after power off
The output state of the circuits usually resets after a power off and the circuit needs to execute the same inputs or operations again in order to resume the previous state before the power off.
For circuits that need to resume their last state of the output even after the power is off, the Arduino EEPROM memory can be used. This function can be also used for similar applications which need to back up the values, last settings, etc, that need to be remembered on the next power ON.
Refer: Arduino EEPROM memory save and read data
In the circuit, switch 2 is for turning ON the output, and switch 3 is for turn off the load or output. The output pin 9 is connected to the signal pin of a 5V relay module to control or ON/OFF the load.
Refer: Relay module interface with Arduino
Arduino code
#include <EEPROM.h> const int switch_on = 2, switch_off = 3, output = 13; int address = 0; void setup() { pinMode(switch_on, INPUT); pinMode(switch_off, INPUT); pinMode(output, OUTPUT); char device_status = EEPROM.read(address); if (device_status == 'H') { digitalWrite(output, HIGH); } else { digitalWrite(output, LOW); } } void loop() { if (digitalRead(switch_on) == HIGH) { digitalWrite(output, HIGH); EEPROM.write(address, 'H'); } if (digitalRead(switch_off) == HIGH) { digitalWrite(output, LOW); EEPROM.write(address, 'L'); } }
When switch 2 is pressed the output switches to HIGH state and at the same time character ‘H’ will be stored to the EEPROM memory at address 0; indicates a high state. Similarly, pressing switch 3 turns the output to a low state and char ‘L’ is stored to the EEPROM memory address 0 replacing the ‘H’; which indicates a LOW state. So, the current state of the device will be stored in EEPROM memory during every ON or OFF operation.
Every time when the power is back after a power off, the code inside the void setup runs once. Inside the void setup, the char store in the EEPROM will be read and the output will be switched ON or OFF according to the char value stored for the corresponding last state; H for high and L for low. So the last state will be resumed during every power ON.