如何使用Arduino将任意大小的数据写入EEPROM?
Arduino Uno 拥有 1 kB 的 EEPROM 存储空间。EEPROM 是一种非易失性存储器,即其内容即使在断电后也能保留。因此,它可以用于存储希望在电源循环之间保持不变的数据。配置或设置就是此类数据的示例。
在本文中,我们将了解如何将任意大小(不仅仅是一个字节)的数据放入 EEPROM。我们将逐步介绍 Arduino 中的内置示例。EEPROM 示例可以从以下位置访问:**文件 → 示例 → EEPROM**。
示例
我们将查看 **eeprom_put** 示例。我们感兴趣的主要函数是 **EEPROM.put()**。它接受两个参数,即开始写入/更新数据的起始地址,以及要写入的数据(可以是基本类型,如 **float**,或自定义结构体)。其他基本数据类型的示例包括 **short**、**int**、**long**、**char**、**double** 等。**put()** 函数的行为类似于 **update()** 函数,即仅当要写入的新值与存储在该内存位置的现有值不同时,它才会写入 EEPROM。
我们首先包含库文件。
#include <EEPROM.h>
接下来,我们定义了一个结构体,其中包含两个浮点数和一个字符数组。
struct MyObject {
float field1;
byte field2;
char name[10];
};在 Setup 中,我们首先初始化 Serial。接下来,我们初始化一个浮点数,并将其写入 EEPROM 的开头(**地址 = 0**)。然后,我们使用浮点数的大小(使用 **sizeof()** 函数)来递增地址变量,并存储一个 **结构体**(使用之前定义的结构体)。
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
float f = 123.456f; //Variable to store in EEPROM.
int eeAddress = 0; // Location we want the data to be put.
// One simple call, with the address first and the object second.
EEPROM.put(eeAddress, f);
Serial.println("Written float data type!");
/** Put is designed for use with custom structures also. **/
// Data to store.
MyObject customVar = {
3.14f,
65,
"Working!"
};
eeAddress += sizeof(float); // Move address to the next byte after float 'f'.
EEPROM.put(eeAddress, customVar);
Serial.print("Written custom data type!
View the example sketch eeprom_get to see how you can retrieve the values!");
}循环中没有任何操作。
void loop() {
/* Empty loop */
}此示例是 **eeprom_get** 示例的前身。换句话说,**eeprom_get** 示例将假设您已在 Arduino 上运行过一次此 **eeprom_put** 示例。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP