Skip to content

How do I save and read array values with preferences? #2497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
xman4242 opened this issue Feb 24, 2019 · 7 comments
Closed

How do I save and read array values with preferences? #2497

xman4242 opened this issue Feb 24, 2019 · 7 comments

Comments

@xman4242
Copy link

I would like to understand how to use this library to write arrays to the memory and to read them.
I am using this library with a Heltec WifiKit 32.
I found this thread, however, I am still struggling to understand.
#611
Thanks,
xman4242

@boarchuz
Copy link
Contributor

If you just want to save and load the whole array, you can simply putbytes("myArray", &myArray, sizeof(myArray));

@lbernstone
Copy link
Contributor

This will require the the modification I just submitted, but shows how to cast data into a struct array.

#include <Preferences.h>
Preferences prefs;

typedef struct {
  uint8_t hour;
  uint8_t minute;
  uint8_t setting1;
  uint8_t setting2;
} schedule_t;

void setup() {
  Serial.begin(115200);
  prefs.begin("schedule");
  uint8_t content[] = {9, 30, 235, 255, 20, 15, 0, 0};
  prefs.putBytes("schedule", content, 8);
  size_t schLen = prefs.getBytes("schedule", NULL, NULL);
  char buffer[schLen];
  prefs.getBytes("schedule", buffer, schLen);
  if (schLen % sizeof(schedule_t)) {
    log_e("Data is not correct size!");
    return;
  }
  schedule_t *schedule = (schedule_t *) buffer;
  Serial.printf("%02d:%02d %d/%d\n", 
    schedule[1].hour, schedule[1].minute,
    schedule[1].setting1, schedule[1].setting2);
  prefs.putBytes("schedule", schedule, sizeof(schedule));
  buffer[0] = 0;
  prefs.getBytes("schedule", buffer, schLen);
  for (int x=0; x<8; x++) Serial.printf("%02X ", buffer[x]);
  Serial.println(); 
}

void loop() {}

@xman4242
Copy link
Author

Thank you all. I think I have it figured out now!

@lbernstone
Copy link
Contributor

Please close the issue

@xman4242
Copy link
Author

My apologies. It is closed now.

@guilhermeaiolfi
Copy link

How that would look like for an array of Booleans? Because if I have an array of 10 items, that would make the second byte to be all messed up.

@bastian2001
Copy link

@guilhermeaiolfi booleans are stored as complete bytes (chars or unsigned chars, idk exactly). If you need to store hundreds of booleans, you could squish them down to bits but otherwise I'd say just store the whole bytes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants