0
0
Arduinoprogramming~5 mins

Writing data to SD card in Arduino

Choose your learning style9 modes available
Introduction

Writing data to an SD card lets your Arduino save information even when it is turned off. This is useful for keeping records or logs.

You want to save sensor readings over time to check later.
You need to store user settings that stay after power off.
You want to log events or errors during your Arduino program.
You want to save data for a project that runs without a computer.
Syntax
Arduino
File dataFile = SD.open("filename.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println("Your data here");
  dataFile.close();
} else {
  // error opening file
}

Use SD.open() with FILE_WRITE to open or create a file for writing.

Always close the file after writing to save data properly.

Examples
This writes a line of text to a file named log.txt on the SD card.
Arduino
File dataFile = SD.open("log.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println("Hello, SD card!");
  dataFile.close();
}
This writes two numbers separated by a comma, like a CSV row.
Arduino
File dataFile = SD.open("data.csv", FILE_WRITE);
if (dataFile) {
  dataFile.print(23);
  dataFile.print(",");
  dataFile.println(42);
  dataFile.close();
}
Sample Program

This program initializes the SD card, then writes a line of text to a file named test.txt. It prints messages to the Serial Monitor to show progress.

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 dataFile = SD.open("test.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println("Data saved to SD card.");
    dataFile.close();
    Serial.println("Data written to test.txt");
  } else {
    Serial.println("Error opening test.txt");
  }
}

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

Make sure your SD card module is connected correctly to the Arduino pins.

Use the correct chip select pin number for your hardware.

Always check if the file opened successfully before writing.

Summary

Use SD.open() with FILE_WRITE to write data to a file on the SD card.

Always close the file after writing to save your data.

Check SD card initialization and file opening to avoid errors.