Using Checksums

When dealing with the flash memory, it is very often desirable to make sure that the data stored in flash sectors is not corrupted. One way to do so is by calculating the checksum on the sector data and storing this checksum together with the data. Each sector of the flash memory conveniently stores 8 extra bytes on top of the "regular" 256 bytes usually storing the actual data.

The fd. object uses two bytes at offsets 262 and 263 to store the checksum of the first 262 bytes of data residing in the same sector. The checksum is a 16-bit value. When the checksum is correct, the modulo 16 sum of the entire sector's data is zero.

The 16-bit values for these calculations are little-endian. That is, offset 0 of the sector is presumed to be the high byte of the first 16-bit value, offset 1; low byte of the first 16-bit value, offset 2; high byte of the second 16-bit value, and so on.

When you are using file-based access, the fd. object automatically calculates and/or verifies the checksum on all sectors it accesses. Should any sector turn out to contain an invalid checksum, the 2 — PL_FD_STATUS_CHECKSUM_ERR status code is generated.

Direct sector access is more primitive and it is your responsibility to maintain and verify the integrity of data you store in the flash memory. To aid you in this, the fd.checksum method can be used to verify the checksum or calculate and store it into the selected RAM buffer (where the sector's data is supposed to be already loaded):

Tibbo BASIC
'Load sector #10, verify its checksum, alter some data, recalculate the checksum, and save new data
Dim i As word
...
'load the sector
If fd.getsector(10)<>PL_FD_STATUS_OK Then
   'flash failure
End If
 
'verify the checksum
If fd.checksum(PL_FD_CSUM_MODE_VERIFY,i)<>OK Then
   'checksum error detected
End If
 
fd.setbuffer("ABC",20) 'alter data at offset 20
 
fd.checksum(PL_FD_CSUM_MODE_CALCULATE,i) 'recalculate the checksum, save it back into the RAM buffer
 
'save back
If fd.setsector(10)<>PL_FD_STATUS_OK Then
   'flash failure
End If