如何使用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