如何使用 Arduino 从 EEPROM 获取任意大小的数据?


Arduino Uno 拥有 1 kB 的 EEPROM 存储空间。EEPROM 是一种非易失性存储器,即即使在断电后其内容也会保留。因此,它可以用来存储您希望在电源循环之间保持不变的数据。配置或设置就是此类数据的示例。

在本文中,我们将了解如何从 EEPROM 获取任意大小(不仅仅是一个字节)的数据。我们将逐步介绍 Arduino 中的内置示例。EEPROM 示例可以从以下位置访问:文件 → 示例 → EEPROM

示例

我们将查看 eeprom_get 示例。此示例假设您已通过运行 eeprom_put 示例中的代码预先设置了 Arduino 的 EEPROM 中的数据。换句话说,eeprom_put 示例是此示例的前提。

主要的关注函数是 EEPROM.get()。它接受两个参数,即开始读取数据的起始地址,以及要将读取到的数据存储到的变量(可以是基本类型,如 float,或自定义 struct)。其他基本数据类型的示例包括 shortintlongchardouble 等。此函数根据要将读取到的数据存储到的变量的大小确定要读取的字节数。

我们首先包含库文件。

#include <EEPROM.h>

代码后面定义了一个全局结构体。

struct MyObject {
   float field1;
   byte field2;
   char name[10];
};

在 Setup 中,我们首先初始化 Serial,然后从 EEPROM 的开头(address = 0)读取一个浮点数。然后,我们在 secondTest() 函数中读取一个 struct(我们首先将 EEPROM 读取地址移动浮点数的大小,然后创建一个 struct 类型的对象,并读取到其中。然后我们逐个打印 struct 中的字段。

void setup() {
   float f = 0.00f; //Variable to store data read from EEPROM.
   int eeAddress = 0; //EEPROM address to start reading from

   Serial.begin(9600);
   while (!Serial) {
      ; // wait for serial port to connect. Needed for native USB port only
   }
   Serial.print("Read float from EEPROM: ");

   //Get the float data from the EEPROM at position 'eeAddress' EEPROM.get(eeAddress, f);
   Serial.println(f, 3); //This may print 'ovf, nan' if the data inside the EEPROM is not a valid float.

   /***
      As get also returns a reference to 'f', you can use it inline.
      E.g: Serial.print( EEPROM.get( eeAddress, f ) );
   ***/
   /***
      Get can be used with custom structures too.
      I have separated this into an extra function.
   ***/

   secondTest(); //Run the next test.
}

void secondTest() {
   int eeAddress = sizeof(float); //Move address to the next byte after float 'f'.
   MyObject customVar; //Variable to store custom object read from EEPROM.
   EEPROM.get(eeAddress, customVar);

   Serial.println("Read custom object from EEPROM: ");
   Serial.println(customVar.field1);
   Serial.println(customVar.field2);
   Serial.println(customVar.name);
}

循环中没有任何操作。

void loop() {
   /* Empty loop */
}

更新于: 2021年7月26日

544 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告