Store a new file in SD Card connected to Arduino


In this tutorial, we will create a new file in an SD Card connected to Arduino Uno.

Circuit Diagram

The circuit diagram is shown below −

As you can see, you need to make the following connections −

SD Card HolderArduino Uno
Vcc5V
GNDGND
MISO12
MOSI11
SCK13
CS10

Only for the Vcc, make sure that your SD Card Holder takes 5V as input. If it takes in 3.3V, connect it to the 3.3V pin on Arduino Uno.

Code Walkthrough

We will be walking through the example code that comes in with the inbuilt SD library. You can access it from File → Examples → SD → Datalogger

Alternatively, you can access the code on GitHub −https://github.com/adafruit/SD/blob/master/examples/Datalogger/Datalogger.inoWe begin with including the SPI and SD libraries and setting the chipSelect pin (we will set it to 10)

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

const int chipSelect = 10;

Within the Setup, we initialize Serial and the SD Card.

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...");
   // see if the card is present and can be initialized:
   if (!SD.begin(chipSelect)) {
      Serial.println("Card failed, or not present");
      // don't do anything more:
      while (1);
   }
   Serial.println("card initialized.");
}

In the loop, we read data from 3 analog pins, and store it in a string called dataString. Then, we open a file datalog.txt in the FILE_WRITE mode using the SD.open() function. This function creates the file if it doesn’t exist. Then we append the new dataString to the file and close the file. The standard command dataFile.println() is used for appending to the file.

void loop() {
   // make a string for assembling the data to log:
   String dataString = "";

   // read three sensors and append to the string:
   for (int analogPin = 0; analogPin < 3; analogPin++) {
      int sensor = analogRead(analogPin);
      dataString += String(sensor);
      if (analogPin < 2) {
         dataString += ",";
      }
   }

   // open the file. note that only one file can be open at a time,
   // so you have to close this one before opening another.
   File dataFile = SD.open("datalog.txt", FILE_WRITE);

   // if the file is available, write to it:
   if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      Serial.println(dataString);
   }
   // if the file isn't open, pop up an error:
   else {
      Serial.println("error opening datalog.txt");
   }
}

Updated on: 29-May-2021

520 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements