BLOG > Tutorial 11 for Arduino: SD Cards and Datalogging

This is my first in a series of more advanced Arduino tutorials. Now that we’ve covered the basics in tutorials 1-10 (you have watched them all right!?), it’s time to start pursuing some more complex projects!  In this episode, we’ll utilize an SD card shield from to create a datalogger.  First, I’ll walk you through the process of reading from, and writing to an SD card.  Then, we’ll utilize some of our knowledge from tutorials 4, 6, 7, and 8 to add several sensors that we can poll periodically using our datalogger.  The logger will record sensor values to its SD card in a useful format so that we can later use a computer program like Microsoft Excel to visualize the data.  Download the schematics and source code first so you can reference them while you watch the video.  For the first time, I’m using fritzing to draw the circuit schematics.  So, take a look at them, and let me know what you think!


You can download the files associated with this episode here:

GNU GPL License Distributed under the GNU General Public (Open-Source) License.
Please Attribute and Share-Alike.


  1. Hi there Jeremy

    Just wanted to say that I loved the tutorial you made, really helpful, I had already bought a freeduino and knew some arduino stuff but needed I2C communication, that how i found your tutorials. Just to give you some relative info, I’m studying mechatronics at CPUT in south africa and Im busy on a final year unmanned ground vehicle that can climb stairs and feedback sensor data to the user via a remote desktop. I dnt know if you’ve heard of a roboard, but its an incredible piece of engineering and you should look at it if you can.

    Thanks again, please keep the tutorials coming

  2. Great tutorial! Thank you. You are doing a very good job. I am working on my own data logger but I have some trouble with the library. You mentioned making a tutorial on it. It would be awesome! Looking forward to your next tutorial. Greetings Norway

  3. Fantastic work Jeremy. Real examples help so much.
    I have a question, if you can spare the time. I would like to record data to a .csv as shown, but only if a digital line changes state (Low>High). Would the Arduino have enough processing power to transfer data to SD at say 500 lines/second? I would be recording RTC data and one Analog input, plus controlling a two digital outputs at a user determined point.

    1. The atmega runs at 8MHz if I recall correctly, so it should be possible to record tat that speed. But, it might be possible to do it with the arduino programming language. Programming in C or assembly would give you much more overhead to capture data at that speed.

  4. I wrote the library name inside angle brackets, but somehow it disappeared. There is probably some kind of html trim going on. Anyways, I was talking about the Time.h library. I think you mentioned making a tutorial on how to track date and time too. That would be great!

  5. Hi nice blog and nice tutorials…..
    i’m SD data logging with my arduino uno.. I’m using onewire dallas 18B20 temperature sensor.. arduino compiler shows some error..can u de bug it plaease…..can i have ur email id or tell me how can i send the code i used in this….

  6. I enjoy your tutorial. Will you have a vedio on using Arduino with an AHRS such as Sparkfun 9 Degrees of Freedom – Razor IMU or a similar product?

    1. I wasn’t planning on it. You generally just communicate with those via SPI, or by reading analog values – so its been covered by my other videos.

  7. These are extremely valuable lessons. I cannot wait for your next video on interfacing a GPS. Do you han any plan to have a video on filters as you mentioned in your lesson five (servo motors)?

  8. Hi nice and very valuable work…
    Im a beginner with Arduino and your tutorial helps a lot, keep up the good work.
    And for my project i need to control two 12v dc motor,
    They should rotate in both directions and stopped, i thought of using two DPDT relays to change the polarity to change the motors rotation and another two SPST relays to stop the motors, but im little confused about connecting and controlling the relays by Arduino, could you help me in this problem?

  9. hey a wonderful way to put things down … was wondering if i cud get a schematic on the sd card module ( making in wud cost a lot less u guess )
    thnak you

  10. hi.. Thanks for the tutorials.. Its very useful to me..
    i have question for you..
    I am now currently studying about RTOS for my final project.
    Can arduino IDE use RTOS kernel, like freeRTOS?
    then how if this project implemented with RTOS??

    thank you..

    1. No, RTOS does not support 8 bit Atmega processors – they list the compatible architectures on their website. The arduino is not nearly powerful enough

        1. No I haven’t the Arduino is not a high-powered computing device. It’s important to be aware of it’s limitations as well as its strengths.

  11. Hi Jeremy,
    Great series! I really enjoy watching them.
    I have a question you might know the anwer to. I want to make a device the measure the rising of dough at different temperature. I was planning to put the dough in container with straight walls and just measure, from above, the distance to the dough. I come across two types of distant sensors, ultrasonic and IR. Which one would you think to have the highest sensitivity? They are about equally priced.

    Regards, Rutger

    1. IR is probably better for this, but they would both work ok. Just be away that both sensors have a dead zone if you get too close to them, so be sure to position accordingly.

  12. Hi Jeremy, great blog!

    I am trying to append a float (temperature) to a dataString and writing that to an SD card on my Arduino. The compiler is giving the following error: call of overloaded ‘String(float&)’ is ambiguous.

    The offending line of code is: dataString += String(temperature);

    Was wondering if you could suggest a straight forward or easy to understand solution for a non-programmer. Thanks!

  13. Jeremy,
    Fantastic tutorials!

    Why did you use the cooking-hacks SD shield? The price in the US is twice what is charged by Sparkfun.

  14. I’m curious to know if I could implement this. However, instead of removing the SD card and putting it into my computer, I would like to transfer the data off of the SD card using one of the wireless shields. Is that even possible? At least with an appreciable amount of speed? A 24 hour log file (at a higher sampling rate, say 250 samples/s) would create a 100+MB file I believe.

    1. It’s probably be possible, but you definitely wouldn’t want to do it with something like an XBee – It would be too slow. It may be more feasible with wifi…

  15. Sample rate @ 250 samples/s = 4 milliseconds between samples. If each sample was a single byte and the serial transmission protocol required 10 bits of transmission per byte, the theoretical transmission rate required would be 2500 bits per second. Figuring in the real capacity of a radio link, practically you would want 19200 bps rate or higher. At that speed, you would not need the SD card except to buffer when the radio link was not functional.

  16. .,hello..can you make a tutorial combining the analog inputs like using ir sensor and then sending the value to a gsm phone via sony ericsson as a modem?..

  17. Hi Jeremy,
    Your videos are fantastic. They have helped me a lot. I am myself working on a small Arduino project and occasionally have difficulties.

    I was wondering if you could shed some light on this.
    I am using the microSD card on the official Arduino ethernet shield to store some time data and temp data. I have setup a website in php/javascript to display temp-time graph from a text file. It works from any remote location such as . But it doesnt read from the ethernet sd card which is something like 179.xx.xx.x/data.txt.

    And on a different and probably complex topic. Is it possible to analyse the input data in real-time and send an email if the data point meets a certain condition?

    Once again, keep up the good work.

  18. hi im beginner in arduino. this is nice blog and nice tutorial. u helps me lots on many ways. here i have a little bit question on arduino with data logger. its that ur data logger program compatible with arduino ethernet? and how to program ethernet with LM35Dz temperature sensor. hope u will helping me.. tq jeremy

  19. Hi!

    Great tutorials! I watched some of them and they are just great!!

    Just a comment, in case it can help. When you read the number from the file, you convert it from string to integer. That way is ok, but, wouldn`t it be easier if you did

    refresh_rate = 0;
    while (commandFile.available())
    float temp = ( – ‘0’);
    refresh_rate = refresh_rate*10 + temp;

    I think this would work as well, and you don’t have to figure out the number of digits and so on…

    Again, great tutorials! Thanks,

    Paco Lacon

  20. Hi,Can you please give example on how to get data on a sd card file with .csv extension and add the value as a beginning value to be incremented from a pulse sensor.I have already set up my arduino and it has already writing data to the sd,but everytime arduino restart the pulse (ReadingTotal1 and ReadingTotal2) total reset to zero.
    my Sd file look like this (Data.csv)


    I just want to get the last values (when arduino restart) of TotalReading1 which is 510.50 and TotalReading2 which is 151 as a beginning value to be increment again when the pulse sensor reads some signal

  21. Saved my life with this tutorial, best i’ve seen on SD card use and was desperately needed to help finish an assignment and get my head round the basic functions. studying for a degree and working avg 45 hour week is not good :)
    cheers, keep the tutorials coming.

    1. me too.. here’s my code for sampling time greater than seconds, its every 6 min

      #include “RTClib.h”

      // A simple data logger for the Arduino analog pins

      // how many milliseconds between grabbing data and logging it. 1000 ms is once a second
      #define LOG_INTERVAL 360000 // mills between entries (reduce to take more/faster data)
      // 3600000 is every 6 minutes
      // how many milliseconds before writing the logged data permanently to disk
      // set it to the LOG_INTERVAL to write each time (safest)
      // set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
      // the last 10 reads if power is lost but it uses less power and is much faster!
      #define SYNC_INTERVAL 360000 // mills between calls to flush() – to write data to the card
      // 3600000 is every 6 minutes
      uint32_t syncTime = 0; // time of last sync()

      #define ECHO_TO_SERIAL 1 // echo data to serial port
      #define WAIT_TO_START 0 // Wait for serial input in setup()

      // the digital pins that connect to the LEDs
      #define redLEDpin 2
      #define greenLEDpin 3

      // The analog pins that connect to the sensors
      #define photocellPin 0 // analog 0
      #define tempPin 1 // analog 1
      #define BANDGAPREF 14 // special indicator that we want to measure the bandgap

      #define aref_voltage 3.3 // we tie 3.3V to ARef and measure it with a multimeter!
      #define bandgap_voltage 1.1 // this is not super guaranteed but its not -too- off

      RTC_DS1307 RTC; // define the Real Time Clock object

      // for the data logging shield, we use digital pin 10 for the SD cs line
      const int chipSelect = 10;

      // the logging file
      File logfile;

      void error(char *str)
      Serial.print(“error: “);

      // red LED indicates error
      digitalWrite(redLEDpin, HIGH);


      void setup(void)

      // use debugging LEDs
      pinMode(redLEDpin, OUTPUT);
      pinMode(greenLEDpin, OUTPUT);

      #if WAIT_TO_START
      Serial.println(“Type any character to start”);
      while (!Serial.available());
      #endif //WAIT_TO_START

      // initialize the SD card
      Serial.print(“Initializing SD card…”);
      // make sure that the default chip select pin is set to
      // output, even if you don’t use it:
      pinMode(10, OUTPUT);

      // see if the card is present and can be initialized:
      if (!SD.begin(chipSelect)) {
      error(“Card failed, or not present”);
      Serial.println(“card initialized.”);

      // create a new file
      char filename[] = “LOGGER00.CSV”;
      for (uint8_t i = 0; i < 100; i++) {
      filename[6] = i/10 + '0';
      filename[7] = i%10 + '0';
      if (! SD.exists(filename)) {
      // only open a new file if it doesn't exist
      logfile =, FILE_WRITE);
      break; // leave the loop!

      if (! logfile) {
      error("couldnt create file");

      Serial.print("Logging to: ");

      // connect to RTC
      if (!RTC.begin()) {
      logfile.println("RTC failed");
      #if ECHO_TO_SERIAL
      Serial.println("RTC failed");
      #endif //ECHO_TO_SERIAL

      #if ECHO_TO_SERIAL

      #endif //ECHO_TO_SERIAL

      // If you want to set the aref to something other than 5v

      void loop(void)
      DateTime now;

      // delay for the amount of time we want between readings
      delay((LOG_INTERVAL -1) – (millis() % LOG_INTERVAL));

      digitalWrite(greenLEDpin, HIGH);

      // log milliseconds since starting
      uint32_t m = millis();
      //logfile.print(m); // milliseconds since start
      //logfile.print(", ");
      #if ECHO_TO_SERIAL
      //Serial.print(m); // milliseconds since start
      // Serial.print(", ");

      // fetch the time
      now =;
      // log time
      //logfile.print(now.unixtime()); // seconds since 1/1/1970
      //logfile.print(", ");
      logfile.print(now.year(), DEC);
      logfile.print(now.month(), DEC);
      logfile.print(, DEC);
      logfile.print(" ");
      logfile.print(now.hour(), DEC);
      logfile.print(now.minute(), DEC);
      logfile.print(now.second(), DEC);
      #if ECHO_TO_SERIAL
      //Serial.print(now.unixtime()); // seconds since 1/1/1970
      //Serial.print(", ");
      Serial.print(now.year(), DEC);
      Serial.print(now.month(), DEC);
      Serial.print(, DEC);
      Serial.print(" ");
      Serial.print(now.hour(), DEC);
      Serial.print(now.minute(), DEC);
      Serial.print(now.second(), DEC);
      #endif //ECHO_TO_SERIAL

      int photocellReading = analogRead(photocellPin);

      int tempReading = analogRead(tempPin);

      // converting that reading to voltage, for 3.3v arduino use 3.3, for 5.0, use 5.0
      float voltage = tempReading * aref_voltage / 1024;
      float temperatureC = (voltage – 0.5) * 100 ;
      float temperatureF = (temperatureC * 9 / 5) + 32;

      // logfile.print(", ");
      // logfile.print(photocellReading);
      logfile.print(", ");
      #if ECHO_TO_SERIAL
      // Serial.print(", ");
      // Serial.print(photocellReading);
      Serial.print(", ");
      #endif //ECHO_TO_SERIAL

      // Log the estimated 'VCC' voltage by measuring the internal 1.1v ref
      int refReading = analogRead(BANDGAPREF);
      float supplyvoltage = (bandgap_voltage * 1024) / refReading;

      //logfile.print(", ");
      #if ECHO_TO_SERIAL
      //Serial.print(", ");
      #endif // ECHO_TO_SERIAL

      #if ECHO_TO_SERIAL
      #endif // ECHO_TO_SERIAL

      digitalWrite(greenLEDpin, LOW);

      // Now we write data to disk! Don't sync too often – requires 2048 bytes of I/O to SD card
      // which uses a bunch of power and takes time
      if ((millis() – syncTime) < SYNC_INTERVAL) return;
      syncTime = millis();

      // blink LED to show we are syncing data to the card & updating FAT!
      digitalWrite(redLEDpin, HIGH);
      digitalWrite(redLEDpin, LOW);


  22. if I do not use the arduino shield sd recognizes that not connected sd, but if the shield is not load because it says nothing on the screen of serial communication is blank

  23. Looking forward for your next tutorial. Very exciting indeed. My request if you could create tutorial on controling motor using PS2 controller. Very appreciate your contribution. Thanks.

  24. Hey Jeremy,

    I successfully was able to use both your write and read/write examples at one point..I then attempted to do the data logger example with a potentiometer feeding into one analog input…the attempt was unsuccessful. The problem is now when I attempt to revert back to the first example (print Hello) I am getting a card failure and could not open log file it possible to fry the microSD card?

  25. Hello,

    I run Arduino 1.0 on Windows 7 SP1 and tried to run the programs that are in the download pack of this episode. The SD_Read and SD_Read_and_Write run fine (by run I mean that I hit the “Verify” button to start compiling the code). When I try to run the Datalogger.pde, it first “complains” that Wire.send and Wire.receive are now called Wire.write and, respectively. Then I corrected that and tried Verify again.

    Now the line “Wire.write(0); //Ask for Register Zero” is marked in yellow, the line at the bottom turns orange and reads “call of overloaded ‘write(int)’ is ambiguous”.

    Below it reads:
    ” datalogger.cpp: In function ‘void loop()’:
    datalogger:98: error: call of overloaded ‘write(int)’ is ambigous
    D:\arduino-1.0\libraries\Wire/Wire.h:55: note: candidates are: virtual size_t TwoWire::write(uint8_t)
    D:\arduino-1.0\hardware\arduino\cores\arduino/Print.h:49: note: size_t Print::write(const char*)”

    My Arduino 1.0 is the standard unpack, but I also included the OneWire and TinyGPS libraries. At the Time of compiling, I had “Arduino Mega 2560 or Mega ADK” selected in Tools->Board.

    PS: Which pins are used for the SD card on a Mega 2560?

  26. i want to send the data on the Sd card via a cellular network maybe the arduino cellular sheild can this be done?

  27. Hi jeremy I`m having a little problem with my datalogger. The problem is that when I read from the serial port it only logs 2 lines, then appears some random symbols and I dont know how to solve it, can you help me with?


    #define LOG_INTERVAL 2000 //intervalos de medicion para el guardado de datos
    #define ECHO_TO_SERIAL 1 //datos al serial port, cada una medicion guardada, uueniada al serial port
    #define WAIT_TO_START 0 // hay que darle un comando aaduino para que empieze a tomar datos, solo basta oprimir una tecla

    #define tempPin1 0 //sensores de temperatura añadidos a los pines analogicos 0,1,2,3 y 4
    #define tempPin2 1
    #define tempPin3 2
    #define tempPin4 3

    const int CS_Pin = 10;
    File logfile;
    long id = 1;

    void error(char *str)

    void setup(void)

    if(WAIT_TO_START == 1) {
    Serial.print(“Pulse cualquier tecla para Iniciar”);
    while (!Serial.available());

    Serial.print(“Iniciando SD”);
    pinMode(CS_Pin, OUTPUT);

    if (!SD.begin(CS_Pin)) {
    Serial.println(“Error en la tarjeta o no esta colocada”);
    Serial.println(“SD OK”);

    File logFile =“LOG.csv”, FILE_WRITE);
    if (logFile)
    logFile.println(“, , , ,”); //Just a leading blank line, incase there was previous data
    String header = “ID, Light, Temp, IR1, IR2”;
    Serial.println(“Couldn’t open log file”);


    void loop ()
    int tempReading1 = analogRead(tempPin1);
    int tempReading2 = analogRead(tempPin2);
    int tempReading3 = analogRead(tempPin3);
    int tempReading4 = analogRead(tempPin4);

    float voltage1 = tempReading1 * 5.0 / 1024.0;
    int temperatureC1 = (voltage1 – 0.5) * 100;

    float voltage2 = tempReading2 * 5.0 / 1024.0;
    int temperatureC2 = (voltage2 – 0.5) * 100;

    float voltage3 = tempReading3 * 5.0 / 1024.0;
    int temperatureC3 = (voltage3 – 0.5) * 100;

    float voltage4 = tempReading4 * 5.0 / 1024.0;
    int temperatureC4 = (voltage4 – 0.5) * 100;

    String dataString = String(id) + “, ” + String(temperatureC1) + “, ” + String(temperatureC2) + “, ” + String(temperatureC3) + “, ” + String(temperatureC4);

    File logFile =“LOG.csv”, FILE_WRITE);
    if (logFile)
    Serial.println(“Couldn’t open log file”);

    //Increment ID number


    1. what arduino do you use for it???
      I do something like that, I use Arduino uno SMD edition and I have the same problem

  28. Hi there Jeremy

    I try to build this circuit but I have this Temperature Sensor (DFRobot LM35 Linear Temperature Sensor) That I can do to Arduiono Mega 2560.

  29. Hi!!!
    Somebody have some problem with arduino uno smd edition???
    I can do any program greater than 12000 bytes becuse the arduino finish hanging… Please some help

  30. Quick and I’m sure simple question.

    Hoping to use the data logger code for recording air pressure readings on a pneumatic system for cylinder testing. After the program opens the file, writes a line and closes the file, does the next command to write to the file, put the new information on the next line or does it overwrite the first line?

    Wouldn’t be much of a datalogger if it could only remember one line at a time, but I’m not fully grasping a portion of the code that would stop it from over writing the previous entry.

  31. Hello,

    I want communicate to Arduino using Wireless SD Shield+RN XV. But I do not know which library to use and how to use. Can anybody please help me out.

    Thanks in advance

  32. Hello there jeremy.
    Great job once again

    i used your code here for my datalogger. I have followed it correctly. The one thing i want to do in my datalogger is that it will log a reading from a sensor. It’s like a door that when one passes by a voltage reading will be log and if no one passes by the arduino will do nothing. I hope i can get an idea from you. If Im correct this logger here continuously log whatever reading the sensor is getting so there will be a lot of data being stored.


  33. I have a question…

    What is your area of specialty (Academically I mean)?

    digital, analog or solid state (i don’t think so..), communication, controls,??

    I am just curious :-)

    And BTW I am learning a lot from you thx a ton

    1. I didn’t have “declared” specialty – I basically dabbled in a lot of things. My main areas of focus are embedded systems, human-computer interaction design, robotics, and sustainable energy systems.

  34. Hello, Jeremy. I found your tutorial kinda helpful, so thanks for that. Anyway, I wanna ask, how about we make the datalogging in online? In other words, how can I store data from Arduino to database such XAMPP or MySQL? Thanks

  35. Hello,
    Just wanted to say that this was a very helpful recourse. Thanks so much for sharing your knowledge.

    I just wanted to point out that I was having issues (and other might have experienced the same thing) with the data periodically stopping for no apparent reason. I looked it up and some forums said there was “memory loss” problems the the ‘string’ command was known for. A work around is this:
    I was logging ID, X, Y, Z for an accelerometer (BMA180).

    Instead of:
    String dataString = String(ID) + “, ” + String(x) + “, ” + String(y) + “, ” + String(z);

    //Open a file to write to
    //Only one file can be open at a time
    File logFile =“LOG.csv”, FILE_WRITE);
    if (logFile)
    Serial.println(“Couldn’t open log file”);

    //Increment ID number


    File logFile =“LOG.csv”, FILE_WRITE);
    if (logFile)
    Serial.println(“Couldn’t open log file”);

    //Increment ID number

    Ive had no issues now.

    Again Thanks!!

  36. Hello,

    I was wondering if it’s possible to read char/strings from the SD card as opposed to just numbers. I’ve searched everywhere for this, but numbers seem to be the only thing. How might I go about grabbing words from a text file on the SD card?

    Thanks for posting this.

  37. Hello, Jeremy.
    I have a logprogram that writes to SD-memory every hour.
    But when I take out the SD-memory to copy into my computer and then put it back in the arduino no new data is written to the SD-memory and no error message.
    How can I solve this?

  38. hi jeremy. i used your code here for mine. I have developed a datalogger for a counter sensor. it works perfectly however even when there is no one being sensed the program logs it. so lots of unimportant data are being logged in the excel file. got any idea thanks?

    it is like.
    counter sensed: 1 then

    1 it must be:
    1 1
    1 2
    1 3
    1 4

  39. Goal is to put together a temp- humidity-radiance system like the one you did at CU.

    parts (1) TI MSP430 eZ430-RF2500 Development tool, 1 ea
    (2) TI MSP430 Value Line Launch Pad Development tool, 2 ea
    (3) adafruit DHT22 temp-humidity sensor

    2 questions
    A. Do I have the right parts?
    B. Am PC disabled… Is there a way for a MAC person to read the discs or downloads?

  40. I am trying to write to a parallax 27937 using the spi code in the arduino library. It doesn’t work at all, is there something in my circuitry that i’m missing. I checked all the wiring and changed my miso and mosi to make sure I had them in correctly still nothing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.