storageesp32arduino-ideeeprom

How do I use Preferences.h library in iteration?


I am using an ESP32 WROOM 32D module in a project using Arduino IDE. I want to utilise NVS facility with the help of Preferences.h library that it provides, although the data that can come through user would be stored in different namespaces and those could be utilised later. I can easily create simple one two namespaces but for this I need to use iteration. I have been scratching my head over this, but to no luck. I saw over on GitHub one person complain that it may not exactly be iteration friendly. Here's my code:

#include<Preferences.h>

Preferences ok;
String data1;
byte data2[2];byte data3[9];
byte buff[2];byte buf[9];
bool data4;

void setup() {
  Serial.begin(115200);
  
  for(int i=2; i<280; i++){
    char testarray[]="test1";
    testarray[4]=i;
    ok.begin(testarray,false);
    char datad1[20]="Code 15 launched 20";
    datad1[15]=i;
    ok.putString("data1", datad1);
    ok.putBytes("data2","2",2);
    ok.putBytes("data3","DF1BE29C",9);
    ok.putBool("data4", true);
    ok.end();
  }
  for(int i=2; i<280; i++){
    char testarray[]="test1";
    testarray[4]=i;
    ok.begin(testarray,false);
    data1=ok.getString("data1");
    Serial.println(data1);
    data2[2]=ok.getBytes("data2",buff,2);
    Serial.print(data2[1], HEX);
    Serial.print(data2[2], HEX);
    Serial.println();
    data3[9]=ok.getBytes("data3",buf,9);
    for (int j = 0; j < sizeof(data3); j++) {
        Serial.print(data3[j], HEX);
    }
    Serial.println();
    data4=ok.getBool("data4");
    Serial.println(data4);
    ok.end();
  }
}

void loop() {
  
}

Is there anything wrong with this? The format is simply const char* as the parameter of the namespace name, I just hoped that this would efficiently create test1, test2, test3, test4 namespaces.... but doesn't seem much feasible. Any guidance will be appreciated.


Solution

  • You cannot construct C strings like that:

        char testarray[]="test1";
        testarray[4]=i;
    ...
        char datad1[20]="Code 15 launched 20";
        datad1[15]=i;
    

    This simply replaces the character '1' with numeric value 2, 3, .. 280. Numbers are not characters.

    This is how you construct C strings with numbers in them:

    char label[8]; // 4 chars for "test", 3 chars for 3 digit number, 1 char for NULL
    snprintf(label, sizeof(label), "test%d", i);