mirror of https://github.com/ARMmbed/mbed-os.git
Saving struct example
parent
2be4fafeb0
commit
55ff892f0c
57
README.md
57
README.md
|
|
@ -9,6 +9,8 @@ EEPROM devices support much higher read/write cycles than flash based memory, at
|
||||||
More info on EEPROM can be found on wikipedia:
|
More info on EEPROM can be found on wikipedia:
|
||||||
https://en.wikipedia.org/wiki/EEPROM
|
https://en.wikipedia.org/wiki/EEPROM
|
||||||
|
|
||||||
|
## Basic example
|
||||||
|
|
||||||
``` cpp
|
``` cpp
|
||||||
// Here's an example using a 24LC256 on a GR PEACH
|
// Here's an example using a 24LC256 on a GR PEACH
|
||||||
#include "mbed.h"
|
#include "mbed.h"
|
||||||
|
|
@ -42,3 +44,58 @@ int main() {
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Saving struct example
|
||||||
|
``` cpp
|
||||||
|
// Here's an example using a 24LC256 to store a C struct
|
||||||
|
#include "mbed.h"
|
||||||
|
#include "I2CEEBlockDevice.h"
|
||||||
|
|
||||||
|
#define BLOCK_SIZE 32
|
||||||
|
|
||||||
|
// Create EEPROM device on I2C bus with 32kbytes of memory
|
||||||
|
I2CEEBlockDevice i2cee(P0_0, P0_1, 0xA0, 32*1024, BLOCK_SIZE);
|
||||||
|
|
||||||
|
uint8_t setting_block_size;
|
||||||
|
|
||||||
|
struct t_setting {
|
||||||
|
uint8_t version;
|
||||||
|
char name[20];
|
||||||
|
} setting = {
|
||||||
|
1,
|
||||||
|
"Hello World!"
|
||||||
|
};
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
printf("i2cee struct test\n");
|
||||||
|
|
||||||
|
// No. of bytes to be stored, but topped up to be multiplied by block size
|
||||||
|
unsigned int setting_block_size = ceil(sizeof(setting)/(double)BLOCK_SIZE)*BLOCK_SIZE;
|
||||||
|
|
||||||
|
// Temporary buffer
|
||||||
|
char *buffer = (char*)malloc(setting_block_size);
|
||||||
|
|
||||||
|
// Initialize the device
|
||||||
|
i2cee.init();
|
||||||
|
|
||||||
|
// Save struct to EEPROM
|
||||||
|
printf("\nSaving struct version: %u, name: %s\n", setting.version, setting.name);
|
||||||
|
memcpy(buffer, &setting, sizeof(setting));
|
||||||
|
i2cee.program(buffer, 0, setting_block_size);
|
||||||
|
|
||||||
|
// Get back what was stored
|
||||||
|
t_setting tmp; //Re-make the struct
|
||||||
|
memset(buffer, 0, sizeof(buffer)); // empty buffer, not nessesary but helps when debugging
|
||||||
|
|
||||||
|
if (i2cee.read(buffer, 0, setting_block_size ) == 0){ // get data into buffer
|
||||||
|
// Convert what we read into struct
|
||||||
|
memcpy(&tmp, buffer, sizeof(tmp)); // copy only size of struct not setting_block_size
|
||||||
|
printf("\nTemporary struct version: %u, name: %s\n", tmp.version, tmp.name);
|
||||||
|
} else {
|
||||||
|
printf("Error when reading\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deinitialize the device
|
||||||
|
i2cee.deinit();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue