Excess Charaters

char message1[1000];

if (Serial.available())
{
for (int i=0; i<1000;i++)
message1[i] = Serial.read(); //Input alphabets or numbers

Serial.print("Message: ");
Serial.print(message1);
}


Hi, I'm using the arduino IDE. Basically I am inputting characters input my variable message1. But I declared it 1000 as I want to vary the number of characters.

So when I execute this command and input "Hello", message1 printed "HelloYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY". Basically rubbish was printed to cover up the other unused 995 characters.

Would appreciate help to allow me to print just the characters I input as message1, while leaving it as 1000 as I will want to change my inputs.
Eg, it should print out what I input like "Mary had a little lamb".

If you are wondering how am I inputting my characters, it is a function in the arduino IDE, Serial.read.

Please advice as I am really bad at c++. Arduino IDE uses c++
1
2
for (int i=0; i<1000;i++)
message1[i] = Serial.read(); //Input alphabets or numbers 


It should be :
1
2
for (int i=0; i<1000;i++)
if((message1[i] = Serial.read()) == -1) { message1[i] = 0; break; }
Thank you so much! It works!
Thank you so much! It works!

Glad it helped. I am actually a newbie in Arduino programming.
If you have the time, would appreciate if you could explain why you have done

if((message1[i] = Serial.read()) == -1)
{
message1[i] = 0;
break;
}

I am a beginner and would like to learn from you. Thank you so much!
If you have learned the if-statement, understanding this would be easy.
1.
message1[i] = Serial.read()
This is an assignment. Serial.read() returns -1 if there is nothing more it can read.

2.
if((message1[i] = Serial.read()) == -1)
It is an if-statement to check if there is no more input. After that :

3.
message1[i] = 0;
This line puts a string terminator character (or '\0'). For example, when you print the string, it will continuously print every character until an element which is a "string terminator character" (or '\0') is encountered.

4.
break;
This line simply stops the for-loop. There is no point in continuing the loop is there is no more input available.
Last edited on
Ah I see, i didn't know that Serial.read() returns -1 if there is nothing more it can read.

Okay fully understand what you did. Thank you very much!
Topic archived. No new replies allowed.