Write data on a SD card with Arduino (MicroSD module and Ethernet Shield)

Today I have been testing a module for Arduino that I had bought on Ebay and I also tried the Micro SD reader located in Arduino’s Ethernet Shield. To do this I made a simple code that writes every 5s the value of a potentiometer connected to the Arduino board in a file called “VALORPOT.TXT” (If this file doesn’t exist It is created and if It already exist the data is added after the existing one).

The program with corresponding explanations (comments in the code) is the following:

// Write data on a SD card with Arduino - Datalogger http://zygzax.com/?lang=en
//We include the SD library.
#include <SD.h>
// We store in what Arduino input the pin CS of the module is connected.
const int chipSelect = 4;
void setup(){
// We set up the serial port to send error messages through It.
Serial.begin(9600);
// The default CS pin of the Arduino board must be configured as an output
// even when not used (10 in most of the boards, 53 in Arduino Mega).
pinMode(10, OUTPUT);
// If there has been an error reading the SD card we send a message through the serial port.
if (!SD.begin(chipSelect)){
Serial.println("Error reading the SD card.");
return;
}
}
void loop(){
// We create the variable where will store the value of the potentiometer.
int pot=0;
// We read the potentiometer value.
pot=analogRead(0);
// We open the file where we will store the data (if It doesn’t exist It is automatically created).
File dataFile = SD.open("valorpot.txt", FILE_WRITE);
// If the file is correct we write on It.
if (dataFile) {
// We write on the file "POT: "
dataFile.print("POT: ");
// Then we write the value of the variable pot and we jump to the next line.
dataFile.println(pot);
dataFile.println("-----5s-----");
// We close the file.
dataFile.close();
// We send a message through the serial port if we could write data correctly.
Serial.println("Correct writing.");
// If we could not write on the file we send an error message through the serial port.
}else{
Serial.println("Error writing on valorpot.txt");
}
// We wait 5s to take the next step.
delay(5000);
}

In the SD card a file called VALORPOT.TXT will be created whose content will look like this:

POT: 443
—–5s—–
POT: 478
—–5s—–
POT: 892
—–5s—–

In the next post I will explain how to read data from a SD with Arduino.