String from Serial help

I’m trying to capture a string from the serial line, but having an issue.
If I send
xxx\r
yyy\r
zzz\r

I only want yyy in my “string”. Here’s the code I’ve been playing with. Can you help me figure out why string is xxxyyy???

#define SERIAL_SPEED 57600
#define LED          13

char charArray[256];
char c;
int  i = 0;
int  r = 0;

void setup()
 {
    pinMode(LED, OUTPUT);
    charArray[0] = '\0';

    // Set serial to 57600 bps
    Serial.begin(SERIAL_SPEED);
    Serial.println("Type something and hit enter, type some more and hit enter.");

    delay(5000);

    if(Serial.available() > 0)
     {
        while(Serial.available() > 0)
         {
            c = Serial.read();

            if(c == '\r')
             {
                r++;
                
                if(r <= 1)
                 {
                    continue;
                 }
                else
                 {
                    break;
                 }

             }
            else if(c == '\n')
             {
                continue;
             }
            else
             {
                i++;
                charArray[i-1] = c;
             }
         }

        Serial.print("\"");
        Serial.print(charArray);
        Serial.println("\""); 
     }
    digitalWrite(LED, HIGH);
 }

void loop()
 {
 }

Do you want to run this continuously as in a loop? or just once (i.e. only one string)?

Here's how I would write it, if I wanted to accept it as a single string, terminated by a \r:

#define SERIAL_SPEED  57600
#define LED  13

void setup()
{
  char charArray[256];
  char c;
  int  i = 0;

  pinMode(LED, OUTPUT);
  charArray[0] = 0;

  // Set serial to 57600 bps
  Serial.begin(SERIAL_SPEED);
  Serial.println("Type something and hit enter, type some more and hit enter.");

  while (Serial.available() == 0);  // do nothing - wait for first char

  c = Serial.read();
  
  while (c != '\r')
  {
    if (c != '\n')                    // skip new lines
    {
      charArray[i++] = c;             // store the character, and then increment our index
      charArray[i] = 0;               // terminate the string
    }
    while (Serial.available() == 0);  // wait for next char
    c = Serial.read();
  }

  Serial.print("\"");
  Serial.print(charArray);
  Serial.println("\"");
  digitalWrite(LED, HIGH);
}

void loop()
{
}

If you want to continuously receive strings terminated by \r, move everything from inside of setup() to loop().

b

thanks for the reply… I got it working before I saw your reply… here’s how I did it…

            if(r < 1)
             {
                if(c == '\r')
                 {
                    r++;
                 }
                continue;             
             }
    
            if(c == '\n')
             {
                continue;
             }
            else if(c == '\r')
             {
                break;
             }