Arduino data logging to SD card

Photo of author

By Jackson Taylor

Home » Arduino » Arduino data logging to SD card

As an Amazon Associate we earn from qualifying purchases.

When it comes to collecting data for various applications, the Arduino platform is one of the most versatile options available. By adding an SD card to your Arduino project, you can store data such as sensor readings, timestamps, or measurements for future use. This guide walks you through the process of data logging using Arduino and an SD card.

What is Arduino Data Logging?

Arduino data logging involves recording sensor data or other variables, and saving them for later analysis. An Arduino, equipped with sensors and an SD card module, can capture information and write it directly to the SD card. The data saved on the card can then be retrieved for processing or visualization, making it an invaluable tool for projects like environmental monitoring, home automation, and scientific experiments.

How to Set Up Arduino for Data Logging

Required Components

To begin your Arduino data logging project, you will need the following components:

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video
  • Arduino board (Uno, Mega, or any compatible model)
  • SD card module
  • MicroSD card (formatted with FAT16 or FAT32)
  • Jumper wires
  • Breadboard (optional)
  • Sensors (e.g., temperature, humidity, or light sensors)
  • Arduino IDE for coding

Connecting the SD Card to Arduino

  1. SD Card Module Pins: The SD card module typically has the following pins:
    • VCC: Connect to 5V or 3.3V on Arduino (depending on module specifications)
    • GND: Connect to GND on Arduino
    • MOSI (Master Out Slave In): Connect to pin 11 (on Arduino Uno)
    • MISO (Master In Slave Out): Connect to pin 12 (on Arduino Uno)
    • SCK (Serial Clock): Connect to pin 13 (on Arduino Uno)
    • CS (Chip Select): Connect to pin 10 (on Arduino Uno)
  2. Sensor Connection: Depending on your sensors, make sure they are connected to appropriate pins on the Arduino.

Arduino IDE

Importing Required Libraries

To interface with the SD card and handle data storage, the Arduino IDE provides a library called SD.h. This library helps the Arduino interact with the SD card module, allowing data to be written or read from the card.

See also
How to connect Arduino to the cloud

Basic Arduino Code for Data Logging

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

File dataFile;

void setup() {
  Serial.begin(9600);

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

  dataFile = SD.open("datalog.txt", FILE_WRITE);

  if (dataFile) {
    dataFile.println("Sensor Data Log:");
    dataFile.close();
  } else {
    Serial.println("Error opening datalog.txt");
  }
}

void loop() {
  int sensorValue = analogRead(A0); // Read from a sensor
  float voltage = sensorValue * (5.0 / 1023.0); // Convert to voltage

  dataFile = SD.open("datalog.txt", FILE_WRITE);

  if (dataFile) {
    dataFile.print("Voltage: ");
    dataFile.println(voltage);
    dataFile.close();
  } else {
    Serial.println("Error opening datalog.txt");
  }

  delay(1000); // Wait for a second
}

Explanation of the Code

  • The SD.begin(10) initializes the SD card on pin 10 of the Arduino. If initialization fails, an error message is displayed.
  • The dataFile = SD.open(“datalog.txt”, FILE_WRITE) line opens the datalog.txt file in write mode. If the file doesn’t exist, it creates a new one.
  • The sensor value is read from analog pin A0, converted to voltage, and then written to the SD card.
  • The loop continuously logs the data every second.

Reading and Analyzing Data from the SD Card

Retrieving Stored Data

Once data is logged to the SD card, you can remove the card from the module and read it on your computer. Simply insert the SD card into a card reader, and access the text file (e.g., datalog.txt). The data is saved in plain text, making it easy to analyze using software like Excel or Python.

Example of Data Saved on the SD Card

Sensor Data Log:
Voltage: 2.45
Voltage: 2.47
Voltage: 2.49
...

This text file can then be imported into data analysis software for further processing, like graphing the data or calculating averages. For a quick check without a spreadsheet, paste a column of readings into our variance and standard deviation calculator to see how stable the sensor is, or into the linear regression calculator to spot a drift over time.

