ESP32

SD Card Module with Arduino & ESP32, Arduino Data Logger, ESP32 Data Logger

SD Card Module with Arduino & ESP32:

 

SD Card Module with Arduino and ESP32- There are times when you need to store the sensor’s values in a text file for later processing. In order to save the values in a text file, you will need an SD card module like the one you can see in the image given below.

SD Card Module

In this tutorial, you will learn how to interface this low-cost and commonly used SD card Module with Arduino to make an efficient Arduino Data Logger. We will also use the Micro SD card Module with the ESP32 for logging or storing the Sensor Data in a text file.

SD Card Module

In this tutorial, I will also explain how to use this Micro SD card Adaptor with the ESP32 Wifi + Bluetooth module if in case you don’t have this SD card Module.

As this is a very basic getting started tutorial on how to use the Card module and SD card adaptor with the Arduino and ESP32 so, I have tried my best to keep things simpler so that you guys can easily follow each and every step. I will use the potentiometer as the sensor for the data logging which of course you can replace with any other sensor as per your requirement.

Without any further delay let’s get started!!!



Amazon Purchase Links:

Arduino SD Card Module

8GB Micro SD Card

Micro SD Card Adaptor

ESP32 WiFi + Bluetooth Module(Recommended)

12v Adaptor:

Arduino Uno

Arduino Nano

RTC DS3231 Real Time Clock:

DHT11 Temperature and Humidity Module:

Other Tools and Components:

Super Starter kit for Beginners

Digital Oscilloscopes

Variable Supply

Digital Multimeter

Soldering iron kits

PCB small portable drill machines

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

SD Card Module Pinout and technical Specification:

SD Card Module

This is the SD Card Reading and Writing Module which can be easily interfaced with Arduino and other embedded boards and microcontrollers. With a very basic program, you can read and write to the SD card over the SPI interface. This card module is provided with the onboard 3.3V voltage regulator due to which it can be interfaced with 3.3V compatible controller boards like ESP32 and ESP8266, etc. In order to use the micro SD card with this module, you will need a micro SD card adaptor.

This SD card module is provided with male headers which are clearly labeled as

GND

3.3V

5V

CS

MOSI

SCK

MISO and

GND

If you are planning to use this Card Module with the Arduino then connect the 5v pin with the Arduino’s 5V, and if you are planning to use this Card module with the ESP32 then connect the 3.3v pin with the ESP32 3.3V pin. Never use 5 volts when using this SD card module with 3.3V compatible controller boards.

While performing the initial tests, I powered up the SD card module using 3.3V and it didn’t work. Then I powered up this module using the Arduino’s 5V and it worked. So, in a nutshell, if you are using the Card Module with the Arduino then use 5volts, and if you are using the Card Module with the ESP32 or ESP8266 then use 3.3V. For more details read my article available on electroniclinic.com. I will provide a link in the description. So, first, let’s start with the Arduino and Card Module.




SD Card Module, Description:

This SD Card Reader/Writer is ideal for many Micro-controller projects (Arduino, Pic, Versalino, etc…) Including (but not limited to) projects involving sensor and other data logging activities. Audio playing and/or recording. Video, Image, and other multimedia storage and retrieval for advanced embedded applications. Processing large quantities of data with a robot, or storing/retrieving items larger than the limited memory available on your microprocessor. This can be used for a broad range of applications from scientific data collection for biological/geological and other statistical studies in the field, to storing map data for your robots surroundings in and outside the home.

Technical Specifications:

Working Voltage: 3.3 & 5V(DC Both required) Requires SPI Capable Microprocessor Size limitations are library dependent, but most microprocessors have libraries pre-coded that will support sizes upward of 1GB 7 wires required (including power and ground) Fits standard size SD Cards Package Contents: 1*SD Card Reader/Writer

Arduino Uno and Arduino Mega SPI pins:

SD Card Module

ESP32 SPI Pins:

For the complete ESP32 Pinout read my article.

SD Card Module Interfacing with Arduino:

SD Card Module

The rightmost and leftmost legs of the Potentiometer are connected with the Arduino’s 3.3V and GND. The 5V and GND pins of the SD Card Module are connected with the Arduino’s 5v and ground. CS is connected with pin 10, MOSI is connected with pin 11, SCK is connected with pin 13, and MISO is connected with pin 12 of the Arduino.

Next, I connected the Card Module and the Potentiometer with the Arduino as per the circuit diagram already explained. Now, let’s take a look at Arduino programming.


Arduino SD Card Module Programming:

/*
 * SD Card Module Interfacing with Arduino Uno
 * https://www.electroniclinic.com/
 */

#include <SPI.h> //for the SD card module
#include <SD.h> // for the SD card

const int chipSelect = 10; 

// Create a file to store the data
File myFile;

int Vresistor = A0; // Potentiometer is connected with the Analog pin A0
int Vrdata; // A variable used to store the Potentiometer value

void setup() {


  //initializing Serial monitor
  Serial.begin(9600); // Baud rate
  pinMode(Vresistor, INPUT); // Sets the Analog pin A0 as the Input. 

    
  // setup for the SD card
  Serial.print("Initializing SD card...");

  if(!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
    
  //open file
  myFile=SD.open("DATA.txt", FILE_WRITE);

  // if the file opened ok, write to it:
  if (myFile) {
    Serial.println("File opened ok");
    // print the headings for our data
    myFile.println("Logging Variable Resistor Values");
  }
  myFile.close();
}



void LoggingVresistor() {
 
  Vrdata = analogRead(Vresistor); // reading the Potentiometer
  Serial.println(Vrdata); // print it on the Serial monitor for debugging purposes. You can Commnent this line.
  myFile = SD.open("DATA.txt", FILE_WRITE); // opens the fils DATA, which is the text file, for writing the Pot value.
  if (myFile) {
    Serial.println("open with success");
    myFile.print("Variable Resistor ");
    myFile.print(",");
    myFile.print(Vrdata);
    myFile.println();
  }
  myFile.close();
}

void loop() {
 
  LoggingVresistor();
  delay(5000); // delay of 5 seconds. 
}

SD Card Module Arduino Code Explanation:

For this program, there is no need to download any libraries. The SPI.h and SD.h libraries are already included in the Arduino IDE. The purpose of this program is to read the potentiometer and then store the value in the DATA.txt file. One more thing that I would like to mention over here is that, format your micro SD card using the FAT32 file system and then make a txt file with the name DATA and the rest Arduino will take care of. So, anyhow, LoggingVresistor() function is a user-defined function and this is the only function I am using inside the void loop() function. This function is called after every 5 seconds, reads the potentiometer, store the data in variable Vrdata then the Arduino opens the DATA.txt file to write the Potentiometer value and then close the file. I have already uploaded this program; let’s watch this Arduino Data Logger in action.

SD Card Module

As you can see we successfully stored the Potentiometer values in the DATA.txt file. Now, I am going to explain how to interface the SD Card module with the ESP32.

As explained earlier, the card Module also supports 3.3V. So, it can also be easily interfaced with the ESP32 module.


SD Card Module interfacing with ESP32:

SD Card Module

The potentiometer’s rightmost and leftmost legs are connected with the 3.3v and GND pins, while the middle leg is connected with the VP pin of the ESP32 which is the GPIO36 and this is the ADC0.

The SD Card Module 3.3V and GND pins are connected with the ESP32 3.3V and GND pins. CS is connected with D5, MOSI is connected with D23, SCK is connected with D18, and MISO is connected with D19.

SD Card Module

Next, I connected the Card Module with the ESP32 as per the circuit diagram already explained. Now, let’s take a look at the programming.

ESP32 SD Card Module Programming:

/*
 * SD Card Module Interfacing with ESP32 Wifi + Bluetooth Module
 * https://www.electroniclinic.com/
 */

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

#define SD_CS 5
String dataMessage;

int Vresistor = 36; // VP pin which is the GPIO36 pin this is adc0
int Vrdata;

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT); // i use this to supply 3.3volts to the variable resistor
  digitalWrite(13, HIGH);
  // Initialize SD card
  SD.begin(SD_CS);  
  if(!SD.begin(SD_CS)) {
    Serial.println("Card Mount Failed");
    return;
  }
  uint8_t cardType = SD.cardType();
  if(cardType == CARD_NONE) {
    Serial.println("No SD card attached");
    return;
  }
  Serial.println("Initializing SD card...");
  if (!SD.begin(SD_CS)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;    // init failed
  }
  File file = SD.open("/data.txt");
  if(!file) {
    Serial.println("File doens't exist");
    Serial.println("Creating file...");
    writeFile(SD, "/data.txt", "ESP32 and SD Card \r\n");
  }
  else {
    Serial.println("File already exists");  
  }
  file.close();
}
void loop() {

    ReadVresistor();
    logSDCard();
    delay(5000); //Wait for 5 seconds before writing the next data 
}

// Write the sensor readings on the SD card
void logSDCard() {
  dataMessage =  "Variable Resistor = " + String(Vrdata) + "\n";
  Serial.print("Save data: ");
  Serial.println(dataMessage);
  appendFile(SD, "/data.txt", dataMessage.c_str());
}
// Write to the SD card (DON'T MODIFY THIS FUNCTION)
void writeFile(fs::FS &fs, const char * path, const char * message) {
  Serial.printf("Writing file: %s\n", path);
  File file = fs.open(path, FILE_WRITE);
  if(!file) {
    Serial.println("Failed to open file for writing");
    return;
  }
  if(file.print(message)) {
    Serial.println("File written");
  } else {
    Serial.println("Write failed");
  }
  file.close();
}
// Append data to the SD card (DON'T MODIFY THIS FUNCTION)
void appendFile(fs::FS &fs, const char * path, const char * message) {
  Serial.printf("Appending to file: %s\n", path);
  File file = fs.open(path, FILE_APPEND);
  if(!file) {
    Serial.println("Failed to open file for appending");
    return;
  }
  if(file.print(message)) {
    Serial.println("Message appended");
  } else {
    Serial.println("Append failed");
  }
  file.close();
}
void ReadVresistor()
{
  Vrdata = analogRead(Vresistor);
  Serial.println(Vrdata);
}


