-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsd_card.h
105 lines (81 loc) · 1.88 KB
/
sd_card.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const char* FILE_INTEGRITY_SYMBOL = "~";
const char* DATA_FILE_NAME = "data.txt";
boolean initializeSD() {
Serial.println(F("Initializing SD card..."));
if (!SD.begin()) {
Serial.println(F("SD card initialization failed"));
return false;
}
Serial.println(F("SD card is ready to use."));
return true;
}
boolean dataFileExists() {
return SD.exists(DATA_FILE_NAME);
}
boolean removeDataFile() {
if (!dataFileExists()) {
return true; // file doesnt exist, we are OK to proceed
}
if (!SD.remove(DATA_FILE_NAME)) {
Serial.println(F("Error while removing file."));
return false;
}
Serial.println(F("File removed successfully."));
return true;
}
File createFile(char *fileName) {
File file = SD.open(fileName, FILE_WRITE);
if (file) {
Serial.println(F("File created successfully."));
}
else {
Serial.println(F("Error while creating file."));
}
return file;
}
File createDataFile() {
return createFile(DATA_FILE_NAME);
}
boolean writeToFile(File *file, char *text) {
if (!file) {
Serial.println(F("Couldn't write to file"));
return false;
}
file->println(text);
return true;
}
void closeFile(File *file) {
if (file) {
file->close();
Serial.println(F("File closed"));
}
}
File openFile(char *fileName) {
File file = SD.open(fileName);
if (file) {
Serial.println(F("File opened with success!"));
}
else {
Serial.println(F("Error opening file..."));
}
return file;
}
File openDataFile() {
return openFile(DATA_FILE_NAME);
}
String readFileContent(File *file) {
String line = "";
while (file->available()) {
line += (char)file->read();
}
return line;
}
boolean isDataFileOK(File *file) {
if (file->seek(file->size() - 1)) {
if ( ((char)file->peek()) == FILE_INTEGRITY_SYMBOL[0]) {
file->seek(0); // return index to start of file
return true;
}
}
return false;
}