Electronic – arduino – Which library for microSD cards with Arduino

arduinoatmegasd

I'm trying to use a microSD card with an Arduino (ATmega328). I'm using the SPI interface.

I've tried using the Arduino SD wrapper, but whenever I #include the SD.h header file the Arduino continuously resets itself. I think this is a RAM issue and it seems like this is the issue: http://code.google.com/p/sdfatlib/issues/detail?id=15

How would I go about doing this now? What library/method do I use?

Best Answer

Full RAM is almost certainly your problem. You want to keep an extra 200-400 bytes for the stack, depending on your program complexity. I tend to have a large stack, so I keep at least 400 open all the time. If it gets less than that free, it is time to optimize something.

Here is an example to show you how much you have left:

#define RAMSIZE 2048 //You can probably get this from another define somewhere

int availableMemory() {
    int size = RAMSIZE;
    byte *buf;
    while ((buf = (byte *)
        malloc(--size)) == NULL);
    free(buf);
    return size;
}

void chkMem() {
    Serial.print("chkMem free= ");
    Serial.print(availableMemory());
    Serial.print(", memory used=");
    Serial.println(RAMSIZE-availableMemory());
}

Arduino release 0022 has been quite problematic for me. I instead use 0021 and grab fat16lib which is lighter and serves my data logging needs. If you can do without directories, use 8.3 filenames, and SD cards <= 2 GB, it's very helpful and works!

Finally, if you have a lot of string data in your program (like println debugging statements or other long strings, consider accessing those directly from the ATmega328's flash memory, which will also save RAM. I use a convenient library for this purpose, called Flash incidentally. See Flash. I also highly recommend Mikal's Streaming and PString library. The gent writes some really well-thought-out libraries IMHO.

Example using Flash lib:

Serial.print(F("really long debug message "));