【问题标题】:Interactive shell via UART serial for Arduino?通过 UART 串​​行为 Arduino 的交互式外壳?
【发布时间】:2017-01-11 04:41:25
【问题描述】:

我想通过 UART 串​​口为 Arduino 实现一个交互式 shell,使用纯 C++ OOP 风格的代码。但是我觉得如果代码中判断用户输入命令的时候if-else判断太多的话,会有点难看,

所以我想问一下,有什么方法可以避免使用 if-else 语句?例如,

之前:

while(Serial.available())
{
    serialReceive = Serial.readString();// read the incoming data as string
    Serial.println(serialReceive);
}

if(serialReceive.equals("factory-reset"))
{
    MyService::ResetSettings();
}
else if(serialReceive.equals("get-freeheap"))
{
    MyService::PrintFreeHeap();
}
else if(serialReceive.equals("get-version"))
{
    MyService::PrintVersion();
}

之后:

while(Serial.available())
{
    serialReceive = Serial.readString();// read the incoming data as string
    Serial.println(serialReceive);
}

MagicClass::AssignCommand("factory-reset", MyService::ResetSettings);
MagicClass::AssignCommand("get-freeheap", MyService::PrintFreeHeap);
MagicClass::AssignCommand("get-version", MyService::PrintVersion);

【问题讨论】:

标签: c++ arduino esp8266 arduino-esp8266 platformio


【解决方案1】:

你可以有一个数组来存储函数指针以及触发命令的字符串(你可以创建一个结构来存储两者)。

不幸的是,Arduino 不支持 std::vector 类,所以在我的示例中,我将使用 c 类型的数组。但是有一个 Arduino 库,它为 Arduino https://github.com/maniacbug/StandardCplusplus 添加了一些 STL 支持(也可以使用这个库,使函数作为参数更容易传递)

//struct that stores function to call and trigger word (can actually have spaces and special characters
struct shellCommand_t
{
  //function pointer that accepts functions that look like "void test(){...}"
  void (*f)(void);
  String cmd;
};

//array to store the commands
shellCommand_t* commands;

有了这个,您可以在开始时将命令数组初始化为一个大小,也可以在每次添加命令时调整它的大小,这取决于您的用例。

假设您已经在数组中分配了足够的空间来添加命令的基本函数可能如下所示

int nCommands = 0;
void addCommand(String cmd, void (*f)(void))
{
  shellCommand_t sc;
  sc.cmd = cmd;
  sc.f = f;

  commands[nCommands++] = sc;
}

然后在您的设置函数中,您可以按照与上面类似的方式添加命令

addCommand("test", test);
addCommand("hello world", helloWorld);

最后,在循环函数中,您可以使用 for 循环查看所有命令,检查输入字符串与所有命令字符串。

你可以像这样调用匹配命令的函数

(*(commands[i].f))();

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 2016-04-16
    • 1970-01-01
    • 2017-07-07
    • 2015-09-26
    • 2014-01-11
    • 2021-09-28
    • 2011-09-07
    • 2013-04-28
    相关资源
    最近更新 更多