#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))
#define blueLed 12
#define whiteLed 13
#define redLed 16
#define MAX_TOKENS 10
#define MAX_INPUT_LENGTH 30
char inputBuffer[MAX_INPUT_LENGTH];
char* tokens[MAX_TOKENS];
byte tokenIndex = 0;
const char* validCommands[] = { "dog", "goat", "cat" };
void dogCommand();
void goatCommand();
void catCommand();
void (*funcPtrs[ARRSIZE(validCommands)])() = { &dogCommand, &goatCommand, &catCommand };
void getInput() {
while (!Serial.available());
Serial.readBytesUntil('\n', inputBuffer, MAX_INPUT_LENGTH);
}
void tokeniseInput() {
char* token = strtok(inputBuffer, " ,.-");
while (token != NULL && tokenIndex < MAX_TOKENS) {
tokens[tokenIndex++] = token;
token = strtok(NULL, " ,.-");
if (tokenIndex >= MAX_TOKENS)
Serial.println(" ERR! Max Tokens Reached");
}
}
void printTokens() {
for (byte i = 0; i < tokenIndex; i++) {
Serial.print("Token Stored: ");
Serial.println(tokens[i]);
}
}
void reset() {
for (byte i = 0; i < MAX_INPUT_LENGTH; i++) inputBuffer[i] = '\0';
for (byte i = 0; i < MAX_TOKENS; i++) tokens[i] = nullptr;
tokenIndex = 0;
}
void processCommands() {
for (byte i = 0; i < tokenIndex; i++) {
for (byte j = 0; j < ARRSIZE(validCommands); j++) {
if (strcmp(tokens[i], validCommands[j]) == 0) (funcPtrs[j])();
}
}
}
void dogCommand() {
Serial.println("dog");
digitalWrite(whiteLed, HIGH);
delay (500);
digitalWrite(whiteLed, LOW);
}
void goatCommand() {
Serial.println("goat");
digitalWrite(blueLed, HIGH);
delay (500);
digitalWrite(blueLed, LOW);
}
void catCommand() {
Serial.println("cat");
digitalWrite(redLed, HIGH);
delay (500);
digitalWrite(redLed, LOW);
}
void setup() {
Serial.begin(9600);
//Serial.println 1("Enter Your Commands:");
pinMode(blueLed, OUTPUT);
pinMode(whiteLed, OUTPUT);
pinMode(redLed, OUTPUT);
delay(2000);
}
void loop() {
getInput();
tokeniseInput();
processCommands();
reset();
}