Storing strings using EEPROM lib doesn't work
Posted: Sat Feb 25, 2017 5:26 pm
Hello, I'm working on a project and I want to store WiFi config but I don't want to use existing projects (like WiFiManager). I'm trying few hours to store SSID and password with EEPROM library but with no success. Where is the problem? Here's my code:
There are no errors when compiling and I'm starting to be desperate. Thanks for any advice.
Code: Select all
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#define CONFIG_ID 0x36
#define DEFAULT_MODE WIFI_STA
#define DEFAULT_SSID "myssid"
#define DEFAULT_PASS "mypass"
byte wifiMode;
String wifiSsid;
String wifiPass;
void setup() {
Serial.begin(9600);
EEPROM.begin(512);
if(EEPROM.read(0)!=CONFIG_ID) {
restartConfig();
}
loadConfig();
if(wifiMode == WIFI_STA) {
WiFi.disconnect();
WiFi.begin(wifiSsid.c_str(), wifiPass.c_str());
while (WiFi.status() != WL_CONNECTED) {
delay(50);
}
}else if(wifiMode == WIFI_AP){
IPAddress apIP(192, 168, 4, 1);
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
if(wifiPass.length()==0){
WiFi.softAP(wifiSsid.c_str());
}else {
WiFi.softAP(wifiSsid.c_str(), wifiPass.c_str());
}
}
...
}
void loop() {
...
}
void restartConfig() {
saveConfig(DEFAULT_MODE, DEFAULT_SSID, DEFAULT_PASS);
}
void saveConfig(byte wMode, String ssid, String pass) {
EEPROM.write(0, CONFIG_ID);
EEPROM.write(1, wMode);
for (int i = 0; i < ssid.length(); ++i){
EEPROM.write(100+i, ssid[i]);
}
EEPROM.write(100+ssid.length(), 0);
for (int i = 0; i < pass.length(); ++i){
EEPROM.write(256+i, pass[i]);
}
EEPROM.write(256+pass.length(), 0);
EEPROM.commit();
}
void loadConfig() {
wifiMode = EEPROM.read(1);
char c;
int i = 0;
while(true) {
c = EEPROM.read(100+i);
if(c==0) break;
wifiSsid[i] = c;
i++;
}
i = 0;
while(true) {
c = EEPROM.read(256+i);
if(c==0) break;
wifiPass[i] = c;
i++;
}
}
There are no errors when compiling and I'm starting to be desperate. Thanks for any advice.