Using SD Card Module With Arduino | Read/Write/Data Logger

Overview: Using SD Card Module with Arduino

In this tutorial, we will learn to use of SD Card Module with an Arduino microcontroller to read, write, store data or make a data logger. We can use the SD Card Module to add the desired memory to the Arduino project to store the data, Media, etc.

The Micro SD Card Reader Module is also called a Micro SD Adaptor. The Module is a simple solution for transferring data to and from a standard SD card. Hence, the tutorial covers the reading of SD Card info and the method to read and write data to SD Card.

Similarly, Building a data logger using Arduino and SD Card is so easy. The DHT11 sensor is used to sense the relative humidity & temperature and the SD card is used to save the values of the humidity and the temperature every 1 second in txt format.

Earlier, we used the SD Card Module on the project like RFID Attendance System and on Surveillance CCTV project.

Bill of Materials

For this tutorial, we recommend to buy the following list of components directly from Amazon.

S.N.Components NameQuantityPurchase Links
1Arduino UNO Board1Amazon | AliExpress
2SD Card Module1Amazon | AliExpress
3SD Card 4-16 GB1Amazon | AliExpress
4USB Card Reader1Amazon | AliExpress
5DHT11 Sensor1Amazon | AliExpress
6Jumper Wires10Amazon | AliExpress

SD Card Module/Adapter

The SD card module is especially useful for projects that require data logging. There are actually two ways to interface with micro SD cards – SPI mode and SDIO mode. Hobbyists like us prefer SPI Mode for interfacing as it’s easy compared to SDO mode which is very complex.

SD Card Module

The operating voltage of micro SD Cards is 3.3 V. Therefore, we cannot SD Card directly with 5V logic. But the module has an onboard ultra-low dropout regulator that converts voltages from 3.3V – 6V down to ~3.3V. There is also a Logic Level converter IC 74LVC125A on the module which converts the interface logic from 3.3V-5V to 3.3V.

Micro SD Card Module Pinout

There are total of six pins (GND, VCC, MISO, MOSI, SCK, CS) on a SD-Card Adapter.

1. GND: Ground Pin 2. VCC: +5V power supply 3. MISO: SPI output 4. MOSI: SPI input 5. SCK: Accepts clock pulses for Data Synchronization 6. CS: Chip select signal pin to enable/disable line

Preparing the micro SD card

Before you insert the micro SD card into the module, you must properly format the card. You should format the SD card as FAT16 or FAT32.

To format the SD card, insert it into your computer. Go to My Computer and right-click on the SD card. A new window pops up. Select FAT32 as a Formatting option. Then press Start to initialize the formatting process

Now the SD Card is properly formatted and you can use the SD Card with SD Card Module to use in project applications.

Interfacing SD Card Module with Arduino

Now let us learn interfacing of SD Card Module with Arduino to read & write data or to make a data logger. Since the SD Card Module works on SPI Communication protocol, thus we need to connect it to SPI Pin of Arduino Board.

SD Card Module Arduino Interfacing

Connect the SD Card Module to Arduino as per the above Circuit Diagram. For Arduino boards like UNO/Nano, the SPI pins are 13 (SCK), 12 (MISO) and 11 (MOSI).

SD Card Module Arduino Connection

In case, if you are using other Arduino Boards then you follow the below table for connection.

Testing the SD Card Module

To make sure everything is wired correctly and the SD card is working properly, upload the following code to the Arduino Board.Make sure you have the right board and COM port selected.

