ESP32 S3 doesn't store string variable after deep sleep

I want to store some variables even if the MCU comes back from deep sleep.
For that, usually you have to add RTC_DATA_ATTR when declaring the variables. But this only works for me with int variables but not strings. Here is an example code that I have tested:

#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */
//Plant 1 Wateringlog
RTC_DATA_ATTR String ZeroWater = "0";
RTC_DATA_ATTR String LatestM[4] = { "0", "Test1", "Test42", "Test33" };
RTC_DATA_ATTR int LatestHumM[4] = { 0, 14, 24, 45 };


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  delay(500);
  Serial.print("Zerowater before restart: ");
  Serial.println(ZeroWater);

  Serial.print("LatestM before restart:");
  Serial.println(LatestM[2]);

  Serial.print("LatestHumM before restart: ");
  Serial.println(LatestHumM[2]);

  ZeroWater = "34";
  Serial.print("NEW Zerowater changed before restart: ");
  Serial.println(ZeroWater);

  LatestM[2] = "Test4545454 hr";
  Serial.print("NEW LatestM[2] changed before restart: ");
  Serial.println(LatestM[2]);

  LatestHumM[2] = 45454545;
  Serial.print("NEW LatestM[2] changed before restart: ");
  Serial.println(LatestHumM[2]);

  Serial.println("");
  Serial.println("");


  Serial.println("Delay");
  delay(50000);
  startDeepSleep();
}

void startDeepSleep() {
  Serial.println("Going to sleep...");
  esp_sleep_enable_timer_wakeup(10 * uS_TO_S_FACTOR);  //time_in_us. uS_TO_S_FACTOR 1000000
  delay(1000);
  //Serial.flush();
  // gpio_deep_sleep_hold_en();
  esp_deep_sleep_start();
}

when coming back from deep sleep, it sucessfully gives me the saved values of LatestHumM, which is an int variable. But all of the string variables return the values of the beginning of the code, not the new one given in the loop.
Is there anything I can do to store my string values during deep sleep?

You have a problem not with strings, but with String class. Take note the difference.
The Arduino String type is a complex object. It uses an indirect access to its text data. When you store it in non-volatile memory - you store the object header only and not its data.
To store the text use a standard C strings - i.e. a char arrays:

RTC_DATA_ATTR char ZeroWater[] = "Test1";

2 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.