Serial Port - Buffering questions - "sliding" / ring buffer performance

Good grief.

  1. Even if you get the matching to work, your sketch will not run very long. The ways you are using the String class are going to cause dynamic memory fragmentation fairly quickly. It will freeze or restart at random times, or otherwise produce strange results. Ditch the String class.

  2. Just use a state machine to watch for the expected string as the characters arrive:

char    expected[30] = "def"; // watch for this
size_t  expectedLen  = strlen( expected );
size_t  matchCount   = 0;     // how many chars have matched so far


void setup()
{
  Serial.begin( 9600 );
}


void loop()
{
  if (Serial.available())
  {
    char c = Serial.read();

    if (foundExpected( c )) {
      Serial.print( F("Found ") );
      Serial.println( expected );
    }
  }

}


bool foundExpected( char c )
{
  bool found = false;

  if (c == expected[ matchCount ]) {

    matchCount++;
    if (matchCount == expectedLen) {
      found      = true;
      matchCount = 0;   // reset for next time
    }

  } else {
    matchCount = 0; // didn't match, start over
  }

  return found;
}

This doesn't even require storing the received data. matchCount is the Finite-State Machine "state" variable. It "remembers" how many characters have matched so far.

This saves lots of time, because you don't have to store each character, then search all the previous characters. Not only that, searching the previous characters would have compared each character multiple times (hence the schlemeil reference).

You can put this quick test at the point the characters are being read. It could set a flag that is used somewhere else to send the response string.

Cheers,
/dev

P.S. There is one extra thing you'll need if the match string contains substrings of itself. It's not typical, but you should be aware that watching for "defdefg" would not match an input of "defdefdefg".