SD card read/write with Arduino

I think the way to go is to use the code already present in the libraries. Check out .\hardware\cores\arduino\Print.cpp

This base class provides the 'printing' functionality. Since you're already wearing the cost of the code whenever you use the Serial library it can be used virtually free. All you need to do is provide a subclass which provides a write byte function which puts a byte to the MMC buffer and writes the sector when necessary.

What you get is the ability to write strings using the exact same functions as you'd use for Serial! How cool is that.

As a super bonus, you could interchangeably use the MMC output with the Serial output for testing..

Here's how. (Please forgive typos, I'm away from arduino right now so I can't test)

class MMCWriter : public Print
{
  public:
    void begin( .. )
    {
       // initialise the mmc byte-by-byte writer here
    }

    void flush(void)
    {
       // flush the buffer to the card here
    }

    virtual void write(uint8_t theByte)
    {
       // call the function that puts a byte in the buffer here 
    }
};

MMCWriter MMCio;

void setup(void)
{
  MMCio.begin();
  MMCio.println("Hello! This string will go to the buffer!");
  MMCio.println(123, DEC);
  MMCio.flush();
}

That's it. I'll leave the serial/mmc swaperoo trick for another post (or you could work it out if you've got 5 mins).

There's a huge amount of power in the arduino core - take some time to have an explore and who knows what you might find :slight_smile:

C