2017-04-04 74 views
0

我有以下问题的话收到的字串 “30,45,33,22 \ n”; 我想在输入'\ n'char并将每个值放入一个int数组后,用逗号分割字符串。问题是我尝试了strtoksscanf的组合,它只是不起作用:Arduino的分裂在

#define PARAM_NR 10 
    Timer tt; 
    int i=0; 
    int index=0; 
    bool stringComplete=false; 
    char recString[MAX_LEN]; 
    char buf[20]; 

int commands[PARAM_NR]; 




void serialEv() 
    { 
     char aux; 
     char *token; 
     int i=0; 

     while(Serial.available()) 
     { 
     aux=Serial.read(); 
     if(i!='\n') 
     { 
     recString[i++]=aux; 
     recString[i]='\0'; 

     } 
     if(aux=='\n'); 
     { 

     token=strtok(recString,","); 
     while(token!=NULL) 
     { 
     token=strtok(NULL,","); 
      sscanf(token,"%d",&commands[index]); 
     Serial.println(commands[index]); 
     index++; 
     if(index==PARAM_NR) 
     index=0; 
     break; 
     } 
     } 


     } 
    } 

实施例:

输入:

1,1,1 

输出:

1 
0 
0 

看起来它只在第一个位置打印1,而在其他位置打印0。 如果我尝试另一种输入

例如: 输入1:

1,1,1 

输入2

3,4,5 

输出:

1 
    0 
    0 
    0 
    0 
    0 
+0

'我!='\ n''这看起来不正确。 –

回答

0

它的工作后,我换的这2条指令:

sscanf(token,"%d",&commands[index]); 
    token=strtok(NULL,","); 

我还是不明白strtok是如何工作的。

+0

PS更新:它似乎无法正常工作,因为如果我使用Serial.println(command [index]);它将在单独的行上打印所有数字。这里有什么问题? –