81 lines
1.6 KiB
C++
81 lines
1.6 KiB
C++
#pragma once
|
|
#include "FS.h"
|
|
#include <SPI.h>
|
|
#include <SD.h>
|
|
|
|
class SDHelper {
|
|
private:
|
|
uint8_t _cs;
|
|
File _stream;
|
|
String _filename;
|
|
bool _available = false;
|
|
SPIClass _spi;
|
|
|
|
String getNewFilename(fs::FS& fs) {
|
|
unsigned long i = 0;
|
|
|
|
File root = fs.open("/");
|
|
if(!root){
|
|
Serial.println("Failed to open root of SD!");
|
|
return "/coords.txt";
|
|
}
|
|
|
|
File file = root.openNextFile();
|
|
while(file){
|
|
if(String(file.name()).indexOf("coords") != -1) i++;
|
|
file = root.openNextFile();
|
|
}
|
|
|
|
return "/coords" + String(i++) + ".txt";
|
|
}
|
|
|
|
void appendFile(fs::FS& fs, const char* path, const char* message) {
|
|
Serial.printf("Appending to file: %s\n", path);
|
|
|
|
File file = fs.open(path, FILE_APPEND);
|
|
if(!file){
|
|
Serial.println("Failed to open file for appending!");
|
|
Serial.println("Trying writing insted!");
|
|
|
|
file = fs.open(path, FILE_WRITE);
|
|
if(!file){
|
|
Serial.println("Failed to open file for writing!");
|
|
return;
|
|
}
|
|
}
|
|
|
|
if(file.print(message))Serial.println("Wrote message!");
|
|
else Serial.println("Writing failed!");
|
|
|
|
file.close();
|
|
}
|
|
|
|
public:
|
|
SDHelper() : _spi(HSPI){
|
|
_spi.begin(14, 2, 15, 13);
|
|
if(!SD.begin(13, _spi)){
|
|
_available = false;
|
|
return;
|
|
}
|
|
|
|
uint8_t cardType = SD.cardType();
|
|
|
|
if (cardType == CARD_NONE) {
|
|
Serial.println("No SD card attached");
|
|
return;
|
|
}
|
|
|
|
_filename = getNewFilename(SD);
|
|
}
|
|
|
|
~SDHelper(){
|
|
if(_stream) _stream.close();
|
|
}
|
|
|
|
String Filename() { return _filename; }
|
|
|
|
void Log(const String& msg) {
|
|
appendFile(SD, _filename.c_str(), (msg + "\n").c_str());
|
|
}
|
|
};
|