使用eeprom时,代码会提供意外的输出

我试图先读取EEPROM,然后再将特定数据写入EEPROM。我最初希望从EEPROM获得以前的数据,但它会打印我尝试写入EEPROM的数据。但是,如果我在读取和写入之间增加了延迟,那么一切都会按预期进行。我正在使用主频为240 Mhz的ESP32(Arduino框架)。我对时钟频率非常怀疑。我认为发生此问题是因为控制器的指令速度远高于波特率。我说的对吗?

#include <Arduino.h>
#include <EEPROM.h>

#define config_ver "pppp"

void saveconfig();

typedef struct {
  char version[10];
  char ssid[10];
  char pass[10];
  int settings;
} configuration_type;

configuration_type configuration = {config_ver,"lol","dk",50};

void setup() {
  Serial.begin(115200);
  EEPROM.begin(128);

  for(int i = 0; i <= 50; i++) {
    Serial.print((char)EEPROM.read(i));    // "pppp" is printed instead of values already in eeprom.
  }
  Serial.println("\n");

  //delay(10000);                          // delay

  saveconfig();                           // "pppp" is about to write to epprom

  for(int i = 0; i <= 50; i++) {
    Serial.print((char)EEPROM.read(i));
  }
  Serial.println("\n");

}

void loop() {

}

void saveconfig() {
  Serial.println("################Saving configuration################!!");
  for(int i = 0; i < sizeof(configuration); i++) {
    char data = *((char*)&configuration + i);
    EEPROM.write(i,data);
  }
  EEPROM.commit();
}

输出:

pppp␀␀␀␀␀␀lol␀␀␀␀␀␀␀dk␀␀␀␀␀␀␀␀␀␀2␀␀␀␀␀␀␀␀␀␀␀␀␀␀␀2␀␀

################Saving configuration################!!
pppp␀␀␀␀␀␀lol␀␀␀␀␀␀␀dk␀␀␀␀␀␀␀␀␀␀2␀␀␀␀␀␀␀␀␀␀␀␀␀␀␀2␀␀

添加延迟后的输出:

pppp␀␀␀␀␀␀lol␀␀␀␀␀␀␀dk␀␀␀␀␀␀␀␀␀␀2␀␀␀␀␀␀␀␀␀␀␀␀␀␀␀2␀␀

################Saving configuration################!!
aaaa␀␀␀␀␀␀lol␀␀␀␀␀␀␀dk␀␀␀␀␀␀␀␀␀␀2␀␀␀␀␀␀␀␀␀␀␀␀␀␀␀2␀␀
xiazai1999 回答:使用eeprom时,代码会提供意外的输出

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3074050.html

大家都在问