Thanks to visit codestin.com
Credit goes to lastminuteengineers.com

Interfacing Micro SD Card Module with Arduino

Every once in a while, you’ll come up with an Arduino project that needs lots of data storage—whether you’re logging sensor data, saving files, or storing more information than the Arduino’s built-in memory can handle.

So how do you manage all that data? The solution is probably something you already have in your digital camera or phone: microSD cards. They can store gigabytes of data in a space smaller than a coin, making them an essential part of our everyday technology.

A microSD card module makes connecting your Arduino to a microSD card easy, making data storage in your next project a breeze. Let’s dive in and explore how!

Hardware Overview

The key components of a microSD card module include:

3.3V LDO Regulator

A standard microSD card runs on 3.3V, which means you can’t directly connect it to circuits using 5V logic. In fact, any voltage higher than 3.6V could permanently damage the card. To protect your card, the module has a built-in ultra-low dropout voltage regulator that creates a steady 3.3V power supply, keeping your microSD card safe during operation.

microSD Card Module 3V3 Regulator

Logic Level Shifter Chip

The module also includes a 74LVC125A logic level shifter chip. This chip works as a bridge between your microcontroller (which typically uses 5V) and the microSD card (which needs 3.3V). The logic level shifter makes sure the voltage levels are properly converted, allowing your microSD card and microcontroller to communicate safely and effectively.

microSD Card Module Logic Level Shifter

microSD Card Socket

On the front of the module, you’ll find a microSD card socket. Any type of microSD memory card will work fine with this socket. The module usually shows you the right way to insert the card, making it simple to get started.

microSD Card Module Socket

Communication Interfaces – SPI vs SDIO

When using a microSD card in your projects, you have two main ways to interface: SPI (Serial Peripheral Interface) and SDIO (Secure Digital Input Output). Each option has different features in terms of speed, how complex it is to set up, and what it’s typically used for.

SDIO is much faster and is what you’ll find in mobile phones, digital cameras, and other devices that need high performance. However, it’s also more complicated and often requires signing special agreements with manufacturers, which makes it hard for hobbyists to access. Because of these challenges, you rarely see SDIO interface code available for DIY projects.

SPI, on the other hand, is what you’ll find in almost all SD card modules made for hobby projects. While it doesn’t work as fast as SDIO and uses more processing power, you can easily set it up with any microcontroller. This simplicity makes SPI the popular choice for most of us working on DIY electronics projects.

microSD Card Module Pinout

A microSD card module has six pins:

Micro SD TF Card Module Pinout SPI

VCC provides power to the module and should be connected to the Arduino’s 5V pin.

GND is a ground pin.

MISO (Master In Slave Out) is the SPI output pin from the microSD card module that sends data to the Arduino.

MOSI (Master Out Slave In) is the SPI input pin to the microSD card module that receives data from the Arduino.

SCK (Serial Clock) receives timing pulses from the master device (your Arduino) to keep the data transmission in sync.

CS (Chip Select) is a control pin used to activate the module on the SPI bus, allowing it to communicate when needed.

Preparing the microSD card

Before you put the microSD card into the module and connect it to your Arduino, it’s important to make sure the card is correctly formatted to FAT16 or FAT32.

If you’re using a brand new SD card, it probably came already formatted with a FAT file system. However, this factory formatting might not be perfect, and you could run into problems. If you’re using an older card that’s been used before, it will definitely need to be reformatted. Either way, it’s a good idea to format the card before using it in your project.

For the best results, try using the official SD card formatter utility developed by the SD Association. This special tool helps prevent many common problems caused by incorrect formatting. Just download the formatter to your computer, run it, select your SD card’s drive letter, and click the Format button.

sd formatter screenshot

Wiring a microSD Card Module to an Arduino

Now that your microSD card is ready, let’s connect the microSD card module to your Arduino!

First, connect the module’s VCC pin to the 5V pin on your Arduino and the GND pin to ground.

