簡體   English   中英

通過用於Arduino的UART串行的交互式shell?

[英]Interactive shell via UART serial for Arduino?

我想通過Arduino的UART串行端口使用純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);

您可以擁有一個存儲函數指針以及觸發命令的字符串的數組(您可以創建一個結構來存儲兩者)。

不幸的是,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))();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM