Hello everybody!
For a project I want to interact with the SD card and still be able to interact with it via Serial.
I've written a code for that purpose and it seems to do the job but when two or more request of listing files are done the system fails it has to be reset. I've tried to run it without asking to list any folder and it work fine for days. I've also tried the code without recording data and works fine. So I think it can be some king of crashing when accessing the SD card by two different systems.
I checked the code to ensure that none of these two functionalities works simultaneously but that doesn't seem to happen ever.
#include <SD.h>
[...]
void loop(){
if (Serial.available() > 0) {
char command[BUFFER_SIZE];
readSerial(command);
Serial.println(command);
listFiles(command);
}
if (millis() - currentTime > UPDATE_TIME) {
char line[100];
getReportLine(line);
updateReport(line);
currentTime = millis();
}
delay(100);
}
void listFiles(char* dirName) {
File dir = SD.open(dirName);
if (!dir) {
Serial.print("ERROR: Cannot list \"");
Serial.print(dirName);
Serial.println("\"");
return;
}
Serial.println("START LIST");
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
}
else {
Serial.println("");
}
entry.close();
}
Serial.println("END LIST");
}
void updateReport(char* line) {
char fileName[10];
char path[25];
bool created = false;
File reportDoc;
// Ensures the folder exists.
getFolderName(path);
getFileName(fileName);
SD.mkdir(path);
strcat(path,"/");
strcat(path,fileName);
reportDoc = SD.open(path, FILE_WRITE );
if (reportDoc) {
reportDoc.println(line);
reportDoc.close();
printNow();
Serial.print("File \"");Serial.print(path);Serial.print("\" updated [ ");
Serial.print(line); Serial.println(" ]");
}
else {
Serial.print( F("ERROR: openning the file \"") );
Serial.print(path);
Serial.println("\" hasn't been possible");
SD.begin(SD_PIN); // Trying to reconnect
}
}
If any find the troublesome or knows a better way to approach this problem it will be more than welcome.
Thank you in advance!