SD Card
To use the SD card on the Quarto, the SdFat library must be loaded and an SdFs object instantiated. Once an SD card has been placed in the Quarto's SD slot, the begin function can be called to connect to the card. For a full description of this class and SD functions available, please see the SD / SdFS documentation.
In the below example, we will open an SD-Card and read and write to files on the device.
#include "SdFat.h" // load SD library
#include "qCommand.h" // use qCommand to interact with SD card
char filename[] = "Data.txt"; // File to read / write to
SdFs sd; // instantiate the library as a global
qCommand qC; // instantiate qCommand as well
void setup() {
qC.addCommand("Connect", &connect); // the commands we will use
qC.addCommand("Open", &openFile);
qC.addCommand("Write", &writeFile);
qC.addCommand("Del", &delFile);
}
void loop() {
qC.readSerial(Serial); // Listen on main serial port for commands
qC.readSerial(Serial2); // Listen on secondary serial port for commands
}
void connect(qCommand& qC, Stream& S) {
if (sd.begin()) {
S.println("Successfully connected to SD Card");
} else {
S.println("Unable to connect to SD Card, was it inserted?");
}
}
void openFile(qCommand& qC, Stream& S) {
if (sd.exists(filename)) {
FsFile file = sd.open(filename,O_RDONLY); // open file as read-only
S.printf("Opened file %s with size of %u\nHere is the content:\n", filename, file.fileSize());
while (file.available()) {
S.write(file.read());
}
} else {
S.println("File does not exist");
}
}
void writeFile(qCommand& qC, Stream& S) {
// open file with 3 flags: O_WRONLY -- write only permission
// O_TRUNC -- 'truncate' file -- overwrite existing file (if is exists)
// O_CREAT -- create file if it does not exist
FsFile file = sd.open(filename, O_WRONLY| O_TRUNC| O_CREAT);
if (file) {
S.println("Writing content to file.");
while (true) {
if (qC.next() == NULL) {
break;
}
file.write(qC.current(),strlen(qC.current()));
file.write(' ');
}
file.write('\n');
file.close();
} else {
S.println("Unable to write to file");
}
}
void delFile(qCommand& qC, Stream& S) {
if (sd.remove(filename)) {
S.println("Successfully deleted file.");
} else {
S.println("Unable to delete file.");
}
}
Running this code, we can interact with it via the serial port to have it read and write from the SD Card. Below is an example:
<< open
>> File does not exist
<< write Not yet connected
>> Unable to write to file
<< connect
>> Successfully connected to SD Card
<< write Now it should work
>> Writing content to file.
<< open
>> Opened file Data.txt with size of 20
>> Here is the content:
>> Now it should work
<< del
>> Successfully deleted file.
<< open
>> File does not exist
<< write Test1
>> Writing content to file.
<< open
>> Opened file Data.txt with size of 7
>> Here is the content:
>> Test1
<< write Testing Number 2
>> Writing content to file.
<< open
>> Opened file Data.txt with size of 18
>> Here is the content:
>> Testing Number 2