Dynamically assigning Preferences name gives problems when reading back

kian79
Posts: 30
Joined: Thu Jun 13, 2019 3:27 am

Dynamically assigning Preferences name gives problems when reading back

Postby kian79 » Sun Apr 16, 2023 6:07 am

Hi all,

I am having a very weird problem trying to get Preferences.getBytes to work. My key names are labelled as "001", "002", "003" ... up to "200" and I am using a character array(char myKey[3] - declared as a global variable) to dynamically assign the key names. And I have written a simple function that takes in an integer and converts it to the correct character array format. For example:

when I call the function convertCharArray(2), it sets myKey[0] ='0', myKey[1]='0' and myKey[2]='2'

Writing into the preference file looks something like this:
convertCharArray(2);
preferences.putBytes(myKey, myData, 6);


And this works perfectly fine.

However, when I try to read back the data using the following, it doesn't work:
convertCharArray(2);
preferences.getBytes(myKey, myData, 6);


The preferences.getByes function should return back 6 but it returns back 0. If I were to provide a constant string into the preferences.getBytes function, then everything works fine:
preferences.getBytes("002", myData, 6);

The preferences.getBytes function has the following function prototype:
size_t getBytes(const char* key, void * buf, size_t len);

The key name is a const char* I wonder if I did anything wrong. But writing works! Just not reading back.

Hope someone can advise. Thanks in advance!

lbernstone
Posts: 826
Joined: Mon Jul 22, 2019 3:20 pm

Re: Dynamically assigning Preferences name gives problems when reading back

Postby lbernstone » Sun Apr 16, 2023 6:24 pm

Nobody is going to be able to debug code that you don't include. If you are just fishing for someone to do your homework, here you go.

Code: Select all

#include <Preferences.h>
Preferences prefs;

void setup() {
  Serial.begin(115200);
  prefs.begin("sequence");
  for (int x=0; x<50; x++) {
    char num1[6];
    snprintf(num1, 6, "%05d", x);
    prefs.putBytes(String(x).c_str(), num1, 6);
  }
}

void loop() {
  char randtxt[6];
  int randseq = random(50);
  prefs.getBytes(String(randseq).c_str(), randtxt, 6); 
  Serial.printf("seq: %d\ttxt: %s\n", randseq, randtxt);
  delay(5000);
}

Who is online

Users browsing this forum: No registered users and 34 guests