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

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 − 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:
   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 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 ="datalog.txt", FILE_WRITE);

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

Updated on: 29-May-2021


Kickstart Your Career

Get certified by completing the course

Get Started