I have an Arduino that is processing a string by splitting it into an array. For some reason, however, after the processing function returns, the array can only be accessed once before it appears that the values become corrupted. In other words, I can access any element of the array, but when I do, I am unable to access any other elements of the array.
void loop(){
int pin;
Serial.print("Enter command: ");
while(Serial.available()<=0)
delay(100);
///Input to the serial terminal was: "This;is;a;command". Notice how inside the getCommands() function, it will output all elements ok
char** commands = getCommands();
Serial.println(commands[1]); ///prints "is"
Serial.println(commands[0]); ///**** prints nothing, or sometimes infinite spaces****
delay(1000);
}
char** getCommands(){
char* commandIn = getSerialString();
char* commands[10];
char *str;
int i=0;
while ((str = strtok_r(commandIn, ";", &commandIn)) != NULL){
commands[i]=str;
i++;
}
Serial.println(commands[0]); ///prints "This"
Serial.println(commands[1]); ///prints "is"
Serial.println(commands[2]); ///prints "a"
return commands;
}
char* getSerialString(){
while(Serial.available()<=0)
delay(100);
int i=0;
char commandbuffer[100];
for(int a=0; a<100; a++)
commandbuffer[a]='\0';
if(Serial.available()){
delay(100);
while( Serial.available() && i< 99) {
commandbuffer[i++] = Serial.read();
}
commandbuffer[i++]='\0';
}
return commandbuffer;
}