// include the SD library: #include <SPI.h> #include <SD.h> // set up variables using the SD utility library functions: Sd2Card card; SdVolume volume; SdFile root; // change this to match your 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 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 native USB port only } Serial.print("\nInitializing SD card..."); // we'll use the initialization code from the utility libraries // since we're just testing if the card is working! if (!card.init(SPI_HALF_SPEED, chipSelect)) { Serial.println("initialization failed. Things to check:"); Serial.println("* is a card inserted?"); Serial.println("* is your wiring correct?"); Serial.println("* did you change the chipSelect pin to match your shield or module?"); while (1); } else { Serial.println("Wiring is correct and a card is present."); } // print the type of card Serial.println(); Serial.print("Card type: "); switch (card.type()) { case SD_CARD_TYPE_SD1: Serial.println("SD1"); break; case SD_CARD_TYPE_SD2: Serial.println("SD2"); break; case SD_CARD_TYPE_SDHC: Serial.println("SDHC"); break; default: Serial.println("Unknown"); } // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32 if (!volume.init(card)) { Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card"); while (1); } Serial.print("Clusters: "); Serial.println(volume.clusterCount()); Serial.print("Blocks x Cluster: "); Serial.println(volume.blocksPerCluster()); Serial.print("Total Blocks: "); Serial.println(volume.blocksPerCluster() * volume.clusterCount()); Serial.println(); // print the type and size of the first FAT-type volume uint32_t volumesize; Serial.print("Volume type is: FAT"); Serial.println(volume.fatType(), DEC); volumesize = volume.blocksPerCluster(); // clusters are collections of blocks volumesize *= volume.clusterCount(); // we'll have a lot of clusters volumesize /= 2; // SD card blocks are always 512 bytes (2 blocks are 1KB) Serial.print("Volume size (Kb): "); Serial.println(volumesize); Serial.print("Volume size (Mb): "); volumesize /= 1024; Serial.println(volumesize); Serial.print("Volume size (Gb): "); Serial.println((float)volumesize / 1024.0); Serial.println("\nFiles found on the card (name, date and size in bytes): "); root.openRoot(volume); // list all files in the card with date and size root.ls(LS_R | LS_DATE | LS_SIZE); } void loop(void) { }
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 // include the SD library:#include <SPI.h>#include <SD.h> // set up variables using the SD utility library functions:Sd2Card card;SdVolume volume;SdFile root; // change this to match your 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_PINconstintchipSelect=10; voidsetup(){// 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("\nInitializing SD card..."); // we'll use the initialization code from the utility libraries// since we're just testing if the card is working!if(!card.init(SPI_HALF_SPEED,chipSelect)){Serial.println("initialization failed. Things to check:");Serial.println("* is a card inserted?");Serial.println("* is your wiring correct?");Serial.println("* did you change the chipSelect pin to match your shield or module?");while(1);}else{Serial.println("Wiring is correct and a card is present.");} // print the type of cardSerial.println();Serial.print("Card type: ");switch(card.type()){caseSD_CARD_TYPE_SD1:Serial.println("SD1");break;caseSD_CARD_TYPE_SD2:Serial.println("SD2");break;caseSD_CARD_TYPE_SDHC:Serial.println("SDHC");break;default:Serial.println("Unknown");} // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32if(!volume.init(card)){Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");while(1);} Serial.print("Clusters: ");Serial.println(volume.clusterCount());Serial.print("Blocks x Cluster: ");Serial.println(volume.blocksPerCluster()); Serial.print("Total Blocks: ");Serial.println(volume.blocksPerCluster()*volume.clusterCount());Serial.println(); // print the type and size of the first FAT-type volumeuint32_t volumesize;Serial.print("Volume type is: FAT");Serial.println(volume.fatType(),DEC); volumesize=volume.blocksPerCluster();// clusters are collections of blocksvolumesize *=volume.clusterCount();// we'll have a lot of clustersvolumesize/=2;// SD card blocks are always 512 bytes (2 blocks are 1KB)Serial.print("Volume size (Kb): ");Serial.println(volumesize);Serial.print("Volume size (Mb): ");volumesize/=1024;Serial.println(volumesize);Serial.print("Volume size (Gb): ");Serial.println((float)volumesize/1024.0); Serial.println("\nFiles found on the card (name, date and size in bytes): ");root.openRoot(volume); // list all files in the card with date and sizeroot.ls(LS_R|LS_DATE|LS_SIZE);} voidloop(void){}

Open the Serial Monitor at a baud rate of 9600 and if everything is working properly you’ll see the following message on the serial monitor.

If SD Card isn’t working properly or if it fails to mount to the Board, then you might see the following messages.

Reading & Writing the data

Let us learn how you can read and write the data to SD Card with Arduino microcontroller. The SD library provides useful functions for easily write in and read from the SD card.

Copy the following sketch and upload it to the Arduino Board.

#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 }
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 #include <SPI.h>#include <SD.h> File myFile; // change this to match your SD shield or module;constintchipSelect=10; voidsetup(){// 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");}} voidloop(){// nothing happens after setup}

Once the code is uploaded & if everything is ok, the following will appear on the serial monitor.

SD Card arduino Read Write Data

This indicates reading writing is done successfully. If you want to check about the files on SD Card, then you can open the SD Card file on your computer and see the following data in txt format.

Code Explanation

To write and read from the SD card, we include the SPI and SD libraries.

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

We have to initialize the SD card module at the Chip Select (CS) pin 10.

SD.begin(10);
1 SD.begin(10);