Next, we’ll set up the pins used for SPI communication. Since microSD cards need fast data transfer, they work best when connected to your microcontroller’s hardware SPI pins.

Remember that different Arduino boards have different SPI pin layouts, so you need to connect them correctly. For example, on Arduino boards like the UNO or Nano V3.0, the SPI pins are: digital 13 (SCK), 12 (MISO), 11 (MOSI), and 10 (CS).

Here’s a quick reference table for the pin connections:

microSD Card ModuleArduino
VCC5V
GNDGND
MISO12
MOSI11
SCK13
CS10

The diagram below shows exactly how to wire the microSD Card Module to your Arduino.

Arduino Wiring Fritzing Connections with Micro SD TF Card Module

And there you have it! You’re now ready to start logging data!

Arduino Code – Testing the microSD card module with CardInfo

Communicating with a microSD card can be tricky, but luckily, the Arduino IDE includes a helpful library called SD that makes reading and writing to SD cards much easier.

Let’s begin with a simple CardInfo example sketch. This sketch doesn’t write anything to the card. Instead, it checks if your Arduino can recognize the card and shows you some basic information about it. It’s really good to run this sketch when testing a new microSD card because it helps you figure out if your Arduino supports the card.

To find the CardInfo example sketch, go to File > Examples > SD > CardInfo in the Arduino IDE.

sd library cardinfo sketch in arduino ide

Before running the sketch, check that the chipSelect is set correctly at the start of the code. Since we’re using digital pin #10 in our setup, make sure it’s set to 10.

initialising chipselect cardinfo sketch in arduino ide

Now, put the SD card into the module and upload the sketch to your Arduino. After uploading, open the Serial Monitor to see the results. The output may vary depending on different scenarios:

Scenario 1: Successful Card Initialization

If everything is working right, you’ll see useful details about your microSD card. For instance, you might learn that your card type is SDHC (SD High Capacity), it uses FAT32 formatting, and it has 4 GB of storage.

cardinfo sketch output in arduino ide working

Scenario 2: Corrupted SD Card Detected

If your card is corrupted, you might see something like this:

cardinfo sketch output in arduino ide bad corrupt card

The card responded, but all the information is wrong. There’s no Manufacturer ID or OEM ID, and the Product ID shows up as ‘N/A.’ This means the card is sending back SD errors.

If this happens, try reformatting the card. If that doesn’t solve the problem, you might need to get a new card.

Scenario 3: Wiring Issue or Permanent Card Damage

If there’s a problem with your wiring or the card is permanently damaged, the Serial Monitor will tell you that the SD card couldn’t be initialized at all.

cardinfo sketch output in arduino ide initialization failed

If this happens, carefully check all your wiring connections and try running the sketch again.

Scenario 4: Improperly Formatted SD Card

If your wiring is correct but the SD card isn’t formatted properly, you’ll get a message saying so.

cardinfo sketch output in arduino ide no proper format

In this case, reformat the card and then run the sketch again.

Arduino Code – Reading and Writing Data

Assuming your previous sketch worked successfully, let’s try the next one. This sketch will show you how to write data to a file and then check what you wrote by reading it back.

Give this sketch a try before we get into all the details.

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

File myFile;

// change this to match your SD shield or module;
const int chipSelect = 10;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  Serial.print("Initializing SD card...");

  if (!SD.begin()) {
    Serial.println("initialization failed!");
    return;
  }
  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("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-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
}

After you upload the code, you’ll see this output in the Serial Monitor.

micro sd card sd library output on serial monitor

If you press the reset button on your Arduino and let the sketch run again, you’ll notice that the new data gets added to the end of the file instead of replacing what was already there.

micro sd card sd library second output on serial monitor

Code Explanation:

The sketch starts by including the SD and SPI libraries, which let your Arduino communicate with the SD card through the SPI interface.

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

Next, we set up which Arduino pin connects to the SD card module’s CS (Chip Select) pin. Since the sketch uses hardware SPI, you only need to specify the CS pin – the other SPI pins are already defined in the SPI library.

const int chipSelect = 10;

Then, we create a file object called myFile. This object includes functions that allow you to access and modify files on the SD card.

File myFile;

In the setup() function, we start serial communication and call SD.begin() to initialize the SD card. If the card is recognized successfully, you’ll see “initialization done.” in the serial monitor. If something goes wrong, you’ll see “initialization failed!” and the program will stop.

Serial.begin(9600);
  Serial.print("Initializing SD card...");
  if (!SD.begin()) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

The sketch then opens a file using the open() function. This function either opens a file that already exists or creates a new one if it doesn’t. The function needs two pieces of information: the name of the file and the mode in which you want to open it.

Your file mode options include FILE_READ, which opens the file for reading and puts the cursor at the beginning, and FILE_WRITE, which opens the file for both reading and writing, placing the cursor at the end.

In this example, we create a file called “test.txt” and open it in read-write mode.

myFile = SD.open("test.txt", FILE_WRITE);

After opening the file, we write data to it using the println() function, which works like the one used for sending data to the serial monitor. You could also use the print() function if you don’t want to move the cursor to a new line.

We then close the file using the close() function. This makes sure all your data gets saved to the SD card.

 if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    myFile.close();
    Serial.println("done.");
  } else {
    Serial.println("error opening test.txt");
  }

To check if our writing worked, we read back the file contents. We reopen the file using the open() function, this time in read mode. Since “test.txt” already exists, the file just gets opened.

We read the file contents using the myFile.read() function and print them to the serial monitor. Since read() gets just one character at a time, we use a while loop with myFile.available() to read and show all characters in the file.

Finally, we close the file again.

myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }

Since this sketch is just meant to demonstrate reading and writing files, all the code is placed in the setup() function, which only runs once. That’s why the loop() function is empty – there’s no need for the code to keep running over and over.

void loop() 
{
}

Important things to note

  • You can use the print() and println() functions to write strings, variables, and more to your files, just like you do when sending information to the Serial Monitor.
  • The read() function only gives you one character at a time. It doesn’t read an entire line at once.
  • When you’re finished working with a file, always use the close() function. This makes sure all your data gets permanently saved and helps free up memory in your Arduino.
  • You can also work with files inside folders. For example, to open a file in a directory, you’d use SD.open("/myfiles/example.txt"). Just remember that the file path is relative.
  • The SD card library only supports short filenames because it uses the 8.3 filename format. This means your filenames should be brief. For instance, “datalog.txt” works great, but “My sensor log file.text” is too long and won’t work properly.
  • Also, remember that filenames aren’t case-sensitive. So “datalog.txt” is exactly the same as “DataLog.Txt” or even “DATALOG.TXT“.

Some useful functions of the SD Library

SD object-specific functions

The SD object comes with several helpful functions. Here are a few important ones:

  • exists(filename): This function checks if a file exists on your SD card. It returns true if the file is there, and false if it’s not.
  • remove(filename): This function lets you delete a file. But be careful! Once you delete a file this way, it’s gone forever and you can’t get it back.
  • mkdir("/mynewdir"): This function creates new folders. It’s really helpful when you need to organize a large number of files in one location.

File object-specific functions

There are also some great functions you can use with File objects:

  • seek(): This function moves the cursor to a new location in the file. For example, seek(0) moves the cursor back to the very beginning of the file.
  • position(): This function tells you the current position of the cursor within the file.
  • size(): This function returns the size of the file in bytes.
  • isDirectory(): This function helps you check whether something is a file or a folder.
  • openNextFile(): This function lets you browse through all the files in a folder one by one.
  • name(): When you’re browsing through files with openNextFile(), you can use this function to get each file’s name. It returns a pointer to an 8.3-formatted character array, which you can easily display using Serial.print().