Changing just one byte in SD card sector

1.2k views Asked by At

I'm implementing FAT16 on SD card with Atmega328.

I often need to change just one or two bytes in the sector (512B region).

I know how Flash works and that it needs to overwrite entire sector at once, but I was wondering if there maybe was some special command that would make the card itself handle it?

The point is, the atmega has only 2k RAM, and allocating 512 just for a read-modify-write SD card buffer is very unfavorable. Is there no other way?

(PS. AFAIK the atmega can't natively have external ram)

2

There are 2 answers

0
too honest for this site On BEST ANSWER

YOu cannot changge just few bytes in a sector without reading/writing the the whole 512 bytes. So you actually do need the RAM for buffer.

However, there are ways to pre-alloc the filespace or update the FAT every some writes only. That will even conserve write cycles, but might result in data loss if power down before the FAT has been updated (however, it might not corrupt the filesystem if implemented properly).

As you state that these are cheap ArduinoNano (clones - supposedly), you could just use two of them interconnected with UART/SPI/i2C - whatever is available, even 8 bit bit-bang would work.

One does whateveryouwanttodo and the other is just for SD-card/FAT processing.

Reminds me of the Comodore 64 and its floppy-disc drive 1541 which also included a small CPU (well "MCU", but not single chip).

6
Clifford On

ELM Petit FAT File System Module claims:

It can be incorporated into the tiny microcontrollers with limited memory even if the RAM size is less than sector size.

In fact:

  • Very small RAM consumption (44 bytes work area + certain stack).

It is open source; so you might take a look at how it does that (or just use it as-is).

The write function does have some significant restrictions, such as while it can modify a file, it cannot create or change the size of one - which is probably the compromise necessary to avoid sector buffers.

There is a full featured version of ELM FatFS, but that requires significantly more code and RAM space. The page also has links to the FAT32 specification, and some technical notes on how SD cards work which might be useful.

EDIT:

In fact this is not particularly helpful. Petit FAT's claim refers only to the filesystem layer itself, it does not include any hardware specific device driver, and for SD/MMC there is no getting away from the 512 byte read-modify-write cycle.

Although the AVR may not support memory-mapped external memory, one could use an external serial memory device such as a Cypress FRAM or nvSRAM to store the sector data; although being non-volatile, it may remove the need for SD altogether unless large removable media is specifically required.