SD Card Module ESP32 Code Explanation:

In order to use the SD Card Module with the ESP32 first, you will need to install the ESP32 board. I have a very detailed tutorial on this which explains how to add the board manager url link for the ESP32. This time you can see I added another library FS.h, you will get this library when you install the ESP32 board. So there is no need to download this library.

The purpose of this program is to read the potentiometer and then store the value in the txt file. This code automatically creates the txt file. I have already uploaded this program let’s watch this ESP32 Data Logger in action.

SD Card Module

As you can see we successfully stored the Potentiometer values in the text file. You can connect and store values of multiple sensors.

Micro SD card Adaptor Interfacing with ESP32:

SD Card Module

If in case you do not have this Card Module then you can also interface this Micro SD Card Adaptor with the ESP32.

SD Card Module

Follow these connections. These are the same exact connections that we used for the SD Card Module.  For easy interfacing, I started by soldering the male headers. Now using these male headers I can easily interface this Micro SD Card Adaptor with the ESP32 and other 3.3V compatible controller boards.

SD Card Module

I connected the Micro SD Card Adaptor with the ESP32 as per the interface connections, the Potentiometer connection with the ESP32 remains exactly the same.

We will be using the same program. Now let’s watch this Micro SD Card Adaptor and ESP32 based Data Logger in action.

SD Card Module



Arduino Temperature Data Logger using SD Card Module:

I covered the basics now let’s make a temperature data logging system using the Card Module and Arduino which saves the temperature in a text file with the date and time information. For this project, you should have a basic understanding of how to use the DHT11 Temperature and Humidity Sensor and you should also know how to use the Real Time Clock DS3231. So, I highly recommend reading these two articles, if you really want to learn how to use the DHT11 and DS3231 modules.

Arduino Temperature Data Logger Circuit Diagram:

SD Card Module

Arduino Temperature Data Logger Programming:

#include <SPI.h> //for the card module, as the SD card module supports spi
#include <SD.h> 
#include <DHT.h> // for the DHT11 Temperature and Humidity sensor
#include <RTClib.h> // for the RTC- Real Time Clock

//define DHT pin
#define DHTPIN 2   

// uncomment whatever type you're using
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
const int chipSelect = 4; 

// Create a file to store the data
File myFile;

// RTC
RTC_DS1307 rtc;

void setup() {
  //initializing the DHT sensor
  dht.begin();

  //initializing Serial monitor
  Serial.begin(9600);
  
  // setup for the RTC
  while(!Serial); // for Leonardo/Micro/Zero
    if(! rtc.begin()) {
      Serial.println("Couldn't find RTC");
      while (1);
    }
    else {
      // following line sets the RTC to the date & time this sketch was compiled
      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    }
    if(! rtc.isrunning()) {
      Serial.println("RTC is NOT running!");
    }
    
  // setup for the SD card
  Serial.print("Initializing SD card...");

  if(!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
    
  //open file
  myFile=SD.open("DATA.txt", FILE_WRITE);

  // if the file opened ok, write to it:
  if (myFile) {
    Serial.println("File opened ok");
    // print the headings for our data
    myFile.println("Date,Time,Temperature ºC");
  }
  myFile.close();
}

void loggingTime() {
  DateTime now = rtc.now();
  myFile = SD.open("DATA.txt", FILE_WRITE);
  if (myFile) {
    myFile.print(now.year(), DEC);
    myFile.print('/');
    myFile.print(now.month(), DEC);
    myFile.print('/');
    myFile.print(now.day(), DEC);
    myFile.print(',');
    myFile.print(now.hour(), DEC);
    myFile.print(':');
    myFile.print(now.minute(), DEC);
    myFile.print(':');
    myFile.print(now.second(), DEC);
    myFile.print(",");
  }
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.println(now.day(), DEC);
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.println(now.second(), DEC);
  myFile.close();
  delay(1000);  
}

void loggingTemperature() {
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  //float f = dht.readTemperature(true);
  
  // Check if any reads failed and exit early (to try again).
  if  (isnan(t) /*|| isnan(f)*/) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  
  //debugging purposes
  Serial.print("Temperature: "); 
  Serial.print(t);
  Serial.println(" *C");
  //Serial.print(f);
  //Serial.println(" *F\t"); 
  
  myFile = SD.open("DATA.txt", FILE_WRITE);
  if (myFile) {
    Serial.println("open with success");
    myFile.print(t);
    myFile.println(",");
  }
  myFile.close();
}

void loop() {
  loggingTime();
  loggingTemperature();
  delay(5000);
}


Watch Video Tutorial:

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

2 Comments

  1. Hello, I’m using esp32, and i use code like you. i can logged data to sd card, but when the file’s size is ~ 450Kb, the format of SD card become error. so, can you help me to fix it. I try to use another library like SD.h, mySD.h but, the SD’ format became error when the file’s size 450Kb. Please, give me some advices! Thank you

  2. Hi, I just use code like you, but after 1 hour, the file’s size is 40 Kb, the file is overwrite and the file’s size start at 0 kb. So, can you give some advices. I use ESP32 and sdhc card.

Leave a Reply

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

Back to top button