Go Down

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

steveinaustria

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() {
   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);
     }
}


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:
http://www.gammon.com.au/electronics

marco_c

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 http://arduinocode.codeplex.com
Parola for Arduino http://parola.codeplex.com

PaulS

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: [");
      Serial.print(theInput);
      Serial.println("]");

will tell you far more about what is actually happening.

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!

Arduino
via Egeo 16
Torino, 10131
Italy