Sometimes we want to be able to turn off the Arduino without loosing all the data gathered from sensors or inputs. Maybe we have a game where the highscore needs to be stored or we want to know if a button was pressed the last time the Arduino was on.
For this purpose we can use the EEPROM (Electrically Erasable Programmable Read-Only Memory) on the Arduino. Data stored on the EEPROM is non-volatile so the EEPROM can hold its data when it has no power.
In this project I will use an Arduino Mega but it also works with any other Arduino. The code down below turns the internal LED on or off if a button is pressed. But every time the button is pressed, the state of the LED (0/1) is saved to the EEPROM. If the Arduino is turned off and on again the LED will be in the same state as before. So we have a way to know if the LED was on or off the last time the Arduino was on.
The Code:To use the EEPROM on the Arduino we first have to include the EEPROM library:
#include <EEPROM.h>
The functions we will need from this library are:
- EEPROM.read(address) This reads the value stored in the given address
- EEPROM.write(address, value) Stores a value between 0 and 255 into the given address
- EERPOM.update(address, value) Does the same as.write but only writes if the new value is not the same as the old
In the setup function pin10 is set as a INPUT_PULLUP so we don't have to use an external resistor for the button.
In the loop function the "button_pressed" variable is used to store the state of the button.
The first if-statement checks if the button is pressed and if the value stored in address 0 on the EEPROM is 0. If this is true the LED is currently off and we want to turn it on. So the value on the EEPROM at address 0 is changed to 1.
The second if-statement is true if the button is pressed and the LED is on. This means we want to turn off the LED. In this case we use the.update function although it is not necessary in this example. The.update function can help to save cycles on the EEPROM because it only writes if the new value is different from the old one. This is important because the EEPROM's have ca. 100'000 write/erase cycles.
After a delay the state of the LED is updated with
digitalWrite(LED_BUILTIN, EEPROM.read(0));
This is a very simple example on how to use the EEPROM on the Arduino. Of course we could also write to any other available address in the EEPROM (Arduino Uno: 0-1023; Arduino Mega: 0-4095; etc.). But don't forget that you can only store 8-Bit values so the value has to bee between 0-255.
Comments