Arduino 101/Genuino 101 EEPROM的使用


EEPROM (Electrically Erasable Programmable Read-Only Memory),电可擦可编程只读存储器-——一种断电后数据不丢失的存储设备。常被用作记录设备工作数据、保存配置参数。简而言之就是你想断电后Arduino还要记住一些数据,那就可以使用EEPROM。

101的EEPROM库和其他Arduino的不同。从源码可知,Arduino 101/Genuino 101(此后称为101),并没有EEPROM存储单元,其提供的EEPROM库,实际上是在操纵其上的Flash空间。CurieEEPROM 从intel Curie的Flash中划分出了 2Kbyte 的空间,模拟成EEPROM空间。

要使用该库,需要调用的头文件 CurieEEPROM.h。在其示例程序中,展示了6个相关例程:

-----------------------------------------
eeprom_clear 清空EEPROM中所有数据

eeprom_crc 使用EEPROM进行CRC校验

eeprom_get 从EEPROM读出特定类型的数据

eeprom_put 向EEPROM存入特定类型数据

eeprom_read 从EEPROM读取4byte数据

eeprom_write 向EEPROM写入4byte数据
-----------------------------------------

这里我仅对最常用的3个例程进行讲解

向EEPROM写入数据

主要使用的到的方法有二:

EEPROM.write(addr, val); //向指定地址,写入4字节的数据val
EEPROM.write8(addr, val);//向指定地址,写入1字节的数据val

#include

/** the current address in the EEPROM (i.e. which byte we're going to write to next) **/
int addr = 0;

void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

for(int i = 0; i < 512; i++)
{
unsigned long val = analogRead(0);
Serial.print("Addr:\t");
Serial.print(addr);
Serial.print("\tWriting: ");
Serial.println(val);
EEPROM.write(addr, val);
addr++;
delay(100);
}

Serial.println("done writing");
}

void loop() {

}

从EEPROM读取数据与EEPROM写入方法类似,读取EEPROM数据的方法如下:

EEPROM.read(addr); //从指定地址,读取4字节的数据
EEPROM.read8(addr);//从指定地址,读取1字节的数据

#include

// start reading from the first byte (address 0) of the EEPROM
int address = 0;
unsigned long value;

void setup() {
// initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
}

void loop() {
// read a dword from the current address of the EEPROM
value = EEPROM.read(address);

Serial.print(address);
Serial.print("\t");
Serial.print(value, DEC);
Serial.println();

//increment address
address++;
if (address == EEPROM.length()) {
address = 0;
}

delay(500);
}

清空EEPROM中所有数据

这个真没啥说的了,要清空EEPROM空间中的所有数据,直接调用 EEPROM.clear() 函数即可。

示例程序如下:

#include

void setup() {
// initialize the LED pin as an output.
pinMode(13, OUTPUT);

EEPROM.clear();

// turn the LED on when we're done
digitalWrite(13, HIGH);
}

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

文章来源: ARDUINO中文社区