2017-01-11 2 views
1

순수한 C++ OOP 스타일 코드와 함께 Arduino 용 UART 직렬 포트를 통해 대화식 셸을 구현하고 싶습니다. 하지만 코드에서 사용자 입력 명령을 판단 할 때 if-else 판단이 너무 많으면 다소 추울 것입니다.Arduino 용 UART 직렬을 통한 대화식 셸?

그래서 저는 if-use를 사용하지 않는 방법이 있는지 묻고 싶습니다. 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(); 
} 

AFTER : 당신은 명령을 트리거하는 문자열과 함께 함수 포인터를 저장하는 배열을 가질 수

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); 

답변

3

는 (당신은에 구조체를 만들 수 있습니다 둘 다 저장하십시오).

아쉽게도 Arduino는 std :: vector 클래스를 지원하지 않으므로 예제에서는 c 유형 배열을 사용합니다. 그러나 아두 이노 https://github.com/maniacbug/StandardCplusplus 명령 배열을 초기화 할 수 있습니다 이것으로

//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; 

(이 라이브러리는 쉽게 인수로 함수를 전달하기 위해 기능 라이브러리를 사용할 수 있습니다)에 대한 몇 가지 STL 지원을 추가 아두 이노를위한 라이브러리가있다 명령을 추가 할 때마다 크기를 시작하거나 크기를 조정할 때 사용 사례에 따라 다릅니다.

당신은 이미 당신이 당신이 비슷한 방식으로 당신의 명령을 추가 할 수 있습니다 설정 기능 안에 그런 다음이

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))(); 
처럼 일치하는 명령의 함수를 호출 할 수 있습니다
관련 문제