To open a new file in the SD card, we then create a file object that refers to the data file.

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

We use the following line to write data to the currently opened file.

dataFile.write(data);
12 dataFile.write(data);

We can also use the print() or println() functions to print data into the file.

dataFile.print(data); dataFile.println(data);
12 dataFile.print(data);dataFile.println(data);

Using the following line, we read the data saved on file.

dataFile.read();
1 dataFile.read();

We can only write within a file at once, so we need to close a file before proceeding to the next one.

SD.close("data.txt");
1 SD.close("data.txt");

Arduino data logger using SD card & DHT11 sensor

Building a data logger using Arduino and SD Card is so easy. This tutorial explains how to build a simple temperature and humidity data logger with a DHT11 sensor.

The DHT11 Sensor is used to sense the relative humidity and temperature and the SD card is used to save the values of the humidity and the temperature every 1 second. The values of the temperature and humidity are saved in .TXT file on the SD card.

SD Card Arduino Data Logger

Connect a DHT11 Sensor to the above circuit. Here is a circuit diagram and connection for making a data logger.

SD Card Arduino Data Logger

Copy the following code and upload it to the Arduino Board. The code requires DHT11 Library for compilation.

// Arduino data logger with SD card and DHT11 humidity and temperature sensor #include <SPI.h> // Include SPI library (needed for the SD card) #include <SD.h> // Include SD library #include <DHT.h> // Include DHT sensor library File dataFile; #define DHTPIN 4 // DHT11 data pin is connected to Arduino pin 4 #define DHTTYPE DHT11 // DHT11 sensor is used DHT dht(DHTPIN, DHTTYPE); // Initialize DHT library 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()) { Serial.println("initialization failed!"); while (1); } Serial.println("initialization done."); delay(2000); dht.begin(); } uint16_t line = 1; void loop() { delay(1000); // Read humidity byte RH = dht.readHumidity(); //Read temperature in degree Celsius byte Temp = dht.readTemperature(); dataFile = SD.open("DHT11Log.txt", FILE_WRITE); // if the file opened okay, write to it: if (dataFile) { Serial.print(line); Serial.print(": Temperature = "); Serial.print(Temp); Serial.print("°C, Humidity = "); Serial.print(RH); Serial.println("%"); // Write data to SD card file (DHT11Log.txt) dataFile.print(line++); dataFile.print(": Temperature = "); dataFile.print(Temp); dataFile.print("°C, Humidity = "); dataFile.print(RH); dataFile.println("%"); dataFile.close(); } // if the file didn't open, print an error: else Serial.println("error opening DHT11Log.txt"); }
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 // Arduino data logger with SD card and DHT11 humidity and temperature sensor#include <SPI.h> // Include SPI library (needed for the SD card)#include <SD.h> // Include SD library#include <DHT.h> // Include DHT sensor libraryFile dataFile;#define DHTPIN 4 // DHT11 data pin is connected to Arduino pin 4#define DHTTYPE DHT11 // DHT11 sensor is usedDHT dht(DHTPIN,DHTTYPE);// Initialize DHT libraryvoidsetup(){// 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 onlySerial.print("Initializing SD card...");if(!SD.begin()){Serial.println("initialization failed!");while(1);}Serial.println("initialization done.");delay(2000);dht.begin();}uint16_t line=1;voidloop(){delay(1000);// Read humiditybyteRH=dht.readHumidity();//Read temperature in degree CelsiusbyteTemp=dht.readTemperature();dataFile=SD.open("DHT11Log.txt",FILE_WRITE);// if the file opened okay, write to it:if(dataFile){Serial.print(line);Serial.print(": Temperature = ");Serial.print(Temp);Serial.print("°C, Humidity = ");Serial.print(RH);Serial.println("%");// Write data to SD card file (DHT11Log.txt)dataFile.print(line++);dataFile.print(": Temperature = ");dataFile.print(Temp);dataFile.print("°C, Humidity = ");dataFile.print(RH);dataFile.println("%");dataFile.close();}// if the file didn't open, print an error:elseSerial.println("error opening DHT11Log.txt");}

After uploading the code, open the Serial Monitor and you will see the following messages with the temperature and humidity data.

SD Card Arduino DHT11

Open the SD Card on windows using the Card Reader. Then open the txt file for the data logger. You will see the following data of temperature and humidity logged on the text file.

This is how you can use the SD Card Module with Arduino to read write data and make a data logger.

Tag » Arduino Micro Sd Card Adapter Tutorial