Waiting for specific word in serial

I'v made the code ridiculously long in order to understand why is this not working :

bool  waitRespond(char *respond,char *error)
{
         mySerial.print("WAITING FOR:");  mySerial.println(respond);

    int maxsize=20;
    boolean didGot=0;
    char inData[maxsize]={0};
    int Tindex=0;
    unsigned long timeOutKeeper = millis();
     while (!didGot)
    {
        if (millis() - timeOutKeeper >=TIME_OUT_LONG   )
        { mySerial.println("TIMEOUT:"); didGot=1;  break;}
        
        while (  Serial.available() >0   )
        {
            if(Tindex>maxsize-1)
            {didGot=1;return 0;}
            
                    char c = Serial.read();
                    inData[Tindex]=c;
                    //prints
                    mySerial.print("*");
                    mySerial.print(inData[Tindex]);
                     //
                    Tindex++;
                    inData[Tindex]='\0';
 
        }
        
         if(strstr(inData, respond) != NULL)
        { mySerial.println("FOUND:"); didGot=1; return 1;}
}

So for this input I print ( and get the right result) :

WAITING FOR:CMD
*E*N*D*
*
*C*M*D*
*
FOUND:

and for another input, he will NOT find the string inside , no matter what I try:

WAITING FOR:CMD
*R*e*b*o*o*t**
**C*M*D**
TIMEOUT:

TIMEOUT happens after 18 seconds.
Where timeout parameter is 18 seconds, and the prints (reboot+cmd) happens after 250 milli seconds= right away.

 if (Tindex > maxsize - 1)
      {
        didGot = 1;
        return 0;
      }

is not at the right place. it should be in the while available() loop when you increase the character count

you should test also for the substring in there and not write beyond the end of the buffer

PS: in english they don't say "didGot" but "didGet" :slight_smile:

J-M-L actually it is inside the while available loop ... :slight_smile: but thanks.
Second, I found out that I had all sorts of \0 and \r\n in the string that I could not see in the print.

So I removed them with :

if(c != '\n' && c!='\0' && c!='\r')

and it works.

Thanks.

right - need my glasses :slight_smile:

You still have an issue in the while available() because you have this:

char inData[maxsize] --> index goes from 0 to maxsize-1

and when you receive one char you do this:

test if Tindex>maxsize-1 so assuming it is arriving at the end of the buffer then Tindex == maxsize-1 and your if says "no worry all is fine" and then you go do

inData[Tindex]=c;
[color=red]Tindex++[/color];
inData[[color=red]Tindex[/color]]='\0';

so you overflow when you put the trailing null char.

Thats right. Thanks.