I'm using Petit FatFS with an Arduino Mega. I've implemented all necessary functions, however I'm having issues with the pf_read()
function. I'm trying to read a file, which is 568 (512 + 56) bytes long. The first sector can be read without a problem (and is correct), but the second partial sector doesn't get read.
I tried debugging pf_read()
and found following: For the first sector it calls disk_readp()
with sector = 41104
, offset = 0
and count = 512
, which seems correct. The second time however, it calls with sector = -538935151
, offset = 512
and count = 56
(at least the count is correct).
Weirdly enough, after pf_read()
is done, *br
is 97
, even though the function has actually read 512 bytes.
Just in case it's an issue with disk_readp()
, here is my code:
DRESULT disk_readp (
BYTE* buff, /* Pointer to the destination object */
DWORD sector, /* Sector number (LBA) */
UINT offset, /* Offset in the sector */
UINT count /* Byte count (bit15:destination) */
)
{
uint8_t r1;
uint8_t res_token;
uint16_t readAttempts;
DRESULT res = RES_ERROR;
CS_HIGH();
spi_transmit(0xFF);
CS_LOW();
spi_transmit(0xFF);
r1 = send_command(CMD17, sector);
if(r1 != 0xFF)
{
readAttempts = 0;
while(++readAttempts != SD_MAX_READ_ATTEMPTS)
{
if((res_token = spi_transmit(0xFF)) != 0xFF) break;
}
if(res_token == 0xFE)
{
// read 512 byte block
for(uint16_t i = 0; i < offset; i++) {
spi_transmit(0xFF); // discard data from (0) to (offset)
}
for(uint16_t i = offset; i < offset + count; i++)
{
*(buff++) = spi_transmit(0xFF); // safe data from (offset) to (offset + count)
}
for(uint16_t i = offset + count; i < 512; i++) {
spi_transmit(0xFF); // discard data from (offset + count) to (512)
}
// read and ignore 16-bit CRC
spi_transmit(0xFF);
spi_transmit(0xFF);
res = RES_OK;
}
}
CS_LOW();
spi_transmit(0xFF);
CS_HIGH();
spi_transmit(0xFF);
return res;
}
And the link to the Petit FatFS documentation: http://elm-chan.org/fsw/ff/00index_p.html
Thanks!