Reputation: 41
I'm programming an ESP32 using VSCode. I have the following simple script:
#include <Arduino.h>
RTC_DATA_ATTR int counter1 = 0;
RTC_NOINIT_ATTR int counter2 = 0;
void setup() {
Serial.begin(115200);
Serial.printf("RTC programme running, counter1 = %d; counter2 = %d\n",counter1,counter2);
delay(3000);
counter1++;
counter2++;
esp_restart();
}
void loop() {
// nothing needed here
}
I'd expect the output to be:
RTC programme running, counter1 = 0; counter2 = 0
RTC programme running, counter1 = 0; counter2 = 1
RTC programme running, counter1 = 0; counter2 = 2
...
But instead I'm getting:
RTC programme running, counter1 = 0; counter2 = 109811943
RTC programme running, counter1 = 0; counter2 = 109811944
RTC programme running, counter1 = 0; counter2 = 109811945
...
(where the value of counter2 is a random value). I've tried various combinations of int, uint32_t etc. but still get the random value. It's caused by the RTC_NOINIT_ATTR definition but it's what I need for the eventual application. Anything I can be doing differently?
Upvotes: 3
Views: 1181
Reputation: 41
I added this at the start of the setup() function:
esp_reset_reason_t reason = esp_reset_reason();
if ((reason != ESP_RST_DEEPSLEEP) && (reason != ESP_RST_SW))
{
counter2 = 0;
}
It now works more or less as it should...
Upvotes: 0
Reputation: 3736
The RTC memory of the ESP32 is retained over software reset and deep sleep.
The RTC_DATA_ATTR and RTC_NOINIT_ATTR macros have linker directives to move the variables to addresses mapped into the RTC memory.
Variable with RTC_NOINIT_ATTR is not initialized at program start to not erase the value stored in the RTC memory. (RTC_DATA_ATTR variables value is available only in deep sleep stubs, which are small functions running in RTC memory right after wakeup before the normal program starts.)
To initialize the RTC_NOINIT_ATTR variable only on power-up, you can check the reset reason in setup() and initialize the variable only on some reset reasons.
Upvotes: 3