Skip to content

Commit 55ff892

Browse files
pilotakgeky
authored andcommitted
Saving struct example
1 parent 2be4faf commit 55ff892

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ EEPROM devices support much higher read/write cycles than flash based memory, at
99
More info on EEPROM can be found on wikipedia:
1010
https://en.wikipedia.org/wiki/EEPROM
1111

12+
## Basic example
13+
1214
``` cpp
1315
// Here's an example using a 24LC256 on a GR PEACH
1416
#include "mbed.h"
@@ -42,3 +44,58 @@ int main() {
4244
}
4345
```
4446
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

Comments
 (0)