/*
Reading lines from SD card
Comparing each line with the entries of a given string array
Calls the related function (if found)
This version uses char arrays / c strings
Forum: https://forum.arduino.cc/t/help-text-file-to-function-calls/1154798/4
Wokwi: https://wokwi.com/projects/372306615255913473
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() {
constexpr byte cLen = 40;
char aLine[cLen + 1];
aLine[cLen] = '\0';
File textFile = SD.open(F("sequence.txt"));
int i = 0;
if (textFile) {
while (textFile.available()) {
char c = textFile.read();
if (i >= cLen) {
i = 0;
}
if (c >= ' ') {
aLine[i] = c;
i++;
}
if (c == 10 && i > 0) {
aLine[i] = '\0';
compare(aLine);
i = 0;
}
}
textFile.close();
if (i > 0) {
aLine[i - 1] = '\0';
compare(aLine);
}
} else {
Serial.println(F("error opening sequence.txt"));
}
}
void compare(char * line) {
int No = -1;
for (int i = 0; i < noOfSeq; i++) {
if (strcmp(line, Sequence[i]) == 0 ) {
No = i;
}
}
char buf[80];
sprintf(buf, "%-25s relates to ", line);
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);
}
}