-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuni_sd.cpp
111 lines (97 loc) · 2.51 KB
/
uni_sd.cpp
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
105
106
107
108
109
110
111
// - SD
#include "uni_sd.h"
UniSd::UniSd(int cs)
{
_cs = cs;
}
void UniSd::setup() {
// returns 1 on success
// returns 0 on failure
_status = SD.begin(_cs);
if (status()) {
Serial.println("SD initialization OK.");
return;
}
Serial.println("SD initialization failed!");
}
// Return true on success
bool UniSd::status() {
// further test that we can write and read
return testWrite();
}
// Write to a file, and read back, to ensure SD card is working
// return true on success
bool UniSd::testWrite() {
File testFile;
bool newstatus = SD.begin(_cs);
testFile = SD.open("testfile.txt", FILE_WRITE);
int result = testFile.println("testing Write");
if (result > 0) {
testFile.close();
return true;
} else {
return false;
}
}
// append the given text to the file, as well as finish with a newline character (ie: println)
bool UniSd::writeFile(const char *filename, char *text) {
if (!testWrite()) {
return false;
}
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open(filename, FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing: ");
Serial.println(text);
Serial.print(" to ");
Serial.println(filename);
if (!myFile.println(text)) {
myFile.close();
return false;
}
// close the file:
myFile.close();
Serial.println("done.");
return true;
} else {
// if the file didn't open, print an error:
Serial.print("error opening ");
Serial.println(filename);
return false;
}
}
bool UniSd::readFile(const char *filename, char *result, int max_result) {
// re-open the file for reading:
myFile = SD.open(filename);
// retry if failure
// this may happen if the SD card was removed between uses
if (!myFile) {
setup();
myFile = SD.open(filename);
}
if (myFile) {
Serial.println(filename);
// read from the file until there's nothing else in it:
int current_position = 0;
while (myFile.available()) {
char character = myFile.read();
if (current_position < max_result) {
result[current_position++] = character;
}
Serial.write(character);
}
// close the file:
myFile.close();
return true;
} else {
// if the file didn't open, print an error:
Serial.print("error opening ");
Serial.println(filename);
return false;
}
}
bool UniSd::clearFile(const char *filename) {
return SD.remove(filename);
}