Pages: [1]   Go Down
Author Topic: [Solved] Why is the read input repeated in the string?  (Read 469 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
#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.
« Last Edit: January 30, 2013, 03:06:35 am by steveinaustria » Logged

Global Moderator
Offline Offline
Brattain Member
*****
Karma: 474
Posts: 18696
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Sydney, Australia
Offline Offline
Edison Member
*
Karma: 33
Posts: 1260
Big things come in large packages
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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!
Logged

Arduino libraries http://arduinocode.codeplex.com
Parola hardware & library http://parola.codeplex.com

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48569
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
      Serial.print("OK I received: [");
      Serial.print(theInput);
      Serial.println("]");
will tell you far more about what is actually happening.
Logged

Pages: [1]   Go Up
Jump to: