Bird
0
0
Arduinoprogramming~5 mins

SPI with SD card module in Arduino

Choose your learning style9 modes available
Introduction

SPI helps your Arduino talk to the SD card quickly. It lets you read and save files on the card.

You want to save sensor data to a file on an SD card.
You need to read a configuration file stored on an SD card.
You want to log events or errors for later review.
You want to store images or large data that won't fit in Arduino memory.
Syntax
Arduino
SPI.begin();
SD.begin(chipSelectPin);
File myFile = SD.open("filename.txt", FILE_WRITE);

SPI.begin() starts the SPI bus.

SD.begin(chipSelectPin) sets up the SD card on the right pin.

Examples
Start SPI and initialize SD card on pin 10.
Arduino
SPI.begin();
SD.begin(10);
Open or create a file named "log.txt" to write data.
Arduino
File dataFile = SD.open("log.txt", FILE_WRITE);
Write a line to the file and close it safely.
Arduino
if (dataFile) {
  dataFile.println("Hello, SD card!");
  dataFile.close();
}
Sample Program

This program starts SPI and the SD card on pin 10. It writes "Hello, SD card!" to a file named "test.txt" and prints status messages 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", FILE_WRITE);

  if (myFile) {
    myFile.println("Hello, SD card!");
    myFile.close();
    Serial.println("Wrote to test.txt");
  } else {
    Serial.println("Error opening test.txt");
  }
}

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

Make sure your SD card module's chip select pin matches the pin number in SD.begin().

Use a 3.3V or 5V SD card module compatible with your Arduino.

Always close files after writing to save data properly.

Summary

SPI connects Arduino and SD card for fast data transfer.

Use SD.begin() with the chip select pin to start the card.

Open files with SD.open(), write data, then close files.