Reading and Writing Data from an SD Card with Arduino

Difficulty Level: Intermediate

In this tutorial, you will learn how to interface an Arduino with an SD card module to read from and write data to the SD card. The SD card module can be used for various data logging applications, storing sensor data, or configuration files.

Components Required

Wiring the SD Card Module

Most SD card modules communicate with the Arduino using the SPI protocol. The pin connections are as follows:

Arduino Libraries

We’ll be using the SD.h library, which provides built-in support for SD card modules. This library makes it easy to read and write files on SD cards.

Basic Code Explanation

In this tutorial, we’ll create a file on the SD card, write data to it, and read the data back. The code handles initializing the SD card, checking for errors, and using the File class to write and read data.

Arduino Code


#include 
#include 

const int chipSelect = 10;  // CS pin for the SD card module

void setup() {
  Serial.begin(9600);
  Serial.print("Initializing SD card...");

  // Check if the SD card is initialized properly
  if (!SD.begin(chipSelect)) {
    Serial.println("Initialization failed!");
    return;
  }
  Serial.println("Initialization done.");

  // Create or open a file for writing
  File dataFile = SD.open("data.txt", FILE_WRITE);

  // If the file is available, write to it
  if (dataFile) {
    dataFile.println("Hello, world!");
    dataFile.close();
    Serial.println("Data written to file.");
  } else {
    Serial.println("Error opening file for writing.");
  }

  // Now read from the file
  dataFile = SD.open("data.txt");
  if (dataFile) {
    Serial.println("Reading data from file:");
    while (dataFile.available()) {
      Serial.write(dataFile.read());
    }
    dataFile.close();
  } else {
    Serial.println("Error opening file for reading.");
  }
}

void loop() {
  // Nothing to do here
}
            

Code Breakdown

Upload and Test

  1. Upload the code to your Arduino.
  2. Open the serial monitor to view the status of the SD card initialization, writing data, and reading data.
  3. The text "Hello, world!" should be written to the SD card, and then read back and displayed in the serial monitor.

Conclusion

In this tutorial, you learned how to interface an SD card with an Arduino to read and write data. This technique is useful for data logging applications and for storing persistent data in Arduino projects.