EEPROM not saving only after restart

Good morning, I have been wanting to perform a series of functions with the EEPROM for several days, which are to save an SSID and a Password for a Wi-Fi site. These are saved correctly and also read correctly after doing this, but once you rerun, it cannot read what we have previously saved. I've read other questions from people who have similar things, but I can't see what I'm doing wrong. I am attaching my code to see if someone can help me.

When I try to execute the code again after saving, it executes the function to check EEPROm and it tells me that it is empty

Thanks a lot

#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <ThingsBoard.h>
#include <PubSubClient.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// SCL GPIO5
// SDA GPIO4
#define OLED_RESET 0  // GPIO0
Adafruit_SSD1306 display(OLED_RESET);

#define WIFI_AP "PRUEBA"
#define WIFI_PASSWORD "1232"
#define TOKEN "#"
// SENSOR
#define PINLED A0
#define Push D0 //
byte Push_lee = 0;
String array_wifi[5] = {"Prueba", "PRUEBA"};
String array_pass[5] = {"1234", "1232"};
String array_eepromssid[5];
String array_eeprompass[5];



WiFiClient wifiClient;
PubSubClient client(wifiClient);
ThingsBoard tb(wifiClient);

char thingsboardServer[] = "##";
int status = WL_IDLE_STATUS;
unsigned long lastSend;
boolean WifiActivado = false;
int intentos = 0;
int aux = 0;

void setup()
{
  pinMode(PINLED, INPUT);
  pinMode(Push, INPUT); //
  Serial.begin(9600);
  EEPROM.begin(1024); //64  / 64
  String ssid2=readEEPROMdata(0);
  String pw2=readEEPROMdata(64);
  Serial.println("He almacenado " + ssid2);
  Serial.println("Cuya contraseña es " + pw2);
  delay(10);
  comprobarDataEEPROM();
  lastSend = 0;

}

void loop()
{
  if ( !tb.connected() ) {
  }
  if ( millis() - lastSend > 9000 ) {
    sendAnalogData();
    lastSend = millis();
  }

  tb.loop();
}

void Wifi() {
  String ssid3=readEEPROMdata(0);
  String pw3=readEEPROMdata(64);
  Serial.println("He almacenado3 " + ssid3);
  Serial.println("Cuya contraseña3 es " + pw3);
  int n = 0;
  int n2 = 0;
  int i;
  boolean WiFiActivado2 = false;
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.println("Buscando puntos de acceso...");
  display.display();
  n = 0;
  intentos = 0;

  while ((WiFi.status() != WL_CONNECTED) && (WiFiActivado2 == false)) {
    if (intentos > 0) {
      n++;
      intentos = 0;
      Serial.println("CAMBIO DE WIFI!");
    }

    WiFi.begin(array_wifi[n], array_pass[n]);
    delay(20000);
    Serial.println("Connecting " + array_wifi[n]);
    Serial.println("Usando la contraseña " + array_pass[n]);
    Serial.println(intentos);
    //display.clearDisplay();
    display.println("Connecting " + array_wifi[n]);
    display.display();
    intentos++;
  }
  if (WiFi.status() == WL_CONNECTED) {
    //        char test[] = "hello world"; char *strptr = &test[6]; EEPROM_writeAnything(0, strptr);
    //        EEPROM.write(item, item2 );
    Serial.println("ESTOY CONECTADO a: " + array_wifi[n]);
    display.clearDisplay();
    display.display();
    display.setCursor(0, 0);
    Serial.println("Conectado a " + array_wifi[n]);
    display.println("Connected! " + array_wifi[n]);
    display.display();
    WiFiActivado2 = true;
    String ssid=readEEPROMdata(0);
    String pw=readEEPROMdata(64);
    //Serial.println("El punto wifi almacenado era " + ssid);
    //Serial.println("La contraseña almacenada era " + pw);
    if(ssid.length() == 0){
      saveDataToEeprom(array_wifi[n], array_pass[n]);
      ssid=readEEPROMdata(0);
      pw=readEEPROMdata(64);
      Serial.println("El punto wifi correcto es " + readEEPROMdata(0));
      Serial.println("La contraseña correcta es " + readEEPROMdata(64));
    }
    
  }

  if (WiFiActivado2 == true) {
    while (!tb.connected()) {
      Serial.println("Conectandose a thingsboard ...");
      if ( tb.connect(thingsboardServer, TOKEN) ) {
        Serial.println( "[CONECTADO A THINGSBOARD]" );
      } else {
        Serial.print( "[FALLO]" );
        Serial.println( " : [Se intentará de nuevo en 5 segundos]" );
        // Wait 5 seconds before retrying
        delay( 5000 );
      }
    }
  }
}



