#include <SD.h>
#include <SPI.h>
#define pushButton 2
#define pinCS 10
#define configName "config.txt"
#define fileTitle "test"
#define fileExtension ".txt"
String fullFileName = fileTitle;
File root;
bool buttonState = false;
// Function to write to file
bool writeFile(String fileName, String data);
// Function to read to file
String readFile(String fileName);
//
void updateConfig(String configfileName);
//
void printDirectory(File dir, int numTabs);
void setup() {
Serial.begin(9600);
pinMode(pushButton, INPUT_PULLUP);
SD.begin(pinCS);
//
updateConfig(configName);
fullFileName += "_" + readFile(configName) + fileExtension;
writeFile(fullFileName, "Testing 1, 2, 3.\n");
// Serial.println(readFile(configName));
// Serial.println(readFile(fullFileName));
}
void loop() {
if (!buttonState && digitalRead(pushButton) == LOW) {
root = SD.open("/");
if (root) {
printDirectory(root, 0);
} else { Serial.println("not root"); }
buttonState = true;
Serial.println("Ok push button.");
} else if (digitalRead(pushButton) == HIGH) {
buttonState = false;
}
delay(100);
}
// Function to write to file
bool writeFile(String fileName, String data) {
File myFile = SD.open(fileName, FILE_WRITE);
if (myFile) {
myFile.print(data);
myFile.close();
return 0;
} else {
Serial.print("Error opening file for writing: ");
Serial.println(fileName);
return 1;
}
}
// Function to read to file
String readFile(String fileName) {
String data;
File myFile = SD.open(fileName, FILE_READ);
if (myFile) {
while (myFile.available()) {
data += (char)myFile.read();
}
myFile.close();
return data;
} else {
Serial.print("Error opening file for reading: ");
Serial.println(fileName);
return "";
}
}
//
void updateConfig(String configFileName) {
String data = readFile(configFileName);
if (data == "") {
writeFile(configFileName, "0");
} else {
SD.remove(configFileName);
writeFile(configFileName, String(data.toInt()+1));
}
}
// NO USING
void printDirectory(File dir, int numTabs) {
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
printDirectory(entry, numTabs + 1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}