#include <SD.h>
#define CS_PIN 10
File textFile;
File root;
uint32_t find(const char *target) {
return findUntil(target, (char*) "");
}
uint32_t find(const char *target, size_t length) {
return findUntil(target, length, NULL, 0);
}
uint32_t findUntil(const char *target, const char *terminator) {
return findUntil(target, strlen(target), terminator, strlen(terminator));
}
uint32_t findUntil(const char *target, size_t targetLen, const char *terminator, size_t termLen) {
size_t index = 0; // maximum target string length is 64k bytes!
size_t termIndex = 0;
int c;
uint32_t pos = 0;
if (*target == 0)
return 1; // return true if target is a null string
while ((c = timedRead()) > 0) {
pos++;
if (c != (unsigned char)target[index])
index = 0; // reset index if any char does not match
if (c == (unsigned char)target[index]) {
//////Serial.print("found "); Serial.write(c); Serial.print("index now"); Serial.println(index+1);
if (++index >= targetLen) { // return true if all chars in the target match
return pos - targetLen;
}
}
if (termLen > 0 && c == terminator[termIndex]) {
if (++termIndex >= termLen)
return 0; // return false if terminate string found before target string
} else
termIndex = 0;
}
return 0;
}
int timedRead() {
int c;
unsigned long _startMillis;
unsigned long _timeout = 1000;
_startMillis = millis();
do {
c = textFile.read();
if (c >= 0)
return c;
if (_timeout == 0)
return -1;
yield();
} while (millis() - _startMillis < _timeout);
return -1; // -1 indicates timeout
}
void setup() {
Serial.begin(115200);
Serial.print("Initializing SD card... ");
if (!SD.begin(CS_PIN)) {
Serial.println("Card initialization failed!");
while (true);
}
Serial.println("initialization done.");
Serial.println("Files in the card:");
root = SD.open("/");
printDirectory(root, 0);
Serial.println("");
// Example of reading file from the card:
}
void loop() {
if (Serial.available()) {
String str = Serial.readStringUntil('\n');
Serial.println(str.length());
textFile = SD.open("wokwi.txt");
if (textFile) {
Serial.println("wokwi.txt: ");
char charr[10];
str.toCharArray(charr, 10);
bool found = false;
//int i = 0;
while (!found) {
find("p=\"");
str = textFile.readStringUntil('&');
//Serial.println(str);
found = findUntil(charr, "lable");
}
//found = textFile.find(charr);
Serial.println(str);
textFile.close();
} else {
Serial.println("error opening wokwi.txt!");
}
}
}
void printDirectory(File dir, int numTabs) {
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
printDirectory(entry, numTabs + 1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}