一:FLASH内容分享
它的数据存储是依靠主控芯片ESP32-P4内部的 16MB Flash(闪存) 来实现的。
工作原理:使用的 EEPROM 库函数,其底层操作的正是这片 16MB 的 Flash 存储空间。库函数通过软件方法,在Flash中模拟出传统EEPROM的读写行为。
可用空间:虽然Flash总容量为16MB,但其中很大一部分要用于存储固件程序。因此,EEPROM库实际能自由读写的模拟EEPROM空间大小,取决于在代码初始化时(例如 EEPROM.begin(4096))所申请的大小,最大可申请的空间受限于Flash的剩余容量。
二:软件编写流程
2.1 初始化 (EEPROM.begin())
功能:在Flash中划出一块区域,用来模拟EEPROM的存储空间。
操作:在setup()函数中,通过 EEPROM.begin(4096) 申请了4096个字节的空间。这个大小可以按需调整,但需注意,在Arduino框架下,默认EEPROM大小通常为4096字节。
2.2 写入数据 (EEPROM.write())
功能:将一个字节的数据写入到指定的内存地址。
操作:例程使用一个 for 循环,向地址0到4095依次写入数据。写入的值是地址对256取模的结果 (addr % 256),因为一个字节最大能表示0-255的数值。
注意:EEPROM.write() 只是将数据写入到内存缓冲区,此时数据并未真正保存到Flash中。
2.3 提交保存 (EEPROM.commit())
功能:将缓冲区中的所有数据,真正地、永久地写入到Flash存储器中。
操作:在所有EEPROM.write()操作完成后,必须调用 EEPROM.commit()。这是整个写入流程中最关键的一步,如果缺少这一步,写入的数据在重启后会全部丢失。
2.4 读取数据 (EEPROM.read())
功能:从指定的内存地址读取一个字节的数据。
操作:在写入并提交后,例程通过另一个 for 循环,读取并打印出所有地址的数据,以验证写入是否成功。
三:软件代码部分
3.1 软件代码:
#include "EEPROM.h"
// the current address in the EEPROM (i.e. which byte
// we're going to write to next)
int addr = 0;
#define EEPROM_SIZE 64
void setup() {
Serial.begin(115200);
Serial.println("start...");
if (!EEPROM.begin(EEPROM_SIZE)) {
Serial.println("failed to initialize EEPROM");
delay(1000000);
}
Serial.println(" bytes read from Flash . Values are:");
for (int i = 0; i < EEPROM_SIZE; i++) {
Serial.print(byte(EEPROM.read(i)));
Serial.print(" ");
}
Serial.println();
Serial.println("writing random n. in memory");
}
void loop() {
// need to divide by 4 because analog inputs range from
// 0 to 1023 and each byte of the EEPROM can only hold a
// value from 0 to 255.
// int val = analogRead(10) / 4;
int val = byte(random(10020));
// write the value to the appropriate byte of the EEPROM.
// these values will remain there when the board is
// turned off.
EEPROM.write(addr, val);
Serial.print(val);
Serial.print(" ");
// advance to the next address. there are 512 bytes in
// the EEPROM, so go back to 0 when we hit 512.
// save all changes to the flash.
addr = addr + 1;
if (addr == EEPROM_SIZE) {
Serial.println();
addr = 0;
EEPROM.commit();
Serial.print(EEPROM_SIZE);
Serial.println(" bytes written on Flash . Values are:");
for (int i = 0; i < EEPROM_SIZE; i++) {
Serial.print(byte(EEPROM.read(i)));
Serial.print(" ");
}
Serial.println();
Serial.println("----------------------------------");
}
delay(100);
}3.2 软件输出界面如下所示:

四:总结
总的来说,EEPROM_WRITE例程通过一个“写入-提交-读取验证”的闭环,清晰地展示了在ESP32上使用模拟EEPROM进行数据持久化存储的标准方法。
本质:并非操作硬件EEPROM,而是操作Flash。
目的:为开发者提供一个在无文件系统情况下,简单保存配置、状态等少量关键数据的方案。
关键:提醒开发者注意 EEPROM.commit() 的必要性,这是确保数据不丢失的核心。
我要赚赏金
