2010-03-26 185 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 
}