0
0
Arduinoprogramming~5 mins

Reading data from SD card in Arduino

Choose your learning style9 modes available
Introduction

Reading data from an SD card lets your Arduino get information stored on a small memory card. This helps your project remember or use data even after it is turned off.

You want to log sensor readings over time and save them for later.
You need to load settings or messages from a file instead of hardcoding them.
You want to read a list of instructions or commands stored on the card.
You want to display text or data stored on the SD card on a screen.
You want to transfer data between your Arduino and a computer using the SD card.
Syntax
Arduino
File myFile = SD.open("filename.txt");
if (myFile) {
  while (myFile.available()) {
    char c = myFile.read();
    // use the character c
  }
  myFile.close();
} else {
  // error opening the file
}

Use SD.open() to open a file for reading.

Always check if the file opened successfully before reading.

Examples
This example reads the whole file and sends it to the Serial Monitor.
Arduino
File dataFile = SD.open("data.txt");
if (dataFile) {
  while (dataFile.available()) {
    Serial.write(dataFile.read());
  }
  dataFile.close();
} else {
  Serial.println("Error opening data.txt");
}
This reads one line from the file until a newline character.
Arduino
File logFile = SD.open("log.txt");
if (logFile) {
  String line = logFile.readStringUntil('\n');
  Serial.println(line);
  logFile.close();
} else {
  Serial.println("Error opening log.txt");
}
Sample Program

This program initializes the SD card, opens a file named "test.txt", and prints its contents to the Serial Monitor.

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

const int chipSelect = 10;

void setup() {
  Serial.begin(9600);
  while (!Serial) {}

  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("Initialization failed!");
    return;
  }
  Serial.println("Initialization done.");

  File myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("Contents of test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("Error opening test.txt");
  }
}

void loop() {
  // nothing here
}
OutputSuccess
Important Notes

Make sure your SD card is formatted as FAT16 or FAT32 for Arduino compatibility.

Use the correct chip select pin for your Arduino board and SD card module.

Always close the file after reading to free resources.

Summary

Use SD.open() to open files on the SD card for reading.

Check if the file opened successfully before reading data.

Read data using methods like read() or readStringUntil() and close the file when done.