boarchuz wrote: ↑Tue Apr 02, 2024 12:57 am
but I can't help being curious what your use case is for dynamically grabbing a chunk of RTC memory? What do you gain vs static?
If a global-scope instance of a class is statically allocated in RTC memory, the constructor for that class will run after the ESP wakes up from deep sleep. That may not be the desired behavior. Perhaps you only want the constructor to run once at power-up but not after deep sleep.
If instead, you could create that object dynamically in RTC memory only when esp_reset_reason() indicates Power On, then you can avoid having the constructor run when it's a deep sleep reset.
This coded accomplishes the same thing, but in a sneaky way:
Code: Select all
#include "Arduino.h"
struct theStruct {
uint8_t data;
static uint32_t constructorCount;
theStruct(uint8_t init) : data(init) {
constructorCount++;
}
};
RTC_DATA_ATTR uint32_t theStruct::constructorCount = 0;
RTC_DATA_ATTR theStruct *objPtr = nullptr;
RTC_DATA_ATTR uint8_t structMemory[sizeof(theStruct)];
RTC_DATA_ATTR uint32_t bootCount;
void setup() {
Serial.begin(115200);
delay(2000);
esp_reset_reason_t resetReason = esp_reset_reason();
if (resetReason != ESP_RST_DEEPSLEEP) {
Serial.println("Resetting bootCount");
bootCount = 0;
if (objPtr != nullptr) {
delete objPtr;
}
objPtr = new (reinterpret_cast<theStruct*>(structMemory)) theStruct(2);
} else {
objPtr->data++;
bootCount++;
}
Serial.printf("bootCount = %lu\n", bootCount);
Serial.printf("constructorCount = %lu\n", theStruct::constructorCount);
Serial.printf("data = %hhu\n\n", objPtr->data);
Serial.flush();
esp_sleep_enable_timer_wakeup(5 * 1000000ULL);
esp_deep_sleep_start();
}
void loop() {
}