1
+ /* **
2
+ Using the EEMEM data attribute.
3
+ Written By: Christopher Andrews
4
+
5
+ Released using MIT licence.
6
+ ***/
7
+
8
+ #include < EEPROM.h>
9
+ #include < IPAddress.h>
10
+
11
+ /* **
12
+ EEMEM is an attribute that can be used with static or global
13
+ variable declarations.
14
+
15
+ What this does is tell the compiling system that the address for the
16
+ variable is to reside in the EEPROM memory space. It can also allow
17
+ assigning a default value, however the Arduino IDE has this particular
18
+ feature disabled.
19
+
20
+ Even though the address is located in the EEPROM, C++ does not know
21
+ the difference between memory spaces (RAM/Flash/EEPROM) and still needs
22
+ to be accessed as usual using the EEPROM library. The advantage however,
23
+ is the management of addressing. Your variables will not overlap from
24
+ faulty indexing, and other libraries using EEMEM will not interfere with
25
+ your application.
26
+ ***/
27
+
28
+ // Two global variables marked with EEMEM data attribute.
29
+ int value EEMEM;
30
+ float fraction EEMEM;
31
+
32
+
33
+ struct Configuration {
34
+ unsigned long ip;
35
+ unsigned int timesRun;
36
+ };
37
+
38
+ // An instance of a structure using EEMEM.
39
+ Configuration eeConfig EEMEM;
40
+
41
+
42
+ void setup () {
43
+
44
+ Serial.begin (9600 );
45
+
46
+ // Wait for serial port to connect. Needed for Leonardo only.
47
+ while (!Serial) {}
48
+
49
+ /* **
50
+ Using the standard get() and put() EEPROM methods, all that is
51
+ needed is a temporary storage space. By taking the address of
52
+ your variable marked with EEMEM, you can easily retrieve its
53
+ contents.
54
+ ***/
55
+
56
+ // Read value from EEPROM using the address assigned automatically
57
+ // when the declaration is used with EEMEM.
58
+ int result = EEPROM.get (&value);
59
+
60
+ float frac = EEPROM.get (&fraction);
61
+
62
+ // Using the standard usage of EEPROM.put() allows you to write to a variable marked with EEMEM.
63
+ result = random (10 );
64
+ EEPROM.put (&value, result);
65
+
66
+ frac = 3 .14f ;
67
+ EEPROM.put (&fraction, frac);
68
+ EEPROM.put (&fraction, 3 .14f ); // You can also directly write literal values without needing temporary storage.
69
+
70
+ /* **
71
+ Using a structure with EEMEM.
72
+ ***/
73
+
74
+ IPAddress ip (192 , 168 , 1 , 1 );
75
+
76
+ // Save an IP Address. An IPAddress object can cast to a uint32_t
77
+ // or unsigned long. This gives a raw 4 byte value to save.
78
+ EEPROM.put (&eeConfig.ip , (unsigned long ) ip);
79
+
80
+ // Read the value and assign the result directly to the IPAddress
81
+ // object (It accepts unsigned long values as an input).
82
+ ip = EEPROM.get (&eeConfig.ip );
83
+
84
+ Serial.print (" IP address is: " );
85
+ Serial.println (ip);
86
+ }
87
+
88
+ void loop () {
89
+ /* * Empty Loop **/
90
+ }
0 commit comments