0

I'm trying to save a union in the RTC memory of my ESP32 but it doesn't semm to work. This is an example of what I'm trying to do:

RTC_DATA_ATTR union {
    float float_variable;
    byte temp_array[4];
  } u;

int sleepTime =5;
RTC_DATA_ATTR int cpt = 0;

void setup() {
  
  Serial.begin(115200);
  esp_sleep_enable_timer_wakeup(sleepTime * 1000000);
  u.float_variable=2.1;

}

void loop() {
  Serial.println("wake up number: " + String(cpt) + " u.float_variable is: " + String(u.float_variable));
  cpt++;
  u.float_variable+=cpt;

  esp_deep_sleep_start();
}

If you are able to test it on your machine, you will see the cpt increase but not the u.float_variable If anyone as any suggestion I'm down, thank you!

EMall
  • 29
  • 3

1 Answers1

0

You don't see u.float_variable increase because you assign a value to it every time your program starts. When the CPU exits deep sleep, the CPU restarts and runs setup() again, which always sets u.float_variable to 2.1.

You could solve this problem by initializing the union as you did cpt:

RTC_DATA_ATTR union {
    float float_variable;
    byte temp_array[4];
  } u = { .float_variable = 2.1 };

int sleepTime =5;
RTC_DATA_ATTR int cpt = 0;

void setup() {
  
  Serial.begin(115200);
  esp_sleep_enable_timer_wakeup(sleepTime * 1000000);
//  u.float_variable=2.1;  THIS FORCES u.float_variable to stay at 2.1

}

void loop() {
  Serial.println("wake up number: " + String(cpt) + " u.float_variable is: " + String(u.float_variable));
  cpt++;
  u.float_variable+=cpt;

  esp_deep_sleep_start();
}

or if union initializations get you down you could only initialize u.float_variable on your first run through:

RTC_DATA_ATTR union {
    float float_variable;
    byte temp_array[4];
  } u;

int sleepTime =5;
RTC_DATA_ATTR int cpt = 0;

void setup() {
  
  Serial.begin(115200);
  esp_sleep_enable_timer_wakeup(sleepTime * 1000000);
  if(cpt == 0)
    u.float_variable=2.1;
}

void loop() {
  Serial.println("wake up number: " + String(cpt) + " u.float_variable is: " + String(u.float_variable));
  cpt++;
  u.float_variable+=cpt;

  esp_deep_sleep_start();
}

The first form - initializing the union - is better C/C++. The second form gives you a bit more flexibility for more complicated behaviors than this program needs.

romkey
  • 6,218
  • 3
  • 16
  • 12