AceUtils
0.6.0
Useful Arduino utilties which are too small as separate libraries, but complex enough to be shared among multiple projects, and often have external dependencies to other libraries.
|
Save data to EEPROM along with a CRC32 value, and an optional contextId
. When the data is retrieved, the CRC32 is calculated and compared with the expected CRC32. The contextId
is also compared with the expected contextId to verify that the data came from the same application.
The contextId
is a 32-bit identifier that is designed to help collisions between 2 applications which store different data, but with the same size. Since the size of the data is the same, the CRC will be valid, but the 2 applications will certain not have compatible data. The writeWithCrc()
writes this contextId
into the EEPROM, just like the CRC. The readWithCrc()
verifies that the contextId
matches, just like the CRC.
You can generate the contextId
in using any method. I wrote the CrcEeprom::toContextId()
helper function to convert 4-letter sequences (e.g. 'o', 'c', 'l', 'k') into a 32-bit number. But I found it difficult to create new 4-letter combos which don't collide with each other.
I now recommend that you simply use a 32-bit random number generator to get the contextId
. Here are some sources:
$ od -v -An -N4 -t x4 /dev/urandom
$ printf "0x%08x\n" $(($RANDOM * 65536 + $RANDOM))
$RANDOM
is only 15-bits, so this generates only a 30-bit random number instead of 32. This may be good enough for you.$ python3 -c 'import random; print(f"0x{random.randint(0,2**32-1):08x}")
If you don't use
srand()`, you get the same number every time you run this.srand()
within the same second, you will get the same number.A previous version of this used a EepromInterface
pure abstract class that provides a stable API to the CrcEeprom
class. Two subclasses were AvrStyleEeprom
and EspStyleEeprom
. Converting CrcEeprom
to a template class, templatized on AvrStyleEeprom
and EspStyleEeprom
eliminates the virtual function calls, and seems to save between 150 to 950 bytes of flash memory on AVR processors. On small processors, like the ATtiny85, this seemed like an optimization worth making.
The complexity of CrcEeprom<>
has been reduced by creating the following helper classes:
CrcEepromAvr<E>
CrcEepromEsp<E>
New EEPROM implementations can be with with CrcEeprom
by creating a new instance of the EepromInterface
, then using the raw CrcEeprom
template class.