[!C] New Class for sd writer
This commit is contained in:
@@ -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();
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user