The trick you are looking to implement here is the ability to look through the EEPROM and say "This is the last place I wrote to - I will write to the next place now."
There's two ways of doing it, the easy way and the right way.
The easy way is to maintain a single address in the EEPROM that says where you wrote to last. If you are trying to implement some form of wear levelling to extend the life of your EEPROM then this would basically negate it, since that one cell in the EEPROM will wear out before the rest of it and become useless. So it's really not a good idea although it may sound like it at first.
The right way to do it is to store more information in the EEPROM every time. Not only do you need to store the data, but also some kind of identifying sequence number.
Say you have 4 bytes of data to write each time. Add a fifth byte to it. That fifth byte increases by one each time you write. Before you write you scan through the EEPROM looking at every fifth byte looking for the "end" of the sequence.
For instance, you may end up with (
xx is your data bytes) in hexadecimal:
00: 00 xx xx xx xx
05: 01 xx xx xx xx
0A: 02 xx xx xx xx
0F: 03 xx xx xx xx
14: FF FF FF FF FF
You see that at address 0x14 the nice sequence of numbers breaks. Therefore your next write must be at that point. Now, if you then loop through the EEPROM many times after a while, you may end up with something that looks like this:
00: FE xx xx xx xx
05: FF xx xx xx xx
0A: 00 xx xx xx xx
0F: 01 xx xx xx xx
14: 58 xx xx xx xx
You can see a clear sequence here of
0xFE 0xFF 0x01 where they increase by 1 each time (0xFF + 1 = 0x00) so you can see that you have looped through your sequence numbers. You don't care though because it's still just plus one. Only when you get the jump from 0x01 to 0x58 does the sequence break, so you know where the last write would have been.
There are only a couple of small gotchas here:
- You can only use 5*n cells in the EEPROM since the last 5-byte packet of data may not fit within the last bit of EEPROM (say it's a 1024 byte EEPROM you would have room for 204.8 packets - so 204 packets and 4 bytes left over).
- You must ensure that you don't end up with exactly 256 packets fitting in the EEPROM before you loop the address - otherwise the sequence won't "break" so you will never know where the last write was after the first loop.