-
-
Save idreamsi/a71302d81e3b470eb0f73ed79508ea9d to your computer and use it in GitHub Desktop.
Arduino EEPROM Read-Write Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/****************************************************** | |
Arduino EEPROM Read-Write Test | |
by Ted Hayes 2012 | |
[email protected] | |
Demonstrates the usage of the EEPROM Library for checking the state of a single value, | |
changing it, and resetting it. To use: | |
1) Put a momentary switch between ground and pin 11 on your Arduino. | |
2) Upload this program to it. | |
3) Open the serial monitor | |
4) You should see: | |
Starting; current EEPROM value is 0 | |
EEPROM byte not set yet; Writing... | |
Done. | |
5) Now press the reset button on your Arduino and keep the serial monitor open. | |
You should see: | |
Starting; current EEPROM value is 1 | |
EEPROM byte was set! | |
Done. | |
6) Press your momentary switch, and you should see: | |
Resetting EEPROM value | |
7) Now press the reset button one more time, and you should see: | |
Starting; current EEPROM value is 0 | |
EEPROM byte not set yet; Writing... | |
Done. | |
That's it! Remember that the EEPROM on ATmega chips has a specified life of 100,000 | |
write/erase cycles, so be careful about putting writes/erases in loops, etc.. | |
******************************************************/ | |
#include <EEPROM.h> | |
#define PIN_SWITCH 11 | |
int lastSwitch = HIGH; | |
boolean didReset = false; | |
void setup(){ | |
Serial.begin(9600); | |
pinMode(PIN_SWITCH, INPUT); | |
digitalWrite(PIN_SWITCH, HIGH); // set internal pull-up resistor | |
int val = EEPROM.read(0); | |
Serial.print("Starting; current EEPROM value is "); | |
Serial.println(val); | |
if(val != 1){ | |
Serial.println("EEPROM byte not set yet; Writing..."); | |
EEPROM.write(0, 1); | |
} else if (val == 1){ | |
Serial.println("EEPROM byte was set!"); | |
} | |
Serial.println("Done."); | |
} | |
void loop(){ | |
int currentSwitch = digitalRead(PIN_SWITCH); | |
if(currentSwitch == LOW && lastSwitch != currentSwitch && !didReset){ | |
// switch has changed state | |
// didReset is a simple form of debouncing, which prevents | |
// this from being run too many times | |
Serial.println("Resetting EEPROM value"); | |
EEPROM.write(0, 0); | |
didReset = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment