strtok运作不佳

时间:2014-02-09 20:34:50

标签: c++ c arduino

我有问题。相信我,我在凌晨1点或凌晨2点开始使用这个strtok()函数。现在是凌晨4点22分。 >。<

问题在于: 当我输入“蓝色”时,三个令牌都没问题。 2.当我输入“红色”或“绿色”时,三个标记为NULL :(。

const char s[2] = "~"; //for cutting;
char inData[100]; // Allocate some space for the string


char *token;
char *token2;
char *token3;
char x1[100];
char x2[100];
char x3[100];

char Comp(char* This) {
    while (Serial.available() > 0) // Don't read unless
                                   // there you know there is data
    {
        if(index < 99) // One less than the size of the array
        {
            inChar = Serial.read(); // Read a character
            inData[index] = inChar; // Store it
            index++; // Increment where to write next
        //  inData[index] = '\0'; // Null terminate the string
        }
    }

    token = strtok(inData, s);
    strcpy(x1,token);

    token2 = strtok(NULL, s);
    strcpy(x2,token2);

    token3 = strtok(NULL, s);
    strcpy(x3,token3);

    if (strcmp(x1,This)  == 0) {

        Serial.println(x1);
        Serial.println(x2);
        Serial.println(x3);

        for (int i=0;i<99;i++) {
            inData[i]=0;
        }
        index=0;
        return(0);
    }
    else {
        return(1);
    }
}

我如何调用函数Comp:

if(Comp("blue")==0){
    Serial.println("BLUE SELECTED");
    analogWrite(9, 0);
    analogWrite(10,255);
    analogWrite(11,255);

}

if(Comp("green")==0){
    Serial.println("GREEN SELECTED");
    analogWrite(10,0);
    analogWrite(11,255);
    analogWrite(9,255); 

}

if(Comp("red")==0){
    Serial.println("RED SELECTED");
    analogWrite(10,255);
    analogWrite(11,0);
    analogWrite(9,255); 

}

输出: 当我输入:“blue~lalalalal~kaakakakaekkewew” 它输出: 蓝色 lalalalal kawawawawewew 选择蓝色

当我输入时:“红~123~321 它输出: 红色

红色选择

当我输入:“green~123~321” 它输出 绿色

绿色选择

1 个答案:

答案 0 :(得分:0)

这是我解决bug的方式。 改变了我收到数据的方式。

char Comp(char* This) {

while(Serial.available()) {
  inChar = Serial.read();
  inData.concat(inChar);
 }

  strcpy(inData2, inData.c_str());
   token = strtok(inData2, s);
        strcpy(x1,token);

            token = strtok(NULL, s);
          strcpy(x2,token);

              token = strtok(NULL, s);
              strcpy(x3,token);

if (strcmp(x1,This)  == 0) {

Serial.println(x1);
Serial.println(x2);
Serial.println(x3);

   inData = "";
   inChar = '\0';
    return(0);
}
else {
return(1);
}

}