Error reading a string from the serial port

Hi, I am trying to read a string from the serial port until I receive a specific character, in this case "OK", but I am not succeeding, can someone tell me what could be my error?

The string would be like this:

Hello world, this is a test OK

Here is my code:

String cadena = "";

void setup(){
  Serial.begin(115200);
  Serial.println("Iniciando");
  cadena = "";
}

void loop() {
  while (Serial.available() > 0) {
    char caracter = Serial.read();
    if (caracter == 'O') {
      caracter = Serial.read();
      if (caracter == 'K') {
        Serial.println(cadena);
        break;
      }
      else {
        cadena += caracter;
      }
    }
    else {
      cadena += caracter;
    }
  }
}

You didn't check to see if the second character was there to be read, but you read it anyway.
Oopsie.

First, never use "String" variables, they tend to clog the memory and give you unpredictable behaviour at mid/long term (not for this small code, but for large ones, and it's a good thing to start with good programming habits).

Said that', you just need to use a "buffer" variable to store the received caracters, and do something when a specific charater or string has been received. I strongly suggest you to use a SINGLE character as terminating command. The most common one is '\n' or Line Feed, or 0x10 (and eventually ignore '\r', or CR, or 0x13).
With this in mind, you could try this to use '\n' as a terminating string, you can see it's pretty straightforward:

char buf[21]; // Size of the longest command, plus 1, in this case 20
byte bufPtr = 0; // Pointer to next character in buffer

void setup(){
  Serial.begin(115200);
  Serial.println("Iniciando");
  buf[0] = '\0'; // String terminator
}

void loop() {
  while (Serial.available()) {
    char c = Serial.read();
    if (c != '\r') {
      if (c == '\n') {
        // End of command!
        Serial.println("Cadena recibida:");
        Serial.println(buf);
        // Reset the buffer
        bufPtr = 0;
        buf[0] = '\0';
      } else {
        // New character
        buf[bufPtr++] = c;
        buf[bufPtr] = '\0'; // String terminator
      } // c == '\n'
    } // c != '\r'
  } // while
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.