Loading

Paste #pyi6xwxmp

  1. #ifdef EEPROM_FEATURES
  2.  
  3. #include <EEPROM.h>
  4.  
  5. // since eeprom operations are quite slow even for reading, we do want ram cache of values
  6. //   for purpose of configuration switch logic in fast code
  7. // also, we do not want to waste any one of million writes available on a single eeprom device for vain
  8. template <typename T> class eeprom_cell {
  9.   // here T is expected to receive only a single byte type, like byte, char or boolean or possibly some other of their synonyms
  10. private:
  11.   static const int DIRTY_BITMASK = 0x8000 ;  // bit 15 of address represents a dirty state logic
  12.  
  13. public:
  14.   T value;    
  15.   int address;
  16.  
  17.   // construct from eeprom address, unchecked
  18.   eeprom_cell (int cell_address) {
  19.       address = (cell_address);
  20.       load ();
  21.   }
  22.  
  23.   // saves the value into eeprom cell, handily returns a copy of old previous value
  24.   T save (void) {
  25.     address &= EEPROM_SIZE_MASK; // clip the dirty bit
  26.     T ret = EEPROM.read (address);
  27.     EEPROM.write (address, value);
  28.     return ret;
  29.   }
  30.  
  31.   // loads a value from eeprom cell
  32.   T& load (void) {
  33.     address &= EEPROM_SIZE_MASK; // clip the dirty bit
  34.     return value = EEPROM.read (address);
  35.   }
  36.  
  37.   // assignment operator is for good use from outside code
  38.   T& operator= (T& source) {
  39.      address |= DIRTY_BITMASK;  // set the dirty bit flag
  40.      return value = source;
  41.   }
  42.  
  43.   // self invocation is for good use from outside.code, strictly not needed since value is public access. we'll consider the size costs later
  44.   inline T& operator()(void) {
  45.     return value;
  46.   }
  47.  
  48.   // check the dirty state from outside code
  49.   boolean dirty (void) {
  50.      return address & DIRTY_BITMASK ? true : false; // check the dirty bit flag
  51.   }
  52.  
  53.   // there is no destructor, by design. but should it exist in future, it  _shall_ do eeprom writeback on dirty state as well
  54. };
  55.  
  56. // example:
  57. eeprom_cell <boolean> terminal_echo (EEPROM_SIZE-1);  // let's have some boolean value mapped to the last eeprom cell on chip
  58. // since factory default value in eeprom is FF, it's default value is true on freshly programmed device
  59.  
  60. #endif // EEPROM_FEATURES
  61.