Simple checksum for word in eeprom

Thread Starter

AlbertHall

Joined Jun 4, 2014
12,116
I will be storing a word (uint16_t) in eeprom. It will be rarely changed and read at the start of running of the program code. Time or space are not limiting factors.
Is the code below correct and effective for this purpose?

(XC8 and MPLABX)

Code:
uint16_t EepromRead16(uint8_t Address)
{
    uint8_t LS;
    uint8_t MS;
    uint8_t Sum;
   
    MS = eeprom_read(Address);
    LS = eeprom_read(Address + 1);
    Sum = eeprom_read(Address + 2);
    if(MS + LS == Sum)
        return (uint16_t)(MS << 8) + LS;
    else
        return 0;
}

void EepromWrite16(uint8_t Address, uint16_t Value)
{
    uint8_t LS;
    uint8_t MS;
    uint8_t Sum;
   
    LS = Value & 0xFF;
    MS = Value >> 8;
    Sum = LS + MS;
    eeprom_write(Address, MS);
    eeprom_write(Address + 1, LS);
    eeprom_write(Address + 2, Sum);
}
 

mckenney

Joined Nov 10, 2018
125
This particular checksum has the weakness that if the EEPROM is erased to all-0s the checksum will pass. 0x00 and 0xFF are perhaps the most common failure modes.

Two very cheap/simple improvements are
1) inversion (~(MS+LS)) and/or
2) a seed: (MS+LS+SEED), just pick a seed like 0xAA or something (probably not 0x00 or 0xFF).

Phil Koopman at CMU did a fair amount of study of checksums and CRCs, including metrics for better vs worse, with an occasional nod to "cheap/simple". I suspect this is more depth than you want to take on today but here's a link anyway:

https://users.ece.cmu.edu/~koopman/projects.html#crc
 
Top