Here is some code I had written to show how to use a circular buffer to wait for a specific string or timeOut
You can test this code and it gives you 5 seconds to say ‘Hello’
#define ESPSEPRIAL Serial
// --------------------------------------
// waitForString wait max for duration ms whilst checking if endMarker string is received
// on the ESP Serial port returns a boolean stating if the marker was found
// --------------------------------------
boolean waitForString(const char * endMarker, unsigned long duration)
{
int localBufferSize = strlen(endMarker); // démo Use of a circular buffer
char localBuffer[localBufferSize];
int index = 0;
boolean endMarkerFound = false;
unsigned long currentTime;
memset(localBuffer, '\0', localBufferSize); // clear buffer
currentTime = millis();
while (millis() - currentTime <= duration) {
if (ESPSEPRIAL.available() > 0) {
if (index == localBufferSize) index = 0;
localBuffer[index] = (uint8_t) ESPSEPRIAL.read();
endMarkerFound = true;
for (int i = 0; i < localBufferSize; i++) {
if (localBuffer[(index + 1 + i) % localBufferSize] != endMarker[i]) {
endMarkerFound = false;
break;
}
}
index++;
}
if (endMarkerFound) break;
}
return endMarkerFound;
}
void setup() {
Serial.begin(115200);
}
void loop() {
if (waitForString("Hello", 5000ul)) {
Serial.println("Good Morning!");
} else {
Serial.println("be polite please!”);
}
}