| 1 |
/*** |
| 2 |
EEPROM Update method |
| 3 |
|
| 4 |
Stores values read from analog input 0 into the EEPROM. |
| 5 |
These values will stay in the EEPROM when the board is |
| 6 |
turned off and may be retrieved later by another sketch. |
| 7 |
|
| 8 |
If a value has not changed in the EEPROM, it is not overwritten |
| 9 |
which would reduce the life span of the EEPROM unnecessarily. |
| 10 |
|
| 11 |
Released using MIT licence. |
| 12 |
***/ |
| 13 |
|
| 14 |
#include <EEPROM.h> |
| 15 |
|
| 16 |
/** the current address in the EEPROM (i.e. which byte we're going to write to next) **/ |
| 17 |
int address = 0; |
| 18 |
|
| 19 |
void setup() { |
| 20 |
/** Empty setup **/ |
| 21 |
} |
| 22 |
|
| 23 |
void loop() { |
| 24 |
/*** |
| 25 |
need to divide by 4 because analog inputs range from |
| 26 |
0 to 1023 and each byte of the EEPROM can only hold a |
| 27 |
value from 0 to 255. |
| 28 |
***/ |
| 29 |
int val = analogRead(0) / 4; |
| 30 |
|
| 31 |
/*** |
| 32 |
Update the particular EEPROM cell. |
| 33 |
these values will remain there when the board is |
| 34 |
turned off. |
| 35 |
***/ |
| 36 |
EEPROM.update(address, val); |
| 37 |
|
| 38 |
/*** |
| 39 |
The function EEPROM.update(address, val) is equivalent to the following: |
| 40 |
|
| 41 |
if( EEPROM.read(address) != val ){ |
| 42 |
EEPROM.write(address, val); |
| 43 |
} |
| 44 |
***/ |
| 45 |
|
| 46 |
|
| 47 |
/*** |
| 48 |
Advance to the next address, when at the end restart at the beginning. |
| 49 |
|
| 50 |
Larger AVR processors have larger EEPROM sizes, E.g: |
| 51 |
- Arduino Duemilanove: 512 B EEPROM storage. |
| 52 |
- Arduino Uno: 1 kB EEPROM storage. |
| 53 |
- Arduino Mega: 4 kB EEPROM storage. |
| 54 |
|
| 55 |
Rather than hard-coding the length, you should use the pre-provided length function. |
| 56 |
This will make your code portable to all AVR processors. |
| 57 |
***/ |
| 58 |
address = address + 1; |
| 59 |
if (address == EEPROM.length()) { |
| 60 |
address = 0; |
| 61 |
} |
| 62 |
|
| 63 |
/*** |
| 64 |
As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an |
| 65 |
EEPROM address is also doable by a bitwise and of the length - 1. |
| 66 |
|
| 67 |
++address &= EEPROM.length() - 1; |
| 68 |
***/ |
| 69 |
|
| 70 |
delay(100); |
| 71 |
} |