I wanted to save wifi credentials from an input. I recieve ssid and password as input, save them in namespace and I can recall them both with "print". But on restart i can only recall the ssid but not the password and instead a blank is printed.
void setup()
{
preferences1.begin("ssdcreden", false); //space for saving credentials
preferences2.begin("passcred", false); //space for saving credentials
if (before restart){
setuppage();}
if (after restart){
initialize();}
}
unless the string created inside the function is created on the heap or declared static, it is pretty much temporary, as it gets destroyed when function exits, and it exits at the end of expression
it may well be saved permanently on ESP32 but the library doesn’t give you the reference to that string it gives you copy that expires at the end of expression, and you take a pointer to that copy.
will have undefined results as you are taking the address of the dynamically-created character buffer belonging to the temporary String object. After that statement executes, the temporary String object will be deleted and your pointer will be left pointing to freed memory. Thus, dereferencing it will have undefined results.
It also appears that you're not doing an exception handling (as required by good programming practices) in case getString() does not find the specified key. That can make your application unreliable.
They have an example for network credentials, which demonstrates
how the return value of getString() needs to be assigned to a String.
some basic error checking on the returned String. If you look at the library source code you will see that if the key is not found, or if there is nothing stored at the key an empty String is returned by getString().
#include <Preferences.h>
#include "WiFi.h"
Preferences preferences;
String ssid;
String password;
void setup() {
Serial.begin(115200);
Serial.println();
preferences.begin("credentials", false);
ssid = preferences.getString("ssid", "");
password = preferences.getString("password", "");
if (ssid == "" || password == ""){
Serial.println("No values saved for ssid or password");
}
else {
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), password.c_str());
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
}
void loop() {
// put your main code here, to run repeatedly:
}