arduino-esp32 icon indicating copy to clipboard operation
arduino-esp32 copied to clipboard

ESP32 Preferences.putString() occasionally hangs after begin()"

Open hicham-vv opened this issue 8 months ago • 4 comments

Board

esp32 dev module

Device Description

NA

Hardware Configuration

NA

Version

v2.0.16

IDE Name

VSCode

Operating System

Windows 10

Flash frequency

80 Mhz setCpuFrequencyMhz(80);

PSRAM enabled

yes

Upload speed

115200

Description

Issue: preferences.putString() occasionally hangs

Hi, I'm experiencing an intermittent issue with Preferences.putString() on ESP32.

In my code, I'm updating several configuration values using Preferences. The preferences.begin() call always works fine — no issues there. But sometimes, the execution gets stuck at the beginning of the saving process, right after printing "Let Save new Configuration ...". It seems like the first putString() call is hanging or blocking, and the device doesn't proceed to the next lines (e.g., I don't see "T1", "T2", etc.).

Here's the relevant code:

Sometimes everything works perfectly and I see all the T1, T2, ... T9 messages in the Serial Monitor. Other times, it hangs after "Let Save new Configuration ...", and nothing further happens.

Any ideas on what could be causing putString() to get stuck like this? Could this be a flash memory or corruption issue?

Thanks in advance for any help or suggestions!

Sketch

void updatePreferences(JsonDocument& doc) {
    if (preferences.begin("ServerConfi", false)) {
        delay(500);
        const char *i_protocol = doc["protocol"];
        const char *i_domainename = doc["domainename"];
        const char *i_port = doc["port"];
        String i_path = doc["path"];
        const int32_t  i_aquifreq = doc["aquifreq"];
        const int32_t  i_sendfreq = doc["sendfreq"];
        const int32_t  i_ping = doc["ping"];
        const char *i_staticimei = doc["staticimei"];
        const char *i_devicename = doc["devicename"];

        Serial.println("Let Save new Configuration ...");
        delay(1000);
        
        preferences.putString("protocol", i_protocol); delay(10); Serial.println("T1");
        preferences.putString("domainename", i_domainename); delay(10); Serial.println("T2");
        preferences.putString("port", i_port); delay(10); Serial.println("T3");
        preferences.putString("path", i_path); delay(10); Serial.println("T4");
        preferences.putInt("aquifreq", i_aquifreq); delay(10); Serial.println("T5");
        preferences.putInt("sendfreq", i_sendfreq); delay(10); Serial.println("T6");
        preferences.putInt("ping", i_ping); delay(10); Serial.println("T7");
        preferences.putString("staticimei", i_staticimei); delay(10); Serial.println("T8");
        preferences.putString("devicename", i_devicename); delay(10); Serial.println("T9");

        Serial.println("New Configuration Saved ...");
        preferences.end();
        Serial.println("Update Setup Done.\n\n");
    } else {
        Serial.println("Failed to open preferences.\n\n");
    }
}

Debug Message

Let Save new Configuration ...

Other Steps to Reproduce

sometimes passes sometimes hangs ...

I have checked existing issues, online documentation and the Troubleshooting Guide

  • [x] I confirm I have checked existing issues, online documentation and Troubleshooting guide.

hicham-vv avatar Apr 02 '25 16:04 hicham-vv

Code doesn't run in a void. If there is something else actively using the flash, Preferences must wait to access the device. Provide code that can be compiled that demonstrates the error. Also, preferences writes in ~4k byte blocks. It isn't really saving you much to break the json apart and make multiple writes (as long as the json is under 4k).

lbernstone avatar Apr 02 '25 18:04 lbernstone

hello @lbernstone i can't provide all the code but it's a function that i call when i want to stock values , it is a task that i resume from loop function when i want to go deep sleep !

this is the json that i get from server httpget !

{"protocol":"http","domainename":"google.remote.com","port":"8080","path":"/datasnap","aquifreq":"5","sendfreq":"25","ping":"3600","staticimei":134755897134,"devicename":AR74,"aquimode":cap}

declaration functions :

void handleJsonRes_SerConfi(const String& response) {
  int jsonStart = response.indexOf('{');
  int jsonEnd = response.lastIndexOf('}') + 1;

  if (jsonStart != -1 && jsonEnd != -1) {
    String json = response.substring(jsonStart, jsonEnd);
    Serial.println(json);

    DeserializationError error = deserializeJson(doc, json.c_str());

    if (error) {
      Serial.print("deserializeJson() failed: ");
      Serial.println(error.f_str());
    } else {
      updatePreferences(doc);
    }
  } else {
    Serial.println("Error: JSON not found in the response.");
  }
}





void updatePreferences(JsonDocument& doc) {
    // Open preferences,in read-write mode
    if (preferences.begin("ServerConfi", false)) {
        delay(500);
        const char *i_protocol = doc["protocol"];
        const char *i_domainename = doc["domainename"];
        const char *i_port = doc["port"];
        String i_path = doc["path"];
        const int32_t  i_aquifreq = doc["aquifreq"];
        const int32_t  i_sendfreq = doc["sendfreq"];
        const int32_t  i_ping = doc["ping"];
        const char *i_staticimei=doc["staticimei"];
        const char *i_devicename=doc["devicename"];

        Serial.println("Let Save new Configuration ...");
        delay(1000);
        // Update the preferences
        preferences.putString("protocol",i_protocol);delay(10);Serial.println("T1");
        preferences.putString("domainename", i_domainename);delay(10);Serial.println("T2");
        preferences.putString("port", i_port);delay(10);Serial.println("T3");
        preferences.putString("path", i_path);delay(10);Serial.println("T4");
        preferences.putInt("aquifreq",i_aquifreq);delay(10);Serial.println("T5");
        preferences.putInt("sendfreq", i_sendfreq );delay(10);Serial.println("T6");
        preferences.putInt("ping",i_ping);delay(10);Serial.println("T7");
        preferences.putString("staticimei",i_staticimei);delay(10);Serial.println("T8");
        preferences.putString("devicename",i_devicename);delay(10);Serial.println("T9");
        Serial.println("New Configuration Saved ...");

        Serial.println("Update Setup Done. \n\n");
        preferences.end();
    }else{
      Serial.println("Failed to open preferences. \n\n");
    }
}

setup Function :

    xTaskCreatePinnedToCore(
                          TaskSetupOTA,   /* Task function. */
                          "Task SetupOTA",     /* name of task. */
                          8192,       /* Stack size of task */
                          NULL,        /* parameter of the task */
                          1,           /* priority of the task */
                          &handle_taskSetupOTA,      /* Task handle to keep track of created task */
                          1);          /* pin task to core 0 */


TaskSetupOTA task :

void TaskSetupOTA(void *pvParameters){

  vTaskSuspend(NULL);
  #ifdef debug
  Serial.print("TaskSetup_OTA running on core ");
  Serial.println(xPortGetCoreID());
  #endif

  delay(500);

  if(!powerUp()){
    powerUp();
  }
  if(!ImeiGood){
    ImeiGood=getImei();
  }
  getICCID();

  Serial2.println("AT+HTTPTERM");
  Serial2.write(26);
  delay(500);

  Serial2.println("AT+NETCLOSE");
  delay(500);
  Serial2.println("AT+HTTPTERM");
  delay(500);

  newflushSim(5000);
  SerialMon.print("Checking Network...");
  if (!modem.waitForNetwork(25000)) {
    SerialMon.println("Fail");
    Holdbef_sleep=false;
    vTaskDelete(NULL);
    return;
  }
  if (!modem.isNetworkConnected()){
    SerialMon.println("Fail");
    Holdbef_sleep=false;
    vTaskDelete(NULL);
    return;

  } 
  SerialMon.println("Network connected");


  // GPRS connection parameters are usually set after network registration
  SerialMon.print("Connecting to APN: ");
  SerialMon.print(offi_apn);
  if (!modem.gprsConnect(offi_apn.c_str(), offi_user.c_str(), offi_pass.c_str())) {
    SerialMon.println(" Fail");
    Holdbef_sleep=false;
    vTaskDelete(NULL);
    return;
  }
  SerialMon.println(" success");
  if (modem.isGprsConnected()) { SerialMon.println("GPRS connected"); }
  /*************************************************************************/

  delay(1000);
  String response = httpGetConfig();

  handleJsonRes_SerConfi(response); // herer where i hang time to time !!!!



  delay(1000);

}

hicham-vv avatar Apr 03 '25 18:04 hicham-vv

We do not need the full code. If you create a sketch small enough to reproduce (no JSON or other external things) we can work on it. With everything else you have going on, it is not clear whether the issue is on our end or yours. We need actually a minimal example, like writing same strings or randomly generated ones and that to be the only thing going on.

me-no-dev avatar Apr 04 '25 12:04 me-no-dev

We do not need the full code. If you create a sketch small enough to reproduce (no JSON or other external things) we can work on it. With everything else you have going on, it is not clear whether the issue is on our end or yours. We need actually a minimal example, like writing same strings or randomly generated ones and that to be the only thing going on.

OK understood , let me write the sketch for you guys

hicham-vv avatar Apr 04 '25 14:04 hicham-vv

Hi @hicham-vv

Would you still need assistance with this issue? if yes, please provide the sketch as requested.

Thanks

Parsaabasi avatar Oct 01 '25 08:10 Parsaabasi

Since there were no response, I close this case for now. Should you need further assistance please feel free to reopen this issue or create a new one.

Thanks

Parsaabasi avatar Oct 29 '25 02:10 Parsaabasi