【问题标题】:Program crashes when receiving data from eeprom从 eeprom 接收数据时程序崩溃
【发布时间】:2020-03-08 02:57:59
【问题描述】:

每次我尝试运行link 中的代码时,我的程序都会崩溃。问题似乎出在*((char*)&configuration + i) = (char)EEPROM.read(i); 这一行。我认为没有必要为变量configuration分配内存,因为变量configuration已经初始化了。

int loadconfig() { 

  if(EEPROM.read(0) == config_ver[0] && EEPROM.read(1) == config_ver[1] &&
    EEPROM.read(2) == config_ver[2] && EEPROM.read(3) == config_ver[3]) {

    for(int i = 0; i <= sizeof(configuration_type); i++) {

      *((char*)&configuration + i) = (char)EEPROM.read(i);     //<------problem
    }
    return 1;
  }
  return 0;
} 

链接中的完整代码:

#include <EEPROM.h>

#define CONFIG_VERSION "VER01"

// Where in EEPROM?
#define CONFIG_START 32

typedef struct
{
  char version[6]; // detect if setting actually are written
  int my_setting_integer;
} configuration_type;

// with DEFAULT values!
configuration_type CONFIGURATION = {
  CONFIG_VERSION,
  42
};

// load whats in EEPROM in to the local CONFIGURATION if it is a valid setting
int loadConfig() {
  // is it correct?
  if (EEPROM.read(CONFIG_START + 0) == CONFIG_VERSION[0] &&
      EEPROM.read(CONFIG_START + 1) == CONFIG_VERSION[1] &&
      EEPROM.read(CONFIG_START + 2) == CONFIG_VERSION[2] &&
      EEPROM.read(CONFIG_START + 3) == CONFIG_VERSION[3] &&
      EEPROM.read(CONFIG_START + 4) == CONFIG_VERSION[4]){

  // load (overwrite) the local configuration struct
    for (unsigned int i=0; i<sizeof(CONFIGURATION); i++){
      *((char*)&CONFIGURATION + i) = EEPROM.read(CONFIG_START + i);
    }
    return 1; // return 1 if config loaded 
  }
  return 0; // return 0 if config NOT loaded
}

// save the CONFIGURATION in to EEPROM
void saveConfig() {
  for (unsigned int i=0; i<sizeof(CONFIGURATION); i++)
    EEPROM.write(CONFIG_START + i, *((char*)&CONFIGURATION + i));
}

void setup() {
  Serial.begin(9600);
  Serial.println("Hello world!");  // prints hello with ending line break 

  if(loadConfig()){
    Serial.println("Config loaded:");
    Serial.println(CONFIGURATION.version);
    Serial.println(CONFIGURATION.my_setting_integer);
  }else{
    Serial.println("Config not loaded!");
    saveConfig(); // overwrite with the default settings
  }
}

void loop() {
  //every 5s increment and save the settings!
  delay(5000);
  CONFIGURATION.my_setting_integer++;
  saveConfig();
}

【问题讨论】:

  • 将您的确切错误信息添加到问题中。
  • @eike 没有错误信息。 ESP32 用垃圾值重置!!
  • 好的,那我误解了你的问题。对我来说,“当我尝试编译时”意味着编译错误。

标签: c++ arduino embedded esp32


【解决方案1】:

它是for循环中的“

将其更改为“

提示:典型的缓冲区溢出问题

【讨论】:

  • 有趣的是,在“完整代码”sn-p 中,= 不见了。
  • @eike :因为“整个代码”是从链接复制并粘贴到“别人的代码”的,而之前呈现的代码是他实际运行的代码。
猜你喜欢
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
相关资源
最近更新 更多