Clear existing array when getting new serial command
To clear an array you would do:
for( int i = 0; i < sizeof(data); ++i )
data[i] = (char)0;
or
memset(data, 0, sizeof(data));
, which does the same thing using a library function.
However, because strings of characters (not referring to 'String' objects here) are terminated by a zero byte, only the first byte needs to be zeroed:
data[0] = (char)0;
will do it.
First of all, this is an excellent example why whitespace matters. Your code is really hard to read as it is, as skimming over it, it seems as the second if statement is outside of the first one.
Fixed code:
int count = 0;
char data[30];
boolean dataComplete = false;
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0){
if (dataComplete == true){
Serial.println("There is data already, clearing...");
char data[30];
dataComplete = false;
}
if (dataComplete == false){
Serial.println("New command, collecting...");
while (Serial.available()>0){
char character = Serial.read();
data[count] = character;
count++;
}
dataComplete = true;
}
}
Serial.print("Command received: ");
Serial.println(data);
delay(1000);
}
Also, it seems as it prints "Command received:" every iteration, regardless of if there's new data or not (although, this could be the intended feature).
Like mentioned, you don't clear the variable, you just create a new one. You'll need to clear and reset count
to fix this issue. However, just resetting count won't work if the second command is shorter than the one before.
Also, why do you complicate the code with the dataComplete
variable? I simplified the code below:
int count = 0;
char data[30];
boolean dataComplete = false;
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()){
Serial.println("New command, collecting...");
count = 0;
data[] = "";
while (Serial.available()){
char character = Serial.read();
data[count] = character;
count++;
}
}
Serial.print("Command received: ");
Serial.println(data);
delay(1000);
}