SD Card Module w/ Arduino: How to Read/Write Data

Table of Contents

Overview

Storing data is one of the most important parts of every project. There are several ways to store data according to the data type and size. SD and micro SD cards are one of the most practical ones among the storage devices, which are used in devices such as mobile phones, minicomputers and etc.

In this tutorial, you’ll learn how to use SD and micro SD cards with Arduino.

In the end, as a simple project, you will measure the environment temperature every hour and store it on the SD card.

What You Will Learn

What is SD and Micro SD Card Module?

The SD and micro SD card modules allow you to communicate with the memory card and write or read the information on them. The module interfaces in the SPI protocol.

To use these modules with Arduino you need the SD library. This library is installed on the Arduino application by default.

Note
These modules can not handle high-capacity memory cards. Usually, the maximum identifiable capacity of these modules is 2GB for SD cards, and 16GB for micro SD cards.

You can download the datasheet of this module here.

Micro SD TF Card Module Pinout

This module has 6 pins:

  • VCC: Module power supply – 5V
  • GND: Ground
  • CS: Chip Select pin
  • MISO: (Master In Slave Out) is SPI output from the Micro SD Card Module
  • MOSI: (Master Out Slave In) is SPI input to the Micro SD Card Module
  • SCK: Serial Clock

You can see the pinout of this module in the image below.

Required Materials

Hardware Components

Arduino UNO R3 × 1
Micro SD TF Card Adapter Module × 1
DS3231 I2C RTC Module × 1
Male to Female jumper wire × 1
micro SD card × 1

Software Apps

Arduino IDE

Important SD Module Library Commands

