// 1. Definição do tipo de função que o comando vai chamar
typedef void (*CommandFunc)(String args);
// 2. Estrutura para associar o nome à função
struct ShellCommand {
const char* name;
CommandFunc function;
};
// 3. Implementação das funções dos comandos
void cmdLed(String args) {
if (args == "on") {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("LED ligado.");
} else {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("LED desligado.");
}
}
void cmdHello(String args) {
Serial.println("Ola! Voce digitou: " + args);
}
// 4. Tabela de comandos (Array de Structs)
ShellCommand shellTable[] = {
{"led", cmdLed},
{"hello", cmdHello}
};
const int numCommands = sizeof(shellTable) / sizeof(ShellCommand);
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
Serial.println("\n--- Micro Shell Pronto ---");
}
void loop() {
if (Serial.available() > 0) {
String input = Serial.readStringUntil('\n');
input.trim(); // Remove espaços e \r
if (input.length() == 0) return;
// Separa o comando dos argumentos
int spaceIdx = input.indexOf(' ');
String cmd = (spaceIdx == -1) ? input : input.substring(0, spaceIdx);
String args = (spaceIdx == -1) ? "" : input.substring(spaceIdx + 1);
// 5. Busca e execução no array de structs
bool found = false;
for (int i = 0; i < numCommands; i++) {
if (cmd == shellTable[i].name) {
shellTable[i].function(args);
found = true;
break;
}
}
if (!found) {
Serial.println("Comando desconhecido: " + cmd);
}
}
}