/*
Reading lines from SD card
Comparing each line with the entries of a given string array
Calls the related function (if found)
This version makes use of String objects/functions
Forum: https://forum.arduino.cc/t/help-text-file-to-function-calls/1154798/4
Wokwi: https://wokwi.com/projects/372315676518280193
ec2021
2023-08-06
*/
#include <SD.h>
#define CS_PIN 10
void sinelon() {
Serial.println("Calling sinelon!");
delay(2000);
}
void stranger() {
Serial.println("Calling stranger!");
delay(2000);
}
void rainbowWithGlitter() {
Serial.println("Calling rainbowWithGlitter!");
delay(2000);
}
// Make sure that the Sequence list is in the same order and length as the
// pattern function list and to use the identical names in this array and
// in the SD card text file!
//
typedef void (*SimplePatternList[])();
SimplePatternList gPatterns = { sinelon, stranger, rainbowWithGlitter};
constexpr byte noOfSeq = 3;
constexpr char *Sequence[noOfSeq] = {
"sinelon", "stranger", "rainbowWithGlitter"
};
void setup() {
Serial.begin(115200);
Serial.print(F("Initializing SD card... "));
if (!SD.begin(CS_PIN)) {
Serial.println(F("Card initialization failed!"));
while (true);
}
Serial.println(F("initialization done.\n-------------------------------------------\n\n"));
readSequence();
Serial.println(F("-------------------------------------------"));
Serial.println(F("End of Sequences"));
}
void loop() {
// nothing happens after setup finishes.
}
void readSequence() {
String aLine;
File textFile = SD.open(F("sequence.txt"));
int i = 0;
if (textFile) {
while (textFile.available()) {
aLine = textFile.readStringUntil('\n');
aLine.trim(); // trim white spaces
aLine.replace("\d", ""); // remove carriage return from string
if (aLine.length() > 0) {
compare(aLine);
}
}
textFile.close();
} else {
Serial.println(F("error opening sequence.txt"));
}
}
void compare(String &line) {
int No = -1;
char buf[80];
for (int i = 0; i < noOfSeq; i++) {
if (line == Sequence[i]) {
No = i;
}
}
sprintf(buf, "%-25s relates to ", line.c_str());
Serial.print(buf);
if (No != -1) {
Serial.println(No);
gPatterns[No]();
//
// This is where further action can be taken
//
// "No" equals gCurrentPatterNumber
} else {
Serial.println("-");
Serial.println(F("Calling nothing .... ;-) "));
delay(2000);
}
}