Dec 28, 2019

eeprom read/write functions

Read and write
one, four-byte variables and character strings
to eeprom in Arduino C++

Create functions for a consistent interface for single and multi-byte variable rd/wr to non-volatile ram using the EEPROM library.


// single byte read
uint8_t eepromReadByte(uint16_t addr) {              
    return EEPROM.read(addr);
}

// single byte write
void eepromWriteByte(uint16_t addr, uint8_t data) {
    EEPROM.update(addr,data);                   // "update" only writes if byte is different
}

// four-byte read
uint32_t eepromReadInt32(uint16_t addr) {
    uint32_t data = 0;
    byte b;
    for (uint8_t i = 0; i < 4; i++) {
        b = EEPROM.read(addr);
        data |= 0x000000FF & (b << 4*i);
        data |= b;
    }
    return data;
}

// four-byte write
void eepromWriteInt32(uint16_t addr, uint32_t data) {
    for (uint8_t i = 0; i < 4; i++) {
        uint8_t aByte = 0x000000FF & (data >> 4*i);
        EEPROM.update(addr+i,aByte); 
    }
}

// write character array 
void eepromWriteChars(uint16_t addr, char str[16], byte num_chars) {
    for (byte i=0; i<num_chars; i++) {
        EEPROM.update(addr+i,str[i]);    
    }
}

Usage:

     eepromWriteByte(ADDR_COUNTDOWN_SECONDS,g_secords);

Initialize EEprom memory: 

Test if memory has been written to;
if yes, read values; else write default values


// update eeprom values
int init_marker = 42;
    if (eepromReadByte(ADDR_EEPROM_INIT) == init_marker) {   // some unique value
        readCountdownIntervalFromEEprom();
    }
    else    {   // first-time init
        eepromWriteByte(ADDR_EEPROM_INIT,  init_marker);
        writeCountdownIntervalToEEprom();   // write defaults
    }
 

No comments: