简体   繁体   English

存储为 RTC_NOINIT_ATTR (ESP32) 时的 C++ int 未定义行为

[英]C++ int undefined behaviour when stored as RTC_NOINIT_ATTR (ESP32)

I'm programming an ESP32 using VSCode.我正在使用 VSCode 对 ESP32 进行编程。 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). (其中counter2的值是一个随机值)。 I've tried various combinations of int , uint32_t etc. but still get the random value.我尝试了intuint32_t等的各种组合,但仍然得到随机值。 It's caused by the RTC_NOINIT_ATTR definition but it's what I need for the eventual application.它是由RTC_NOINIT_ATTR定义引起的,但这是我最终应用程序所需要的。 Anything I can be doing differently?我可以做一些不同的事情吗?

The RTC memory of the ESP32 is retained over software reset and deep sleep. ESP32 的 RTC 内存在软件复位和深度睡眠期间保留。

The RTC_DATA_ATTR and RTC_NOINIT_ATTR macros have linker directives to move the variables to addresses mapped into the RTC memory. RTC_DATA_ATTR 和RTC_NOINIT_ATTR宏具有链接器指令,可将变量移动到映射到 RTC 存储器的地址。

Variable with RTC_NOINIT_ATTR is not initialized at program start to not erase the value stored in the RTC memory.带有 RTC_NOINIT_ATTR 的变量不会在程序启动时初始化,以免擦除存储在 RTC 存储器中的值。 (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.) (RTC_DATA_ATTR 变量值仅在深度睡眠存根中可用,深度睡眠存根是在正常程序启动之前唤醒后立即在 RTC 内存中运行的小函数。)

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 .要仅在上电时初始化 RTC_NOINIT_ATTR 变量,您可以检查setup() 中的重置原因并仅在某些重置原因时初始化变量。

I added this at the start of the setup() function:我在 setup() 函数的开头添加了这个:

  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...它现在或多或少地工作了......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM