Micro SD Card Module with ESP8266 NodeMCU

In this user guide, we will learn how to interface a micro SD card with ESP8266 NodeMCU using the microSD card module or connector and Arduino IDE. This module provides an SPI interface to connect an SD card module with any microcontroller which supports the SPI communication interface. Using a micro SD card becomes very handy for applications where we need to store files or any data.

Micro SD Card Module with ESP8266 NodeMCU

Additionally, we will learn how to handle files in the microSD card including accessing the microSD card information and reading/writing to a file. Storage data including text, video, audio, CSV, HTML, JavaScript, and CSS files can all be conveniently stored in the microSD card. It is one of the most reliable and practical ways to store data in devices such as mobile phones, laptops, and personal computers. The SD card library provides a convenient way of storing files in the microSD card which will be discussed in later sections of this tutorial.

We have a similar guide with the ESP32 development board and Arduino UNO as well:

MicroSD Card Module with ESP32 using Arduino IDE

Micro SD Card Interfacing with Arduino using MicroSD Module

Micro SD Card Module Introduction

The microSD card Modules are designed to communicate with the MicroSD cards. These connectors provide the required hardware and pinout to connect SD cards with microcontrollers such as ESP32, Arduino, ESP8266, Raspberry Pi, etc. Although, they are compatible with almost all SD cards which are commonly used in cell phones. But they can handle a maximum of 16GB capacity microSD cards and only 2GB capacity for standard SD cards.

With the help of these modules, we will be able to read and write data to and from SD cards through the SPI communication protocol. There are several different types of microSD card modules easily available in the market. But, the one which we will be using in this article is shown below:

MicroSD Card module
MicroSD card module

Pinout

This microSD card module has 6 terminals consisting of SPI and power supply terminals. Below you can view the pinout of this module with some description of the individual pins.

MicroSD card module pin out
Pinout of MicroSD card Module
Pin Name Description
GNDThis is the ground pin which should be connected with the ground pin of ESP8266.
VCCThis pin supplies power to the module. The power supply of ~4.5V-5.5V. The adapter consists of a 3.3V voltage regulator circuit as well to cater to ESP8266’s power supply range.
CSThis is the Chip Select pin for SPI communication.
MOSIThis is called the ‘Master Out Slave In.’ It is used as the SPI input to the module.
SCKThis is called the ‘Serial Clock’ pin which is used in SPI serial clock output.
MISOThis is called the ‘Master in Slave Out.’ It is used as the SPI output from the module.
Table showing the pin names and their short descriptions

Interface Micro SD card module with ESP8266 NodeMCU

Required Hardware:

Following components are required:

  • 1 x ESP8266 NodeMCU board
  • MicroSD card
  • 1 x MicroSD card module

Now, we will show you how to connect the microSD card module and the ESP8266 board together. Below you can see the pinout of ESP32 DEVKIT V1 to get a better idea of the SPI default pins.

ESP8266 GPIO pins

The table below shows the default SPI pins of ESP8266

MOSID7 (GPIO13)
MISOD6 (GPIO12)
SCKD5 (GPIO14)
CSD8 (GPIO15)

Now let us see how to connect the microSD card module and the ESP8266 board. The table below shows the connections between the two devices:

MicroSD card module ESP8266
GNDGND
VCC3.3V
CSD8
MOSID7
SCKD5
MISOD6

As shown from the table, we will connect the VCC terminal of the MicroSD card module with 3.3V of the ESP8266 board. Both grounds will be common. The default SPI GPIO pins of ESP8266 are being used to connect with each of the remaining SPI terminals of the microSD card module.

ESP8266 with microSD card module schematic diagram
Connection diagram of ESP8266 with microSD card module

SD Card Module Issues with ESP8266 NodeMCU

SD card module has voltage issues with ESP8266 modules. There are two methods to resolve those issues:

Method 1:

Power up ESP8266 NodeMCU with 5V external power source through Vin pin. That means connect power to NodeMCU through Vin pin directly instead of USB connector.

power ESP8266 NodeMCU with Vin pin

Now, as we know how to interface the microSD card module and the ESP8266 together let us learn how to prepare the microSD card to handle files in Arduino IDE.

Method 2:

If you have any limitation to power ESP8266 NodeMCU through Vin pin, you can use this method. But it is recommended to use last method which is easy fix.

To make it work with ESP8266, we need to remove 3.3V regulator IC and short pin 2 and 3 with each other as shown below:

ESP8266 NodeMCU SD card module changes

Formatting the Micro SD card

As we have to use our microSD card in Arduino IDE so we would have to format it as FAT32. We will have to follow a series of steps to accomplish it successfully.

  • First, insert your microSD card in your laptop/computer. Now go to ‘This PC’ and click on SD card icon. Then click on Format by right clicking the SD card icon.
microSD card formatting pic1
  • The following window will appear. Select FAT32 from the dialog box of ‘File System’ and click on ‘START.’
microSD card formatting pic2
  • You will receive a warning message that formatting will erase all previous data saved on the microSD card. Click ‘OK.’
microSD card formatting pic3
  • After a few moments, your microSD card will be formatted successfully. Click ‘OK.’
microSD card formatting pic4

ESP8266 with micro SD Card: Example Sketches

In this section, we will show you how to use example sketches available in the Arduino IDE. These will help us to learn how to handle files with a microSD card using ESP8266 and Arduino IDE. We will use the SD library examples to demonstrate the card information and some file handling functions like reading and writing on a file which will be saved on the microSD card.

ESP8266 NodeMCU Sketch: Read/Write on a File

Open your Arduino IDE and go to File > Examples > SD (esp8266) > ReadWrite . The following program code will open. This example sketch will read and write data on a .txt file that will get saved on our microSD card.

/*
  SD card read/write

  This example shows how to read and write data to and from an SD card file
  The circuit:
   SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*/

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

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);

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

  if (!SD.begin(15)) {
    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
}

We have modified one line in this sketch according to the board we are using. As we are using ESP8266, hence its default SPI CS pin is GPIO15. Using the begin() function on the SD filesystem, we will initialize the microSD card. Therefore, make sure when initializing the microSD card replace the argument in the begin() function to 15. By default it was set to 4.

 if (!SD.begin(15)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

How the Code Works?

Now let us understand how each part of the code works.

Including Libraries

The first step is to include all the libraries that are necessary for this project. The SD library will be used for the microSD card functionality and the SPI library will be used as we are using SPI communication protocol between the ESP8266 board and the microSD card module.

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

Creating File Object

Secondly, we will create an object of File and name it ‘myFile.’ This is the object which we will use later to read and write data to our file in the microSD card.

File myFile;

Inside the setup() function, we will open a serial connection at a baud rate of 115200.

 Serial.begin(115200);

Initializing the microSD card

The following lines of code will initialize the microSD card using the begin() function on the SD filesystem using SD.begin(). The begin() function takes in the CS Pin as an argument which we have stated as ’15.’ Thus, it will start the SPI communication using the default SPI CS pin that is GPIO15. To change the SPI CS pin you can pass the pin number as an argument inside the begin() function.

if (!SD.begin(15)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

Writing data to file

Next, we will open the test.txt file on the microSD card using SD.open() and will act as read/write. If the file does not exist, it will get created.

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

Using the println() function on the myFile object we will write ‘testing 1, 2, 3.’ in the test.txt file. After that, we will close the file using file.close(). This will ensure that the data written on the file gets saved as well. The serial monitor will display ‘Writing to test.txt…’ and ‘done’ after the data is written. If the file is unable to open the serial monitor will display an error message.

Note: print() and println() work in similar way to write strings/variable to a file

print(): prints the message on the same line
println(): prints the message on the next line

  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");
  }

Reading data from file

Now, we will read the data which we just wrote on our test.txt file. To do that we will first open the test.txt file by using SD.open(). Then by using Serial.write() and passing myFile.read() as an argument inside it, it will read the test.txt file and print the data in the serial monitor. Notice that we are using a while loop with myFile.available() as an argument inside it. This will make sure that all the contents of the file are displayed on the serial monitor properly. After that, we will close the file using file.close(). If the file is unable to open the serial monitor will display an error message.

Note: read() function only reads a single character at a time.

  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");
  }

Demonstration

To see the demonstration of the above code, upload the code to your ESP8266. Select the board from Tools > Board and choose NodeMCU 1.0 and also select the correct COM port to which the your board is connected from Tools > Port.

select ESP8266 NodeMCU board

Once the code is uploaded to ESP8266, open the serial monitor of Arduino IDE and set the baud rate to 115200. You will be able to view the following messages if the data is successfully written to the file (highlighted in blue). The red highlighted box shows the contents of the test.txt file which are ‘testing 1, 2, 3.’ If we press the Reset button again, another set of data will get appended in the file.

microSD card module with Arduino uno readWrite serial monitor demo
Serial Monitor

ESP8266 NodeMCU Sketch: Creating and Deleting Files on SD Card

Open your Arduino IDE and go to File > Examples > SD > Files . The following program code will open. This example sketch will create and delete a .txt file in our microSD card.

/*
  SD card basic file example

  This example shows how to create and destroy an SD card file
  The circuit:
   SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*/
#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.");

  if (SD.exists("example.txt")) {
    Serial.println("example.txt exists.");
  } else {
    Serial.println("example.txt doesn't exist.");
  }

  // open a new file and immediately close it:
  Serial.println("Creating example.txt...");
  myFile = SD.open("example.txt", FILE_WRITE);
  myFile.close();

  // Check to see if the file exists:
  if (SD.exists("example.txt")) {
    Serial.println("example.txt exists.");
  } else {
    Serial.println("example.txt doesn't exist.");
  }

  // delete the file:
  Serial.println("Removing example.txt...");
  SD.remove("example.txt");

  if (SD.exists("example.txt")) {
    Serial.println("example.txt exists.");
  } else {
    Serial.println("example.txt doesn't exist.");
  }
}

void loop() {
  // nothing happens after setup finishes.
}

We have modified one line in this sketch according to the board we are using. As we are using Arduino Uno, hence its default SPI CS pin is GPIO10. Using the begin() function on the SD filesystem, we will initialize the microSD card. Therefore, make sure when initializing the microSD card replace the argument in the begin() function to 10. By default it was set to 4.

if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    while (1);
  }

Demonstration

To see the demonstration of the above code, upload the code to Arduino. But, before uploading code, make sure to select the Arduino board from Tools > Board and also select the correct COM port to which the Arduino board is connected from Tools > Port.

Once the code is uploaded to Arduino, open the serial monitor of Arduino IDE and set the baud rate to 9600.

microSD card module with Arduino uno Files serial monitor demo
Serial Monitor

At first, you can view that example.txt file did not exist in the microSD card. Hence it was first created as highlighted in red. Then it was removed from the microSD card.

ESP8266 NodeMCU Sketch: List all Files from MicroSD Card

Open your Arduino IDE and go to File > Examples > SD > listfiles. The following program code will open. This example sketch will display all the files present in your microSD card on the serial monitor.

/*
  Listfiles

  This example shows how print out the files in a
  directory on a SD card

  The circuit:
   SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe
  modified 2 Feb 2014
  by Scott Fitzgerald

  This example code is in the public domain.

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

File root;

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.");

  root = SD.open("/");

  printDirectory(root, 0);

  Serial.println("done!");
}

void loop() {
  // nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

We have modified one line in this sketch according to the board we are using. As we are using Arduino Uno, hence its default SPI CS pin is GPIO10. Using the begin() function on the SD filesystem, we will initialize the microSD card. Therefore, make sure when initializing the microSD card replace the argument in the begin() function to 10. By default it was set to 4.

 if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    while (1);
  }

Demonstration

To see the demonstration of the above code, upload the code to Arduino. But, before uploading code, make sure to select the Arduino board from Tools > Board and also select the correct COM port to which the Arduino board is connected from Tools > Port.

Once the code is uploaded to Arduino, open the serial monitor of Arduino IDE and set the baud rate to 9600.

microSD card module with Arduino uno listFiles serial monitor demo
Serial Monitor

As you can notice in the serial monitor, first the system files are displayed with their sizes. Next, we have three .txt files (TEST1.txt, TEST2.txt and TEST3.txt) in our microSD card which are empty as denoted by their size.

SD Card Library Useful Functions

The table below shows some commonly used functions with SD object that we did not cover till now.

exists(“test.txt”)This function will return true/false depending on whether the file passed as an argument inside it exists or not. In this case, it will check whether the file ‘test.txt’ exists in the microSD card or not.
remove(“test.txt”)This function will permanently remove the file passed as an argument inside it. In this case, it will remove the ‘test.txt’ file.
mkdir(“/mynewdir”)This function will create a new directory

The table below shows some commonly used functions with the File object (e.g. myFile) that we did not cover till now.

seek()This function will help us to change the location of the cursor while reading/writing on a file. It takes in a single parameter which denotes the relative position of the cursor where 0 is the starting of a file.
position()This function will help us in knowing the exact position we are in a file while reading/writing.
size()This function denotes the size of the file by denoting the number of bytes it consumes.
isDirectory()This function specifies whether the particular file is a directory or not.
openNextFile()This function will enable us to go through all the files in a directory.

Conclusion

In conclusion, we learned how to use a micro SD card with Arduino using Arduino IDE. We looked at example sketches from the SD library and successfully initialized our microSD card. Additionally, we were able to read and write to a .txt file as well.

You may also like to read:

Leave a Comment