Expanding Your Data Logging Project

Using Multiple Sensors

Arduino’s versatility allows for the use of multiple sensors in a single project. For example, you can log temperature, humidity, and light levels in the same file or create separate files for each sensor. The logic remains the same: connect your sensors to the Arduino, read the data, and write it to the SD card.

See also
Arduino cloud integration with Google Cloud IoT Core
float temperature = readTemperature();
float humidity = readHumidity();
float lightLevel = readLight();

dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.print("Temperature: ");
  dataFile.print(temperature);
  dataFile.print(" C, ");
  dataFile.print("Humidity: ");
  dataFile.print(humidity);
  dataFile.print(" %, ");
  dataFile.print("Light: ");
  dataFile.println(lightLevel);
  dataFile.close();
}

Timestamping Your Data

For more detailed logs, you might want to include timestamps. You can add real-time data using the RTC (Real-Time Clock) module or rely on Arduino’s millis() function to approximate timestamps. By adding the current time to your data logs, you can better track when measurements were taken.

unsigned long currentMillis = millis();
dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.print("Timestamp: ");
  dataFile.print(currentMillis);
  dataFile.print(" ms, ");
  dataFile.print("Temperature: ");
  dataFile.println(temperature);
  dataFile.close();
}

Troubleshooting Common Issues

SD Card Not Initializing

If the SD card does not initialize, ensure:

  • The card is properly inserted and formatted with FAT16 or FAT32.
  • The wiring is correct and secure.
  • The CS pin (Chip Select) is connected to the right Arduino pin.

Data Not Being Saved

If your Arduino fails to save data:

  • Verify that the SD card module is working properly.
  • Check if there is enough available space on the SD card (a kilobytes to megabytes converter helps compare your log file size with the free space).
  • Ensure your code correctly opens the file in write mode.

Tips for a More Reliable Arduino SD Card Data Logger

The sketch above works for a first test, but a logger that runs for days or weeks needs a few extra habits. These tips cover problems that usually show up only after the project is left running on its own.

Log in CSV format

Instead of writing text such as “Voltage: 2.45”, write comma-separated values, for example a time value, a comma, then the reading. Save the file with a .csv extension and give the first line column names. Excel, Google Sheets and Python tools can then open it directly, with no cleanup of the text.

Keep file names short

The standard Arduino SD library expects short file names in the older 8.3 style, meaning up to eight characters, a dot and a three-character extension. A name like “datalog.csv” works. A long name such as “temperature_log_january.csv” may fail to open or may be shortened in unexpected ways.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works
See also
Arduino machine learning for object detection

Protect data against power loss

Data is only safely stored once it has been written to the card. Closing the file does this, and so does calling flush() on an open file. If your logger loses power or the card is pulled out between writes, anything still held in memory is lost. Two common approaches:

  • Open and close the file on every reading, as in the example above. It is simple and safe, but slower.
  • Open the file once in setup() and call flush() after each line, or after every few lines, if you need faster logging.

Either way, avoid removing the card while the Arduino is powered and writing.

Check voltage levels

SD cards run on 3.3V logic. Most SD card modules sold for Arduino include a voltage regulator and level shifter, so they can be wired to a 5V board such as the Uno. A bare card socket without these parts can be damaged by 5V signals. Check your module’s description before connecting it.

Choose a sensible logging interval

Logging every second is useful for testing, but slow-changing values such as room temperature rarely need it. A longer interval makes the log file smaller and easier to read. It also means fewer writes to the card, which helps in battery-powered projects.

Conclusion

Arduino data logging to an SD card is a powerful technique for capturing sensor data and storing it for later analysis. With just a few components and some basic coding, you can log various types of data from sensors, store it on an SD card, and later retrieve it for analysis. Whether you’re working on environmental projects, home automation systems, or scientific experiments, Arduino’s data logging capabilities can help you efficiently record and track your data.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works