sparkfun / SparkFun_External_EEPROM_Arduino_Library

An Arduino library for the easy control of external I2C EEPROMs.
Other
54 stars 14 forks source link

Fix multi-page write #18

Closed romain145 closed 1 year ago

romain145 commented 1 year ago

Fix multi-page write calculation for how many bytes need to be written on each page. Also fix a small typo in the comment.

When pageNumber2 is not the next page the calculation returns a value higher than the page size. Instead, use pageNumber1 end and substract the number of bytes already written to that page.

I made this little python scratch file to show the difference before and after the fix:

from math import floor

buffer = []

def write(eepromLocation, dataToWrite, bufferSize):

    pageSize_bytes = 64
    recorded = 0

    print('bufferSize: {}'.format(bufferSize))

    while recorded < bufferSize:
        amtToWriteBad = amtToWrite = bufferSize - recorded
        pageNumber1 = floor((eepromLocation + recorded) / pageSize_bytes)
        print('Page1: {}'.format(pageNumber1))

        pageNumber2f = (eepromLocation + recorded + amtToWrite - 1) / pageSize_bytes
        pageNumber2 = floor(pageNumber2f)
        print('Page2: {}'.format(pageNumber2))

        if pageNumber2 > pageNumber1:
            amtToWriteBad = (pageNumber2 * pageSize_bytes) - (eepromLocation + recorded)
            amtToWrite = ((1+pageNumber1) * pageSize_bytes) - (eepromLocation + recorded)
        print('AddrToWrite: {}, AmtToWrite: {}, amtToWriteBad: {}'
              .format((eepromLocation+recorded), amtToWrite, amtToWriteBad))

        recorded += amtToWrite

write(eepromLocation=10, dataToWrite=buffer, bufferSize=200)

Output:

bufferSize: 200
Page1: 0
Page2: 3
AddrToWrite: 10, AmtToWrite: 54, amtToWriteBad: 182
Page1: 1
Page2: 3
AddrToWrite: 64, AmtToWrite: 64, amtToWriteBad: 128
Page1: 2
Page2: 3
AddrToWrite: 128, AmtToWrite: 64, amtToWriteBad: 64
Page1: 3
Page2: 3
AddrToWrite: 192, AmtToWrite: 18, amtToWriteBad: 18
nseidle commented 1 year ago

Awesome! Thanks!