Greenhouse: trust only good settings
Decide at start-up whether the settings read back from EEPROM can be used. A medium embedded C problem (Checksums and CRCs), run and graded in the browser.
medium · Checksums and CRCs · crc · validation · eeprom · product
Product: Smart greenhouse controller (Agriculture)
Requirement. After any power cut the controller restores the grower's settings, and it never waters by a corrupted or blank record.
The record is 4 bytes in EEPROM: version, water_below, a reserved byte, and a CRC-8 of the first three (crc8(rec, 3) is provided). It can be used only if:
- its CRC matches,
- its version is 1 (older layouts are not understood), and
water_belowis from 10 to 60.
Return whether the record is valid.
Starter code
bool settings_valid(const uint8_t rec[4]) {
return rec[3] == crc8(rec, 4);
}Example tests
A good record and blank EEPROM
uint8_t good[4] = { 1, 30, 0, 0 };
good[3] = crc8(good, 3);
uint8_t blank[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
printf("%d %d\n", settings_valid(good), settings_valid(blank));Expected output:
1 0One flipped bit
uint8_t rec[4] = { 1, 30, 0, 0 };
rec[3] = crc8(rec, 3);
rec[1] ^= 0x04;
printf("%d\n", settings_valid(rec));Expected output:
0Learn it first
- Checksums and CRCs · Detecting corruption: sums versus CRCs, CRC parameters, tables and protecting stored records.
More Checksums and CRCs problems
- CRC-32 · Compute the CRC-32 used by Ethernet, zip and PNG, bit by bit.
- A table-driven CRC-16 · Build a 256-entry table once, then compute CRC-16/CCITT a byte at a time.
- Load the newest valid settings · Choose between two settings records by magic, CRC and a wrapping sequence number.
- Fix: the receiver rejects some frames · The checksum covers one byte too many.
- Fix: our CRC matches the wrong tool · A CRC-16 routine has the right polynomial and the wrong initial value.