IOT

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

In this tutorial, we’ll learn how to read, write, save, and create a data logger using an SD Card Module and an Arduino microcontroller. We can utilise the SD Card Module to add memory to the Arduino project in order to store data, media, and other items.

Micro SD Adaptor is another name for the Micro SD Card Reader Module. The Module is a straightforward way to move data to and from a normal SD card. As a result, the lesson covers how to read SD Card information as well as how to read and write data to SD Card.

Similarly, making a data logger with an Arduino and an SD card is really simple. The DHT11 sensor is used to measure relative humidity and temperature, and the SD card is used to save the humidity and temperature information in txt format every 1 second.

Hardware Required:

  • Arduino UNO Board with ATmega328 Microcontroller
  • Micro-SD Card Adapter
  • 4-16 GB SD Card
  • USB Card reader

SD Card Module/Adapter

The SD card module is particularly handy for data logging tasks. SPI mode and SDIO mode are the two methods for interacting with micro SD cards. SPI Mode is preferred by hobbyists like us for interfacing since it is simpler than SDO Mode, which is more complicated.

SD Card Module

Micro SD Cards have a 3.3 V operating voltage. As a result, we can’t use the SD Card with 5V logic directly. However, the module includes an ultra-low dropout regulator that converts voltages between 3.3V and 6V to 3.3V. On the module, there is also a Logic Level Converter IC 74LVC125A that changes the interface logic from 3.3V-5V to 3.3V.

Micro SD Card Module Pinout

There are a total of six pins (GND, VCC, MISO, MOSI, SCK, CS) on an 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

You must first format the micro SD card before inserting it into the module. The SD card should be formatted as FAT16 or FAT32.

Insert the SD card into your computer to format it. Right-click on the SD card in My Computer. There is a new window that appears. As a Formatting option, choose FAT32. Then, to begin the formatting process, press Start.

Now that the SD card has been properly formatted, you can utilize it in project applications using the SD Card Module.

Interfacing SD Card Module with Arduino

Let’s look at how to use an SD Card Module with an Arduino to read and write data or create a data logger. Because the SD Card Module uses the SPI communication protocol, we must connect it to the Arduino Board’s SPI pin.

SD Card Module Arduino Interfacing

As shown in the circuit diagram, connect the SD Card Module to the Arduino. SPI pins 13 (SCK), 12 (MISO), and 11 are used on Arduino boards like the UNO/Nano (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

Upload the following code to the Arduino Board to ensure that everything is wired correctly and that the SD card is operating properly. Make sure you’re using the correct board and COM port.



// 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) {
}

If everything is working properly, open the Serial Monitor at a baud rate of 9600 and you should see the following message on the serial monitor.

You may notice the following alerts if your SD Card isn’t working properly or if it fails to mount to the Board.

Reading & Writing the data

Let’s look at how to read and write data to an SD card using an Arduino microcontroller. The SD library includes functions that make it simple to write to and read from the SD card.

Copy and paste the following sketch onto 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
}

The following will appear on the serial monitor once the code has been uploaded and everything is working properly.

SD Card arduino Read Write Data

This signifies that the reading and writing have been completed satisfactorily. If you wish to look at the files on your SD Card, open the file on your computer and look at 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>

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

SD.begin(10);

We next create a file object that corresponds to the data file in order to open a new file on the SD card.

dataFile = SD.open(“data.txt”, FILE_WRITE);

To write data to the currently open file, we use the following line.

dataFile.write(data);

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

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

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

dataFile.read();

We can only write in one file at a time, so we must close one before moving on to the next.

SD.close(“data.txt”);

Arduino data logger using SD card & DHT11 sensor

It’s quite simple to make a data logger with an Arduino and an SD card. This tutorial shows how to use a DHT11 sensor to make a simple temperature and humidity data logger.

The DHT11 sensor is used to sense relative humidity and temperature, and the SD card is used to save humidity and temperature readings every 1 second. The temperature and humidity readings are recorded to a.TXT file on the SD card.

SD Card Arduino Data Logger

Connect the above circuit to a DHT11 sensor. A circuit diagram and connections for building a data logger are shown below.

SD Card Arduino Data Logger

Copy the code below and paste it into the Arduino board. Compilation of the code necessitates the use of the DHT11 Library .



// 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”);
}

When you open the Serial Monitor after uploading the code, you should see the following messages with temperature and humidity data.

SD Card Arduino DHT11

Using the Card Reader, open the SD Card on Windows. Then open the data logger’s txt file. On the text file, you’ll find the following temperature and humidity data.

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

Leave a Reply

Your email address will not be published.