SD Card Module
SD Card Module
The SD Card module allows you to add data storage capability to your Arduino
from a regular memory card.
The module has a holder for regular size SD cards, a voltage regulator,
capacitors and resistors for SPI-bus.
Here you will learn how to initialize, write to and read from your SD Card using
SD- and SPI-libraries.
#include <SD.h>
#include <SPI.h>
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
}
Serial.println("Initializing SD card...");
Serial.println();
pinMode(cs, OUTPUT);
void loop()
{
}
If it does initialize, try removing your removing your SD card and notice that it will fail to initialize.
void setup()
{
char myFileName[] = "MyFile.txt"; // The name of the file we will create
}
Serial.println("Initializing SD card...");
Serial.println();
pinMode(cs, OUTPUT);
// Documentation says you're supposed to do this even if you don't use it:
pinMode(SS, OUTPUT);
// Lets check to make sure that the SD card doesn't already have our file
if (! SD.exists(myFileName)){
// This next statement will open a file for writing if it exists
// If it does not exist, it will create that file. That's what we're doing here.
myFile = SD.open(myFileName, FILE_WRITE);
// This next statement checks to see if the file
myFile.println("My 1st Line of Data"); // Send Your First Line to that file
myFile.flush(); // Save it.
}
else {
// We got here because the file already exists.
// Therefore we're simple opening the file and writing to it. We will add another line
at the end.
myFile = SD.open(myFileName, FILE_WRITE);
myFile.println("Another Line of Data"); // Send Your First Line to that file
myFile.flush();
}
Serial.println("Done Writing");
}
void loop()
{
}
Test your Creating and Writing to SD Card Sketch
1. Start with a clear SD card
2. Open your serial monitor and close it when it is done
3. Remove your SD Card and insert into your computer
4. Navigate to the SD card and find “MyFile.txt”
5. Open the text file and see that it contains “My 1st Line of Data”
6. Remove the SD Card from your computer and reinsert into your SD Card Module
7. Repeat steps 2, 3 and 4
8. Open the text file and see that it now also contains “Another Line of Data”
#include <SD.h>
#include <SPI.h>
void loop() { }