Ahmed Saleh Ahmed Saleh - 2 months ago 8
C Question

Reading from EEPROM, and knowing that its not written at the start up

I write a structure into EEPRM as follows

typedef struct
{
fract32 AmpF; // amplitude fundamental
fract32 AmpH; // amplitude harmonic
UINT32 b;
UINT16 d;
UINT16 crc;

}CoilBoardAmp_T;

// mechanic angles and salt water angles of coil stored in coil-eeprom
typedef struct
{
ChannelData_T channel[NUM_CHANNELS];
CoilBoard_T coilboard;
CoilBoardAmp_T coil_h;
CoilBoardAmp_T coil_d;
// UINT32 gCoilSerialNumber;
// UINT32 gInversSerialNumber;
} Coil_Eeprom_Data_T;


I set that data by a software, which writes to that structure.

The problem is when reading that structure at the first time without writing to it, I read false data.

I need to detect that point. How would I know If the data that is read is false, or how would I know that I read the data without the software.

Answer

You can add a checksum or CRC at the end of your structure, which is calculated on all the structure's members.

When you write the data to the EEPROM you calculate the value of the checksum and write it. When you read the data from the EEPROM, you calculate the checksum of this data and compare it with the checksum of the data you've just read, and if it does match it means (with a high probability) that your data is correct.

Basically if we represent your structure in memory :

byte |0 1 2 3|4 5 6 7|8 9 10 11|12 13|14 15|
       AmpF    AmpH      b        d    CRC

Then the 2-bytes CRC could be calculated like this :

CRC = (AmpF<<2) + (AmpF & 0x00FF) 
    + (AmpH<<2) + (AmpH & 0x00FF) 
    + (h<<2)    + (h & 0x00FF) 
    + d;

Which could obviously be optimized with a for loop. I'm quite sure there are examples on the 'Net but an idea would be to go from the address of your structure to this address + sizeof(struct) - sizeof(CRC) by steps of 2 bytes.

Internet is full of implementations for checksums and CRCs that go from extremely simple to very complicated, depending on what you want to achieve and your system capabilities, but basically a simple checksum is just the addition of all the bytes in your data structure.

A simple checksum like the one I gave as an example only detects wrong bits in your data, you wouldn't detect if two values are swapped, e.g. AmpF and AmpH.

Note that though checksums and CRCs are a different thing, both terms are often used to designate the other.