#include <FS.h>
#include <SD.h>
#include <SPI.h>
#define SD_CS 5
#define SD_SCK 12
#define SD_MISO 13
#define SD_MOSI 11
// -----------------------------
// Initialize SPI bus
// -----------------------------
void initSPI() {
SPI.begin(SD_SCK, SD_MISO, SD_MOSI);
}
// -----------------------------
// Initialize SD card
// -----------------------------
bool initSD() {
if (!SD.begin(SD_CS)) {
Serial.println("SD mount failed");
return false;
}
Serial.println("SD card mounted");
return true;
}
// -----------------------------
// Create folder
// -----------------------------
bool createFolder(const char *path) {
if (SD.exists(path)) return true; // already exists
if (SD.mkdir(path)) {
Serial.print("Folder created: ");
Serial.println(path);
return true;
} else {
Serial.print("Failed to create folder: ");
Serial.println(path);
return false;
}
}
// -----------------------------
// Move a file
// -----------------------------
bool moveFile(const char *fromPath, const char *toPath) {
if (!SD.exists(fromPath)) {
Serial.print("Source file not found: ");
Serial.println(fromPath);
return false;
}
File src = SD.open(fromPath, FILE_READ);
File dest = SD.open(toPath, FILE_WRITE);
if (!dest) {
Serial.print("Cannot create destination file: ");
Serial.println(toPath);
src.close();
return false;
}
uint8_t buffer[512];
while (src.available()) {
size_t bytes = src.read(buffer, sizeof(buffer));
dest.write(buffer, bytes);
}
src.close();
dest.close();
SD.remove(fromPath);
Serial.print("Moved: ");
Serial.print(fromPath);
Serial.print(" --> ");
Serial.println(toPath);
return true;
}
// -----------------------------
// Tree-style directory listing
// -----------------------------
void listTree(const char *path, uint8_t levels, String prefix = "") {
File root = SD.open(path);
if (!root || !root.isDirectory()) return;
File file = root.openNextFile();
while (file) {
bool isDir = file.isDirectory();
Serial.print(prefix);
Serial.print(isDir ? "├── " : "├── ");
Serial.print(file.name());
if (!isDir) {
Serial.print(" (");
Serial.print(file.size());
Serial.print(")");
}
Serial.println(isDir ? "/" : "");
if (isDir && levels > 0) {
String subPath = String(path) + "/" + file.name();
String newPrefix = prefix + "│ ";
listTree(subPath.c_str(), levels - 1, newPrefix);
}
file = root.openNextFile();
}
}
// -----------------------------
// Setup
// -----------------------------
void setup() {
Serial.begin(115200);
delay(1000); // give time for serial monitor
initSPI();
if (!initSD()) return;
createFolder("/logs");
createFolder("/data");
createFolder("/data/sensors");
moveFile("/sketch.ino", "/data/sketch.ino");
moveFile("/diagram.json", "/data/diagram.json");
Serial.println("SD Card Tree:");
listTree("/", 4);
}
void loop() {
// Not needed
}