【问题标题】:Store Union value in RTC memory将 Union 值存储在 RTC 内存中
【发布时间】:2022-01-03 17:08:49
【问题描述】:

我正在尝试在我的 ESP32 的 RTC 内存中保存一个联合,但它无法正常工作。这是我正在尝试做的一个例子:

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();
}

如果你能在你的机器上测试它,你会看到 cpt 增加,但不会看到 u.float_variable 如果有人对我有任何建议,谢谢!

【问题讨论】:

    标签: c++ arduino storage esp32 arduino-esp32


    【解决方案1】:

    您看不到u.float_variable 增加,因为您在每次程序启动时都为其分配了一个值。当 CPU 退出深度睡眠时,CPU 重新启动并再次运行 setup(),这始终将 u.float_variable 设置为 2.1。

    您可以像 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();
    }
    

    或者如果联合初始化让您失望,您只能在第一次运行时初始化 u.float_variable

    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();
    }
    

    第一种形式——初始化联合——是更好的 C/C++。第二种形式为您提供了比该程序需要的更复杂的行为更多的灵活性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多