I am trying to read from the serial monitor and use the input as a string. However the resultant string, as printed, is the input + the input, ie if I input 12345678 the string printed is 1234567812345678. Could someone please explain why?
Here is the code:
#define STR 8
char theInput[STR];
void setup() {
Serial.begin(9600);
Serial.flush();
}
void loop() {
int i=0;
if (Serial.available() >= STR) {
for (i=0; i<STR; i++) {
theInput[i]=Serial.read();
}
Serial.print("OK I received: ");
Serial.println(theInput);
}
}
You need to terminate the string you received with a '\0' character to signify the end of the string. I think you are just getting some random stuff after the string that happens to be your input string.