Difficulty Level: Intermediate
In this tutorial, you will learn how to interface an Arduino with an SD card module to read from and write data to the SD card. The SD card module can be used for various data logging applications, storing sensor data, or configuration files.
Most SD card modules communicate with the Arduino using the SPI protocol. The pin connections are as follows:
We’ll be using the SD.h
library, which provides built-in support for SD card modules. This library makes it easy to read and write files on SD cards.
In this tutorial, we’ll create a file on the SD card, write data to it, and read the data back. The code handles initializing the SD card, checking for errors, and using the File
class to write and read data.
#include
#include
const int chipSelect = 10; // CS pin for the SD card module
void setup() {
Serial.begin(9600);
Serial.print("Initializing SD card...");
// Check if the SD card is initialized properly
if (!SD.begin(chipSelect)) {
Serial.println("Initialization failed!");
return;
}
Serial.println("Initialization done.");
// Create or open a file for writing
File dataFile = SD.open("data.txt", FILE_WRITE);
// If the file is available, write to it
if (dataFile) {
dataFile.println("Hello, world!");
dataFile.close();
Serial.println("Data written to file.");
} else {
Serial.println("Error opening file for writing.");
}
// Now read from the file
dataFile = SD.open("data.txt");
if (dataFile) {
Serial.println("Reading data from file:");
while (dataFile.available()) {
Serial.write(dataFile.read());
}
dataFile.close();
} else {
Serial.println("Error opening file for reading.");
}
}
void loop() {
// Nothing to do here
}
SD.begin(chipSelect)
: Initializes the SD card with the specified chip select pin. If initialization fails, an error message is displayed.SD.open(filename, mode)
: Opens the specified file in read or write mode. The FILE_WRITE
mode is used for writing data.dataFile.println()
: Writes a string to the file.dataFile.available()
: Checks if data is available for reading.dataFile.read()
: Reads a byte from the file.In this tutorial, you learned how to interface an SD card with an Arduino to read and write data. This technique is useful for data logging applications and for storing persistent data in Arduino projects.