EEPROM (Electrically Erasable Programmable Read-Only Memory),电可擦可编程只读存储器–一种掉电后数据不丢掉的存储芯片。简而言之便是你想断电后arduino还要保存一些参数,就运用EEPROM吧。在各型号的arduino控制器上的AVR芯片均带有EEPROM,也有外接的EEPROM芯片,常见arduino控制器的EEPROM巨细:Arduino UNO、Arduino duemilanove-m328、Zduino m328均运用ATmega328芯片,EEPROM都为1KArduino duemilanove-m168的EEPROM为512bytesArduino 2560的EEPROM为4K下面咱们介绍arduino自带的EEPROM运用办法,arduino的库已经为咱们预备好了EEPROM类库,咱们要运用得先调用EEPROM.h,然后运用write和read办法,即可操作EEPROM。

另:下面的官方比如因为写成较早,所以讲EEPROM的巨细都定为了512字节,实际运用中,大家可参照上面所说的EEPROM巨细,自行更改。

1.写入

挑选 File>Examples>EEPROM>eeprom_write


    /*
    * EEPROM Write
    *
    * Stores values read from analog input 0 into the EEPROM.
    * These values will stay in the EEPROM when the board is
    * turned off and may be retrieved later by another sketch.
    */
    #include <EEPROM.h>
    // EEPROM 的当前地址,即你即将写入的地址,这儿便是从0开始写
    int addr = 0;
    void setup()
    {
    }
    void loop()
    {
      //模仿值读出后是一个0-1024的值,但每字节的巨细为0-255,所以这儿将值除以4再存储到val
      int val = analogRead(0) / 4;
      // write the value to the appropriate byte of the EEPROM.
      // these values will remain there when the board is
      // turned off.
      EEPROM.write(addr, val);
      // advance to the next address.  there are 512 bytes in
      // the EEPROM, so go back to 0 when we hit 512.
      addr = addr + 1;
      if (addr == 512)
        addr = 0;
      delay(100);
    }

2.读取

挑选 File>Examples>EEPROM>eeprom_read


    /*
    * EEPROM Read
    *
    * Reads the value of each byte of the EEPROM and prints it
    * to the computer.
    * This example code is in the public domain.
    */
    #include <EEPROM.h>
    // start reading from the first byte (address 0) of the EEPROM
    int address = 0;
    byte value;
    void setup()
    {
      // initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
    }
    void loop()
    {
      // read a byte from the current address of the EEPROM
      value = EEPROM.read(address);
      Serial.print(address);
      Serial.print("t");
      Serial.print(value, DEC);
      Serial.println();
      // advance to the next address of the EEPROM
      address = address + 1;
      // there are only 512 bytes of EEPROM, from 0 to 511, so if we're
      // on address 512, wrap around to address 0
      if (address == 512)
        address = 0;
      delay(500);
    }

3.铲除

挑选 File>Examples>EEPROM>eeprom_clear铲除EEPROM的内容,其实便是把EEPROM中每一个字节写入0,因为只用清一次零,所以整个程序都在setup部分完成。


    /* * EEPROM Clear
    *
    * Sets all of the bytes of the EEPROM to 0.
    * This example code is in the public domain.
    */
    #include <EEPROM.h>
    void setup()
    {
      // 让EEPROM的512字节内容悉数清零
      for (int i = 0; i < 512; i++)
        EEPROM.write(i, 0);
      // 清零作业完成后,将L灯点亮,提示EEPROM清零完成
      digitalWrite(13, HIGH);
    }
    void loop()
    {
    }