Issue w/ Traversing array

Hi.

I’m trying to traverse a list, then upon finding the correct Char, I want to “show” (the show function writes strings to a screen) the char infront of it, hence the [i+i]. For the life of me, I cannot get it to work. If I change [i+i] back to just [i], all works fine.

I’ve made the array reset at 250 just to steer clear of any out-of-bounds errors (a little excessive, I know :stuck_out_tongue: )

  int a=0;
  char item [300];
void loop(){ 
  item[a] = Serial.read();
  a++;
  if(a==250){
    a=0; //reset array
    //traverse through list to R
    for(int i=0;i<250;++i){
      if(item[i]=='R'){
          show(String(item[i+1]));
        }
      }
      
    
    }
  }

Why does your program read from serial without knowing if there is anything there to read ?

What do you expect to read from i+1. You are not getting -1 by any chance, are you ?

I doubt it. If it finds an R, there will be another value after that (it's reading GPS strings, R is never at the end of a NMEA string), so the chances of it being -1 are next to none.

using Serial.available seems to crash the other code involved here - there are other software serials involved. That's another kettle of fish, though. I don't see the serial.available to be completely necessary in this case - am I wrong?

I'd say the chances of just about every character being -1 are pretty high.
Why do you think otherwise?

The serial device is sending strings starting in $GPRMC . In my school of thought, once the R has been received, the next thing to be received is an M - unless it sends "-1"s in between characters?

Even so, surely -1 would then still be displayed on the screen. When [i+1] is used, nothing at all displays.

In my school of thought, once the R has been received, the next thing to be received is an M

read is non-blocking.
Does your school of thought consider checking to see if there is something to read, before reading it?

Fair enough. I'll fix that up.

But still, shouldn't I at least then get a -1? I'm getting nothing at all....

I've no idea, but then I can't see your code.

As per your suggestion:

  int a=0;
  char item [300];
void loop(){ 
  while(Serial.available()){
  item[a] = Serial.read();
  a++;
  if(a==250){
    a=0; //reset array
    //traverse through list to R
    for(int i=0;i<250;++i){
      if(item[i]=='R'){
          show(String(item[i+1]));
        }
      }  
    }
  }
}

And it works! Thank you!

nicshackle:
Fair enough. I'll fix that up.

But still, shouldn't I at least then get a -1? I'm getting nothing at all....

It depends on how that show function works and what the display is expecting. If the display is expecting ascii and you send it -1 then it probably will show nothing. If you do that to the serial monitor in the IDE you get that funny y looking thing with the two dots over it. But most LCDs would just not put anything.