[!C] New Class for sd writer

This commit is contained in:
Ano-sys
2025-08-10 15:35:09 +02:00
parent 94402e106c
commit cd30c25956
2 changed files with 69 additions and 10 deletions
+58
View File
@@ -0,0 +1,58 @@
#include <SPI.h>
#include <SD.h>
typedef enum{
FAM_R,
FAM_W
} FileAccessMode;
class SDHelper {
private:
uint8_t _cs;
FileAccessMode _fam;
File _stream;
String _filename;
bool _available = false;
SPIClass _spi(HSPI);
String getNewFilename() {
static unsigned long i = 0;
String name;
do {
name = "coords" + String(i++) + ".txt";
} while (SD.exists(name.c_str()));
return name;
}
public:
SDHelper(uint8_t csPin, FileAccessMode fam, String filename = "") : _cs(csPin), _fam(fam) {
_spi.begin(14, 2, 15, 13);
if(!SD.begin(_cs, _spi)){
_available = false;
return;
}
if(_fam == FAM_W){
_filename = filename.length() ? filename : getNewFilename();
_stream = SD.open(_filename.c_str(), FILE_WRITE);
}
else {
_filename = filename;
_stream = SD.open(_filename.c_str(), FILE_READ);
}
_available = (bool)_stream;
}
~SDHelper(){
if(_stream) _stream.close();
}
bool Available() const { return _available; }
const String& filename() const { return _filename; }
void Log(const String& msg) {
if(_fam != FAM_W || !_stream) return;
_stream.println(msg);
_stream.flush();
}
};