void sendAnalogData() {
  Serial.println(analogRead(PINLED));
  Push_lee = digitalRead(Push);
  int a = random(100);
  int b = random(100);
  tb.sendTelemetryFloat("TemperaturaAleatoria", a);
  tb.sendTelemetryFloat("HumedadAleatoria", b);
  tb.sendTelemetryFloat("Puerta", Push_lee);
}

void comprobarDataEEPROM(){
  if (array_eepromssid[0].length() == 0){
    Serial.println("He comprobado la EEPROM y está vacía");
    Wifi();
  
  }else{
    Serial.println("Los datos que posee la EEPROM son");
    Serial.println(array_eepromssid[0]);
    Serial.println(array_eepromssid[1]);
  }
}

void saveDataToEeprom(String ssid, String pass)
{
  
  Serial.println("Saving to Eeprom");
  if (ssid.length() > 0 && pass.length() > 0) {
    //for (int i = 0; i < 128; ++i) {
      //EEPROM.write(i, 0);
    //}
    int index=0;
    while(ssid[index]){
      EEPROM.write(index, ssid[index]);
      Serial.println(ssid[index]);
      index++;
    }
    //Serial.println("Antes del commit");
    //Serial.println(readEEPROMdata(0));
    index=0;
    while(pass[index]){
      EEPROM.write(index+64, pass[index]);
      Serial.println(pass[index]);
      index++;
    }
    //Serial.println("AAAAAA " + ssid);
    //Serial.println("AAAAAA " + pass);
    EEPROM.commit();
    Serial.println("Despues del commit");
    array_eepromssid[0] = readEEPROMdata(0);
    array_eepromssid[1] = readEEPROMdata(64);
    Serial.println(array_eepromssid[0]);
    Serial.println(array_eepromssid[0].length());
    Serial.println(array_eepromssid[1]);
    //EEPROM.end();
    //ESP.reset();
  }
  Serial.println("Ya he guardado todo");
}

void erase_eeprom(){
  // write a 0 to all 512 bytes of the EEPROM
  for (int i = 0; i < 1024; i++) {
    EEPROM.write(i, 0);
  }
  EEPROM.end();
}
String readEEPROMdata(int index)
{
  String aux = "";
  char caracter;
  while(caracter=EEPROM.read(index)){
    aux += caracter;
    index++;
    }
    Serial.println(aux);
    return aux;
    
    }
    

Why are you making things complicated by using Strings ?

If you were to use C style strings you could use EEPROM.put() and EEPROM.get() to save/load them with one command

code is kind of a mess... a struct with a fixed size array would make your life easier.

when you call saveDataToEeprom() you don't store a trailing null char - which is what you are trying to read back to decide when to stop.

so you depend on what's in the EEPROM (hopefully 0) to decide when your string ends

also seems you have either an SSID or a PWD at address 64? I have not read in details but this feels weird just by looking at the name of the variables

  String ssid2=readEEPROMdata(0);
  String pw2=readEEPROMdata(64);

and

    array_eepromssid[0] = readEEPROMdata(0);
    array_eepromssid[1] = readEEPROMdata(64);

how do you exit this while loop:

while ((WiFi.status() != WL_CONNECTED) && (WiFiActivado2 == false)) {
  if (intentos > 0) {
    n++;
    intentos = 0;
    Serial.println("CAMBIO DE WIFI!");
  }

  WiFi.begin(array_wifi[n], array_pass[n]);
  delay(20000);
  Serial.println("Connecting " + array_wifi[n]);
  Serial.println("Usando la contraseña " + array_pass[n]);
  Serial.println(intentos);
  display.println("Connecting " + array_wifi[n]);
  display.display();
  intentos++;
}

