/*
SD card read/write with SdFat-beta
This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
created Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
Modified 12-15-20
by Warren Watson
This example code is in the public domain.
*/
#include "SdFat.h"
// Uncomment 'USE_EXTERNAL_SD' define to use an external SD card adapter or leave
// it commented to use the built in sd card.
//#define USE_EXTERNAL_SD
#ifdef USE_EXTERNAL_SD
const uint8_t SD_CS_PIN = SS;
#define SPI_CLOCK SD_SCK_MHZ(10)
#define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI, SPI_CLOCK)
#else // Use built in SD card.
// Why does this #ifdef have to be here? I do not understand. If it is defined
// then why does the compiler give this error without the #ifdef/#endif:
// "ReadWrite:39: error: 'SDCARD_SS_PIN' was not declared in this scope"
// Either it is defined previously or it is not right???
// This one has me stumped. Uncomment the #ifdef and #endif and you will see what
// happens. I am probably missing something again!
#ifdef SDCARD_SS_PIN
const uint8_t SD_CS_PIN = SDCARD_SS_PIN;
#endif // SDCARD_SS_PIN
// Setup for built in SD card.
#define SPI_CLOCK SD_SCK_MHZ(50)
#define SD_CONFIG SdioConfig(FIFO_SDIO)
#endif // USE_EXTERNAL_SD
// SdFat-beta usage
SdFs sd;
FsFile myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
if (!sd.begin(SD_CONFIG)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
// NOTE: With SdFat-Beta this is not the case anymore.
myFile = sd.open("test.txt", FILE_WRITE);
// Comment out the following line to append text to test.txt.
myFile.truncate(0);
// if the file opened okay, write to it:
if (myFile) {
#ifdef USE_EXTERNAL_SD
Serial.print("Writing test.txt to external SD card...");
#else
Serial.print("Writing test.txt to built in SD card...");
#endif
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
// re-open the file for reading:
myFile = sd.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void loop() {
// nothing happens after setup
}