I'm trying to store at the EEPROM an SSID and PASSWORD value as strings and when i read them when i restart the esp put them at the WiFi.begin() function. When i hardcode them or pass them directly from const char* variables they work but when i retrieve a string from the eeprom and convert it into a const char* with the c_str() function it doesn't work.....
This is the code. The first time i get into the loop I type my password and hit enter.
Then i restart my ESP and even though this Serial.print(password.c_str()); correctly prints my password the WiFi.begin() ain't connecting.. When i hardcode my pass like this
Serial.begin("MY SSID","MY PASS") it works or when i assign the values directly to const char* variables and pass them into the function but it's not what i need for my project..
Thank you for your time guys.
If Serial.print(password.c_str()) correctly prints your password - it means that you store and read pass in the EEPROM correctly.
Therefore the error is elsewhere.
Are you sure that spaces are allowed in the SSID?
Daaaamn mate you are right i directly stored my pass into a string and then called it with the c_str() function and worked..
But do you have an alternative on how to store and read it in order to make it work?
Guys i thank you so much for your replies they were most appreciated.
The problem was th readString() function causi it saved the input as a String class and not as a string (as @jremington said) so i had to read from the Serial input char by char. SO finally for anyone that might be interested this is the working code. Again thank you!!
#include <WiFi.h>
#include <Preferences.h>
#include <nvs_flash.h>
Preferences preferences;
char* ssid = "pew - pew 2.4GHz";
String password;
char readByte;
void setup()
{
// Only when i need to erase NVS partition then comment again and reupload code
// nvs_flash_erase();
// nvs_flash_init();
Serial.begin(115200);
Serial.println();
preferences.begin("credentials", false);
// ssid = preferences.getString("ssid", "");
password = preferences.getString("password", "");
Serial.println("current pass");
Serial.println(password);
if (password.c_str() == "") {
Serial.println("No values saved for ssid or password");
} else {
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password.c_str());
Serial.print("Connecting to WiFi ..");
unsigned long currentMillis = millis();
while (WiFi.status() != WL_CONNECTED && millis() - currentMillis < 15000) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
preferences.end();
password = "";
}
void loop() {
while (Serial.available() > 0) {
readByte = Serial.read();
if (readByte != '\n') {
password += readByte;
} else {
Serial.println("le pass");
preferences.begin("credentials", false);
preferences.putString("password", password);
password = preferences.getString("password", "");
Serial.println(password);
Serial.println("Network Credentials Saved using Preferences");
preferences.end();
ESP.restart();
}
}
}