Arduino writing to an SD card

A common task in the world of datalogging is to store your data on some sort of storage card, the most common kinds being SD and micro SD cards.

There are a couple of ways you can do this by adding an SD card breakout and connecting it to your Arduino or purchasing a shield which has SD card capabilities. We had the shield option at hand here so this example is based on that , the shield used was the Data logging shield and was manufactured by Keyes, there seems to be a few similar shields that can be bought all of which based on a fairly common design. Here is a picture of the shield I used

data logging shield

In the example we will show we write some text to the SD card , you can then remove the SD card from your arduino data logging shield and then you can then open up the file in your operating system by inserting the card. You’ll see one line for each time the sketch has run.

Here are some things to consider regarding writing to SD cards

You can have multiple files open at a time, and you can also write to them as well but you need to close them all as well.
You can use print and println() to write strings, variables for example.
You must close() the file(s) when you’re finished to make sure all the data is written to the file(s).
You can open files in a directory. If you wanted to open a file in a directory such as /temp/latesttemp.txt you simply do the following SD.open(“/temp/latesttemp.txt”).

The following sketch is a basic demo of writing to a file, it uses the built in SD library. It writes to a file called test.txt with some sample data

Code

[codesyntax lang=”cpp”]

#include <SPI.h>
#include <SD.h>


File myFile;

void setup()
{
Serial.begin(9600);
Serial.print("Initializing SD card...");
pinMode(10, OUTPUT);

if (!SD.begin(10)) 
{
Serial.println("initialization failed!");
return;
}
Serial.println("initialization complete.");

//open the file.
myFile = SD.open("test.txt", FILE_WRITE);

//write to file
if (myFile) 
{
Serial.print("Writing to test.txt...");
myFile.println("TESTING : 1,2,3");
//close the file
myFile.close();
Serial.println("done.");
} 
else 
{
// if the file didn't open, print an error:
Serial.println("error opening test.txt file");
}
}

void loop()
{

}

[/codesyntax]
Result

If you remove the SD card and connect it to your PC and locate the test.txt file , now open the file you will see something like the following.

TESTING : 1,2,3
TESTING : 1,2,3
TESTING : 1,2,3

The amount of lines varies depending on how many times the sketch has been run

 

Links
Data Collection Logger Module Recorder Logging Shield for Arduino UNO SD Card

Related posts

Arduino and GY-21P readings on a web page

MPL3115A2 sensor readings displayed on a web page

Adafruit Neopixel shield examples