@@ -9,6 +9,8 @@ EEPROM devices support much higher read/write cycles than flash based memory, at
9
9
More info on EEPROM can be found on wikipedia:
10
10
https://en.wikipedia.org/wiki/EEPROM
11
11
12
+ ## Basic example
13
+
12
14
``` cpp
13
15
// Here's an example using a 24LC256 on a GR PEACH
14
16
#include " mbed.h"
@@ -42,3 +44,58 @@ int main() {
42
44
}
43
45
```
44
46
47
+ ## Saving struct example
48
+ ``` cpp
49
+ // Here's an example using a 24LC256 to store a C struct
50
+ #include "mbed.h"
51
+ #include "I2CEEBlockDevice.h"
52
+
53
+ #define BLOCK_SIZE 32
54
+
55
+ // Create EEPROM device on I2C bus with 32kbytes of memory
56
+ I2CEEBlockDevice i2cee(P0_0, P0_1, 0xA0, 32*1024, BLOCK_SIZE);
57
+
58
+ uint8_t setting_block_size;
59
+
60
+ struct t_setting {
61
+ uint8_t version;
62
+ char name[20];
63
+ } setting = {
64
+ 1,
65
+ "Hello World!"
66
+ };
67
+
68
+ int main() {
69
+ printf("i2cee struct test\n");
70
+
71
+ // No. of bytes to be stored, but topped up to be multiplied by block size
72
+ unsigned int setting_block_size = ceil(sizeof(setting)/(double)BLOCK_SIZE)*BLOCK_SIZE;
73
+
74
+ // Temporary buffer
75
+ char *buffer = (char*)malloc(setting_block_size);
76
+
77
+ // Initialize the device
78
+ i2cee.init();
79
+
80
+ // Save struct to EEPROM
81
+ printf("\nSaving struct version: %u, name: %s\n", setting.version, setting.name);
82
+ memcpy(buffer, &setting, sizeof(setting));
83
+ i2cee.program(buffer, 0, setting_block_size);
84
+
85
+ // Get back what was stored
86
+ t_setting tmp; //Re-make the struct
87
+ memset(buffer, 0, sizeof(buffer)); // empty buffer, not nessesary but helps when debugging
88
+
89
+ if (i2cee.read(buffer, 0, setting_block_size ) == 0){ // get data into buffer
90
+ // Convert what we read into struct
91
+ memcpy(&tmp, buffer, sizeof(tmp)); // copy only size of struct not setting_block_size
92
+ printf("\nTemporary struct version: %u, name: %s\n", tmp.version, tmp.name);
93
+ } else {
94
+ printf("Error when reading\n");
95
+ }
96
+
97
+ // Deinitialize the device
98
+ i2cee.deinit();
99
+ }
100
+ ```
101
+
0 commit comments