如何使用 Arduino 從 EEPROM 獲取任意大小的資料?
Arduino Uno 擁有 1 kB 的 EEPROM 儲存空間。EEPROM 是一種非易失性儲存器,即即使在斷電後其內容也會保留。因此,它可以用來儲存您希望在電源迴圈之間保持不變的資料。配置或設定就是此類資料的示例。
在本文中,我們將瞭解如何從 EEPROM 獲取任意大小(不僅僅是一個位元組)的資料。我們將逐步介紹 Arduino 中的內建示例。EEPROM 示例可以從以下位置訪問:檔案 → 示例 → EEPROM。
示例
我們將檢視 eeprom_get 示例。此示例假設您已透過執行 eeprom_put 示例中的程式碼預先設定了 Arduino 的 EEPROM 中的資料。換句話說,eeprom_put 示例是此示例的前提。
主要的關注函式是 EEPROM.get()。它接受兩個引數,即開始讀取資料的起始地址,以及要將讀取到的資料儲存到的變數(可以是基本型別,如 float,或自定義 struct)。其他基本資料型別的示例包括 short、int、long、char、double 等。此函式根據要將讀取到的資料儲存到的變數的大小確定要讀取的位元組數。
我們首先包含庫檔案。
#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 */
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP