Hello,
I'm a newbie with Arduino, and this is my first question. Hope I posted it in the right section, too.
The question I'm asking is more a "I don't understand why" than a "it doesn't work", and I post it after searching for the answer in other threads/via search engine, and I didn't find the exact reason why this happens. I tried also reading about the function Serial itself, but I didn't go far.
So, here's the "problem": I'm learning the basics of Arduino via a tutorial I found on YouTube, and I ended with this code:
char c;
String string1;
void setup(){
Serial.begin(9600);
}
void loop(){
if (Serial.available()){
string1 = "";
do{
if (Serial.available()){ // I don't understand why this loop is necessary
c = Serial.read();
if (c != '\n'){
string1 += c;
}
}
}while(c != '\n');
Serial.print(string1);
}
}
The purpose is to simply print a string I digited previously on the Serial Monitor. The code is clear to me (it's very simple), except for one thing: the second if loop.
Example: if I try to write in the Serial Monitor a random string with this exact code, ex. "Hello there", it prints the result as it should be.
If I remove that if loop, leaving the do-while loop like
...
if (Serial.available()){
c = Serial.read();
if (c != '\n'){
string1 += c;
}
}
...
The output is this:
H⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮e⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮l⸮⸮...
(I didn't print the whole message, think you got what's up)
Now, I simply don't understand why it has this behaviour, and I don't now why, after every letter printed I get those symbols. Sorry if I can't be more specific about a possible explanation, but I don't understand neither the problem (what caused it), nor why the if loops solves it.
Hope my English wasn't that bad, it's not my native language. Hope I also explained everything clearly, and thanks to whoever will bright me up. Alternate and easier solutions are also welcomed.
NOTE: The guy who made the tutorial just inserted the loop saying it would solve the issue, but it didn't explain why.
EDIT: I forgot to specify. I use an Arduino Uno rev. 3 on Ubuntu. Don't know if it helps.
