ESP32 preferens.h get char

Hello. I'm using the Preferences.h library and I want to store and read arrays. Please help me with this, I did not find the right answer on the Internet.

For example:

char* ssid;

The putString and getString methods work with character array pointers as well as Strings.

size_t putString(const char* key, const char* value);
size_t putString(const char* key, String value);

size_t getString(const char* key, char* value, size_t maxLen);
String getString(const char* key, String defaultValue = String());

You can also use the putBytes and getBytes methods with character arrays.

There is not an issue with using the String class on the ESP32 and its more simple to use them to work with dynamic allocation of the char* for the retrieved value.

#include <Preferences.h>
Preferences prefs;

String MyEmail    = "myEmail@myProvider.com";
String MyPassWord = "thereisnopassword";
String MySecret   = "NUX007";

String MyEmailR    = "";
String MyPassWordR = "";
String MySecretR   = "";


void setup() {
  Serial.begin(115200);
  prefs.begin("Settings"); //namespace
  
  //key/value pairs within namespace
  prefs.putString("MyEmail", MyEmail);
  prefs.putString("MyPassWord", MyPassWord);
  prefs.putString("MySecret", MySecret);

  MyEmailR = prefs.getString("MyEmail");
  Serial.println(MyEmailR);
  MyPassWordR = prefs.getString("MyPassWord");
  Serial.println(MyPassWordR);
  MySecretR = prefs.getString("MySecret");
  Serial.println(MySecretR);
}

void loop() {}

Sorry. I don't quite understand how to use your methods.

I have an array structure in my code.

struct config_wifi_mqtt_struct {
  char* ssid;
  char* pass;
  bool DHCP;
  char* ip;
  char* gt;
  char* mac;
  char* dns;

  char* ip_mqtt;
  int port_mqtt;
  char* lg_mqtt;
  char* ps_mqtt;
};

I want to save and write values ​​from it

!!!But I really need to use the minimum amount of RAM!!!

it is not an array, it just a pointer to it. You need create array itself before you can store values to it.

You can either use a static array with fixed size:

char ssid[32] = "My SSID";

or use dynamic memory allocation with new() or malloc()

Dynamic memory must be used with care to avoid leaks. If you are not experienced enough, it is better to use fixed-size arrays, otherwise memory leaks will negate all the advantages of dynamism.

In any case, I would recommend learning the basics of C ++ regarding arrays, pointers and references, you do not have enough knowledge for such a project

As far as I can see, your problem is the same as in the question about the kernel panic - you do not know how to allocate and free memory for your variables. Using preferences.h will not solve this problem for you.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.