A brief explanation of practical SD library’s commands is provided in the following table:
Description Command
Initializes the SD library and card. Enter the pin connected to the SS pin as a function’s argument. SD.begin(#sspin)
Tests whether a file or directory exists on the SD card. SD.exists(filename)
Opens a file on the SD card in reading or writing mode. (If you leave the mode section blank, the file will open in reading mode by default) If the file is opened for writing, it will be created a file with this name if it doesn’t already exist. SD.open(filepath, mode)
Close the file and ensure that any data written to it is physically saved to the SD card. file.close()*
Remove a file from the SD card. SD.remove(filename)
Create a directory on the SD card SD.mkdir(filename)
Remove a directory from the SD card. SD.rmdir(filename
Returns the file name file.name()*
Print data to the file file.print(data)
Print data, followed by a carriage return and newline file.println(data
Read from the file. file.read()
Check if there are any bytes available for reading from the file. file.available()

*file is an instance from File class.

You can find more information about the SD library Here.

How to Use SD and Micro SD Card with Arduino?

Tip
The module used in this tutorial is the micro SD module, however, you can use the code and tutorial for SD modules as well.

Circuit

Using this module is very simple and its configuration is as follows:

Code

Writing data on SD card with Arduino:

#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("This is a test file :)");
myFile.println("testing 1, 2, 3.");
for (int i = 0; i < 20; i++) {
myFile.println(i);
}
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void loop() {
// nothing happens after setup
}
The result of the above code execution:

Reading data from SD card with Arduino

#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
// open the file for reading:
myFile = SD.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void loop() {
// nothing happens after setup
}
The result of the above code execution:

Project: Save Temperature Data on a microSD using DS3231 Module

You can find DS3231 here. In addition to the IC clock and calendar, this module also has a temperature sensor.

Circuit

Code

To work with the DS3231 module, you must first add the library (Sodaq_DS3231.h) to the Arduino application.
/*
Save temperature in SD/microSD card every hour with DS3231 + SD/microSD module + Arduino
modified on 15 Apr 2019
by Mohammadreza Akbari @ Electropeak
Home
*/ #include <SPI.h> #include <SD.h> #include <Wire.h> #include "Sodaq_DS3231.h" File myFile; DateTime now; int newHour = 0; int oldHour = 0; void save_temperature() { myFile = SD.open("temp.txt", FILE_WRITE); now = rtc.now(); myFile.print(now.hour()); myFile.print(":"); myFile.print(now.minute()); rtc.convertTemperature(); //convert current temperature into registers myFile.print(","); myFile.println(rtc.getTemperature()); //read registers and save temperature on deg C myFile.close(); } void setup () { Wire.begin(); rtc.begin(); Serial.begin(9600); Serial.print("Initializing SD card..."); if (!SD.begin(10)) { Serial.println("initialization failed!"); while (1); } Serial.println("initialization done."); now = rtc.now(); oldHour = now.hour(); } void loop () { now = rtc.now(); newHour = now.hour(); if (oldHour != newHour) { save_temperature(); oldHour = newHour; } }
After storing the temperature at different times of the day, you can draw this information into Excel using the chart.

Draw a chart in Excel:

To do this, follow these steps:

Connect the SD card to your PC.

Enter the Excel software and select the From Text option from the data window and select the file from your memory card.

Select the cells and draw a diagram with them.

What’s Next?

  • Create an entry/exit control device. Using the RFID module and Arduino, save entrance and exit time for several persons on the memory card. (Consider an RFID card for each person)

Liked What you see?

Get updates and learn from the best

More To Explore

Comments (12)

  • Givi Reply

    Mohammadreza,

    Very good tutprial here. Ejoyed reading and learnin about SD card and how it works with the Arduino.

    Thanks.

    February 17, 2021 at 4:47 am
    • Mehran Maleki Reply

      You’re quite welcome. We’re so happy you enjoyed it.

      February 17, 2021 at 3:04 pm
  • Givi Reply

    Hi Akbari, Maleki,
    Chetorrine? I was trying to learn some about the SAMD51and interfacing/coding it, So, I purchased an Adafruit Grand Central M4 Express Featuring SAMD51, which also has a SD card built in. I’ve had little success in accessing the SD card Writing/Reading it and I even tried it with different size SD card with few examples, but I was not happy with the results. I came across SD modules and different Type/Pin selection etc., see below. I like to know what they should be for the Adafruit Grand Central M4 Express! Which libraries and include files you recommend. Or direct me to a working example.

    // SD shield or module;
    // Arduino Ethernet shield: pin 4
    // Adafruit SD shields and modules: pin 10
    // Sparkfun SD shield: pin 8
    // MKRZero SD: SDCARD_SS_PIN
    // chipSelect = 4

    Thanks.
    Regards,

    Givi

    February 26, 2021 at 10:12 pm
    • Mehran Maleki Reply

      Hi.
      Unfortunately, like you, I haven’t had much experience with SAMD51, so I can’t specifically tell you what you should do in details. But generally speaking, you should refer to the datasheet to figure out which pins of the st microcontroller are connected to the SD card slot. Then you can change the examples you’ve been trying according to the datasheet, then you will probably get the right results.

      February 28, 2021 at 11:28 am
      • Givi Reply

        Thanks Mehran. I’ll do that.

        Regards.

        February 28, 2021 at 3:20 pm
        • Mehran Maleki Reply

          You’re quite welcome.

          March 1, 2021 at 5:17 am
  • Gino Reply

    Where is the code (uno) file for this project. I can’t find it anywhere other than the library files you need? Thanks

    October 5, 2021 at 2:36 am
    • Mehran Maleki Reply

      Hi!
      You’re right! Our bad! It seems that we’d forgotten to add the code files to the article.
      Now the article is updated, and you can see the codes.

      October 6, 2021 at 5:58 am
      • Gino Reply

        Thank you very much!!! I really appreciate you fixing it, now I can make this project & adapt it to fit my needs. Thanks again!

        October 6, 2021 at 2:53 pm
        • Mehran Maleki Reply

          You’re quite welcome!

          October 9, 2021 at 5:32 am
  • Gary woods Reply

    Can you just push button for selecting specific files and output audio to speaker?

    December 29, 2021 at 4:42 pm
    • Mehran Maleki Reply

      Hi.
      Yes, it’s pretty much straightforward. You just need to connect as many push buttons as you want to the digital pins of the Arduino boards and define them as Input in your code. Then, you can set conditions in which your desirable files are played by the speaker.

      January 1, 2022 at 6:49 am

Leave a Reply

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