Thursday, 18 April 2013 22:26

读取和写入任何结构EEPROM

Written by
Arduino内建的EEPROM函数(function)毎次只支能写入一个字节(one byte),一个英文字母或者整数从0到255。当想要写入较大的数字时,唯有调用多次的EEPROM函数,从而造成代码复杂以及难于调试。
 
使用下面的代码,只需一次EEPROM函数调用,任何数据结构或变数都可以一一写入及读取。保存以下代码至文件名为EEPROMAnything.h

#include <EEPROM.h>
#include <Arduino.h> // for type definitions

template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
   const byte* p = (const byte*)(const void*)&value;
   unsigned int i;
   for (i = 0; i < sizeof(value); i++)
   EEPROM.write(ee++, *p++);
   return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value)
{
   byte* p = (byte*)(void*)&value;
   unsigned int i;
   for (i = 0; i < sizeof(value); i++)
   *p++ = EEPROM.read(ee++);
   return i;
}

 

 

一旦有了以上文件,编写程序前只要添加#include "EEPROMAnything.h"就能调用 EEPROM_writeAnything 和 EEPROM_readAnything函数了。请看以下例子:
#include <EEPROM.h>
#include "EEPROMAnything.h"
struct config_t
{
    long alarm;
    int mode;
} configuration;
void setup()
{
    EEPROM_readAnything(0, configuration);
    // ...
}
void loop()
{
    // let the user adjust their alarm settings
    // let the user adjust their mode settings
    // ...
    // if they push the "Save" button, save their configuration
    if (digitalRead(13) == HIGH)
        EEPROM_writeAnything(0, configuration);
}
  
当然也可以使用avr的eeprom程序库来代替以上EEPROMAnything.h

#include <avr/eeprom.h>

struct settings_t
{
  long alarm;
  int mode;
} settings;

void setup()
{
  eeprom_read_block((void*)&settings, (void*)0, sizeof(settings));
    // ...
}
void loop()
{
    // let the user adjust their alarm settings
    // let the user adjust their mode settings
    // ...

    // if they push the "Save" button, save their configuration
    if (digitalRead(13) == HIGH)
      eeprom_write_block((const void*)&settings, (void*)0, sizeof(settings));
}

Read 50288 times Last modified on Sunday, 21 April 2013 11:47
Back to Top