Writing CSV files to an SD Card with An Arduino.


The use of the SD Card reader is well documented on the Internet and I have found the sketch shown here to work well in a number of data logging projects I have built. This is just an outline sketch and should be modified to meet your needs.

I save the file in CSV format so that it can be imported into a spreadsheet program like Excel. The CSV format is just a text file containing data separated by ‘commas’ to produce ‘columns’ of data. A new ‘row’ is formed by adding a CR/LF character (this can be achieved by using file.println(datastring);

Writing Sensor Data to an SD card
This example shows how to write data
to an SD card using the SD library.

The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 10 Uno (53 on Mega)

Based on code by Tom Igoe
#include "SD.h"
//the hardware CS pin (10 on most Arduino boards,
// 53 on the Mega) must be left as an output or the SD
// library functions will not work.
const int CSpin = 10;
String dataString =""; // holds the data to be written to the SD card
float sensorReading1 = 0.00; // value read from your first sensor
float sensorReading2 = 0.00; // value read from your second sensor
float sensorReading3 = 0.00; // value read from your third sensor
File sensorData;
void setup()
// Open serial communications
Serial.print("Initializing SD card...");
pinMode(CSpin, OUTPUT);
// see if the card is present and can be initialized:
if (!SD.begin(CSpin)) {
Serial.println("Card failed, or not present");
// don't do anything more:
Serial.println("card initialized.");
void loop(){
// build the data string
dataString = String(sensorReading1) + "," + String(sensorReading2) + "," + String(sensorReading3); // convert to CSV
saveData(); // save to SD card
delay(60000); // delay before next write to SD Card, adjust as required
void saveData(){
if(SD.exists("data.csv")){ // check the card is still there
// now append new data file
sensorData = SD.open("data.csv", FILE_WRITE);
if (sensorData){
sensorData.close(); // close the file
Serial.println("Error writing to file !");


One thought on “Writing CSV files to an SD Card with An Arduino.”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: