Go Down

Topic: [Solved] Why is the read input repeated in the string? (Read 804 times) previous topic - next topic


Jan 29, 2013, 11:09 am Last Edit: Jan 30, 2013, 09:06 am by steveinaustria Reason: 1
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:

Code: [Select]
#define STR 8

char theInput[STR];

 void setup() {

 void loop() {
     int i=0;
     if (Serial.available() >= STR) {
       for (i=0; i<STR; i++) {
     Serial.print("OK I received: ");

Thanks in advance for any help.

Nick Gammon

You need room for a terminating "null" byte (0x00). If you are reading 8 bytes, you need an array of 9 to put them in. The final one needs to be 0x00.
Please post technical questions on the forum, not by personal message. Thanks!

More info:


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.

Edit: Nick beat me to it!
Arduino Libraries https://github.com/MajicDesigns?tab=Repositories
Parola for Arduino https://github.com/MajicDesigns/Parola
Arduino++ blog https://arduinoplusplus.wordpress.com


Printing stuff before (you do that) and after the string (you don't do that) is a good idea.

Showing the exact output you get is a good idea, too.

Code: [Select]
      Serial.print("OK I received: [");

will tell you far more about what is actually happening.
The art of getting good answers lies in asking good questions.

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131