2010-03-26 182 views
2

我目前正試圖用我的arduino構建一個非常基本的串行shell。將字符添加到字符串

我能夠使用Serial.read()從設備獲取輸出,並且可以獲取已輸出的字符,但是我無法確定如何將該字符添加到更長的時間以形成完整的命令。

我試圖順理成章的事情,但它不工作:

char Command[]; 

void loop(){ 
    if(Serial.available() > 0){ 
    int clinput = Serial.read(); 
    Command = Command + char(clinput); 
} 

有人能幫忙嗎?謝謝。

回答

0

如果可以,請使用std :: string。如果您不能:

snprintf(Command, sizeof(Command), "%s%c", Command, clinput); 

或(remeber檢查命令不會增長太多...)

size_t len = strlen(Command); 
Command[len] = clinput; 
Command[len + 1] = '\0'; 
+0

命令犯規點 – pm100 2010-03-26 23:33:05

+0

非常感謝,我硬是花了一天谷歌搜索:d – Jamescun 2010-03-26 23:33:43

-1
char command[MAX_COMMAND]; 
void loop(){ 
    char *p = command; 
    if(Serial.available() > 0){ 
     int clinput = Serial.read(); 
    command[p++] = (char)clinput; 
    } 
    } 
+0

應檢查緩衝區溢出雖然。 – 2010-03-26 23:35:33

+1

幾乎可以肯定是一個seg錯誤,如果它編譯的話。 p是指向char的指針,而不是char數組的索引。 – 2010-03-26 23:36:08

+0

@simon你是認真的嗎? char *完美地指向char數組。希望你會低調接受的答案,因爲這寫入一個統一的指針 – pm100 2010-03-27 00:16:18

0

使用std::ostringstreamstd::string

 
#include <sstream> 
#include <string> 

std::string loop() 
{ 
    std::ostringstream oss; 
    while (Serial.available() > 0){ 
     oss << static_cast<char>(Serial.read()); 
    } 
    return oss.str(); 
} 

您也可以將多個std :: string實例與operator +連接起來。

0

自也標記C,

char *command = (char *)malloc(sizeof(char) * MAXLENGTH); 
*command = '\0'; 

void loop(){ 
    char clinput[2] = {}; //for nullifying the array 
    if(Serial.available() > 0){ 
    clinput[0] = (char)Serial.read(); 
    strcat(command, clinput); 
} 
+0

strcat需要char *作爲其第二個參數 – 2010-03-26 23:39:59

+0

@Simon Nickerson:已更新。謝謝! – 2010-03-27 00:09:22

3

你必須寫逐個字符到一個數組。 例如這樣:

#define MAX_COMMAND_LENGTH 20 

char Command[MAX_COMMAND_LENGTH]; 
int commandLength;  

void loop(){ 
    if(Serial.available() > 0){ 
    int clinput = Serial.read(); 
    if (commandLength < MAX_COMMAND_LENGTH) { 
     Command[commandLength++] = (char)clinput; 
    } 
} 

順便說一下:這是不完整的。例如。 commandLength必須以0

1

您需要分配足夠的空間在command容納最長條命令 ,然後將字符寫入它的進來,當你用完的人物, 你空終止命令並進行初始化然後返回。在任何事情,的sizeof(命令)= 4(或者2的Arduino)

char Command[MAX_COMMAND_CHARS]; 

void loop() { 
    int ix = 0; 
    // uncomment this to append to the Command buffer 
    //ix = strlen(Command); 

    while(ix < MAX_COMMAND_CHARS-1 && Serial.available() > 0) { 
    Command[ix] = Serial.read(); 
    ++ix; 
    } 

    Command[ix] = 0; // null terminate the command 
}