我在尝试在ESP32 NodeMCU板的EEPROM中写入和检索字符串时遇到问题。
我遵循了本教程:https://roboticsbackend.com/arduino-write-string-in-eeprom/
这是我的代码:
#include <EEPROM.h>
void writeStringToEEPROM(int addrOffset, const String &strToWrite)
{
byte len = strToWrite.length();
EEPROM.write(addrOffset, len);
for (int i = 0; i < len; i++)
{
EEPROM.write(addrOffset + 1 + i, strToWrite[i]);
}
}
String readStringFromEEPROM(int addrOffset)
{
int newStrLen = EEPROM.read(addrOffset);
char data[newStrLen + 1];
for (int i = 0; i < newStrLen; i++)
{
data[i] = EEPROM.read(addrOffset + 1 + i);
}
data[newStrLen] = ' '; // !!! NOTE !!! Remove the space between the slash "/" and "0" (I've added a space because otherwise there is a display bug)
return String(data);
}
void setup() {
Serial.begin(115200);
Serial.println("-- Starting --");
writeStringToEEPROM(0, "Hello Arduino");
String retrievedString = readStringFromEEPROM(0);
Serial.print("The String we read from EEPROM: ");
Serial.println(retrievedString);
}
void loop() {}
这是输出:
ets Jun 8 2016 00:22:57
rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:10944
load:0x40080400,len:6388
entry 0x400806b4
-- Starting --
The String we read from EEPROM:
Serial.println(retrievedString(返回为blank。。。
@Juraj是对的,Arduino和ESP32的EEPROM.h库不同。在使用该函数之前,必须使用begin((初始化内存大小,write函数的工作原理与update函数类似。一旦执行了写函数,就需要执行commit((
#include <EEPROM.h>
#define EEPROM_SIZE 24
void writeStringToEEPROM(int addrOffset, const String &strToWrite)
{
byte len = strToWrite.length();
EEPROM.write(addrOffset, len);
delay(500);
for (int i = 0; i < len; i++)
{
EEPROM.write(addrOffset + 1 + i, strToWrite[i]);
delay(500);
}
EEPROM.commit();
}
String readStringFromEEPROM(int addrOffset)
{
int newStrLen = EEPROM.read(addrOffset);
char data[newStrLen + 1];
for (int i = 0; i < newStrLen; i++)
{
data[i] = EEPROM.read(addrOffset + 1 + i);
}
data[newStrLen] = ' ';
return String(data);
}
void setup() {
Serial.begin(115200);
EEPROM.begin(EEPROM_SIZE);
Serial.println("-- Starting --");
writeStringToEEPROM(0, "Hello Arduino");
String retrievedString = readStringFromEEPROM(0);
Serial.print("The String we read from EEPROM: ");
Serial.println(retrievedString);
}
void loop() {}