you don't modify WiFiActivado2

Yes the idea is to have 64 bytes for each ssid and password so when I hit 64 bytes it stops and starts typing the password.

Declaring ssid2 and pw2 is just for testing.

So how can I stop storing the ssid or password in the writedatatoeeprom? I have tried to put an index <20 in the while for example but I get nothing.

Loop stops when Wifi is connected. I tried this an it works properly.

the code says it does not. there is something else at play here

seems you want to deal with multiple wifi network. Have you looked at
Arduino/WiFiMulti.ino at master · esp8266/Arduino · GitHub

/*
    This sketch shows how to use multiple WiFi networks.
    In this example, ESP8266 works in AP mode.
    It demonstrates:
    - Fast connect to previous WiFi network at startup
    - Registering multiple networks (at least 1)
    - Connect to WiFi with strongest signal (RSSI)
    - Fall back to connect to next WiFi when a connection failed or lost
    - Fall back to connect to hidden SSID's which are not reported by WiFi scan
    To enable debugging output, select in the Arduino iDE:
    - Tools | Debug Port: Serial
    - Tools | Debug Level: WiFi
*/

The function of that while is to go through an array with different ssids and passwords that I have set by hand, so that when one matches the ssid and password of a wifi, it connects and begins to send data to thingsboard, I have modified The code a little more in case I have left something before, but the important thing is that connecting to the Wi-Fi does it correctly, the error I have for what you have told me is how to tell the eeprom memory with the eeprom.write to stop to save the ssid or the password, once it has finished letter by letter, I do not know if I explain myself.

What surprises me the most is that in the savedatatoeeprom function, in one of the prints that I tell you, I ask you to show me the length of what you have saved and the ssid or password, and it does it correctly and gives me the ssid along with the length which is 10 in my case

Thanks

actually it works but is useless

what's the value of WiFiActivado2 when you arrive there ?
if it's true, then you don't enter the while
if it's false, then the && (WiFiActivado2 == false) is always true and thus useless as you never change that value

ps: that while() does not test if n goes out of bounds for example....

Yes, the idea is that the moment it connects to the Wi-Fi it will not go back in, but it is a bit useless as you are saying, now I change it.

Regarding the writeEEprom, I still don't understand what the problem is and why it has to stop, if when I ask it to return what it has in the EEPROM before restarting, it returns what I request.

Just use a char buffer for your SSID and PWD, in a struct for example and save / read back the struct

SaveDataToEeprom and readEEPROMdata are already structures to save / read information, right? What is failing within them so that this information is erased when restarting the eeprom?

they are functions.

a structure would be something like

const byte maxTextLength = 16;
struct t_wifiConfig {
  const char ssid[maxTextLength + 1];
  const char pwd[maxTextLength + 1];
};

you would use a t_wifiConfig for representing your information, for example

const byte maxTextLength = 16;
struct t_wifiConfig {
  const char ssid[maxTextLength + 1];
  const char pwd[maxTextLength + 1];
};

t_wifiConfig knownNetworks[] = {
  {"SSDI1", "PWD#1!"},
  {"SSDI2", "PWD#2!"},
};
const byte knownNetworksCount = sizeof knownNetworks / sizeof knownNetworks[0];


void setup() {
  Serial.begin(115200); Serial.println();
   Serial.println(F("Known Configs:"));
  for (auto && aConfig : knownNetworks) {
    Serial.print(aConfig.ssid); Serial.write('\t'); Serial.println(aConfig.pwd);
  }
}

void loop() {}

In your function looking for the current network you could populate a
t_wifiConfig currentConfig;
and that's what would be saved to EEPROM

although given the known networks are hardwired, you could only save 1 byte which is the index of the current network.

It is always a good idea to save a magic keyword first in EEPROM to help distinguish if the EEPROM was already set or not (for the first time you use the ESP).

but in practice I really recommend you study the multiple wifi example I pointed at in post #5... seems you did not even click on it...

Okay, i will study that possibility, it seems that could help me, thank you so much for the help!

Saving and reading are working now!