Issues with Serial Read and write

I am trying to send data in a comma separated list from one arduino (hereafter transmitter) to another arduino (hereafter receiver) via xbee radio. That works fine. Then the receiver would upload that data to a php script via GET. I am having a few problems, but for the purposes of this post I want to resolve the issue of relaying variables. The following code should parse the comma separated values and put each value into a separate variable.
But the input of

5,6,7,

produces the output

7
0
0

I've been through this a hundred times, and I'm sure it's something simple, but I'm just not seeing it.

String inputString = "";         
String transmitterid = "0";
String sensorid = "0";
String sensorcondition = "0";

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

void loop() {
  
  int i = 0;
  while (Serial.available()) {
    
    char inChar = (char)Serial.read();
    Serial.println(inChar);
    if (inChar != ','){
    inputString += inChar;
    }
    else {
      i++;
      switch(i){
         case 1:
            sensorid = inputString;
            inputString = "";
         break;
         case 2:
            sensorcondition = inputString;
            inputString = "";
         break;
         case 3:
            transmitterid = inputString;
            inputString = "";
         break; 
        }
    }
    
    
    if (inChar == '\n') {
      Serial.println(sensorid);
      Serial.println(sensorcondition);
      Serial.println(transmitterid);
      i = 0;
      
    } 
  }
}

Thanks!

void loop() {

static int i = 0;

To bring a bit of good luck, you should also check for i > 3 and take an appropriate action.

Works like a charm! Thanks!

I'm not sure I understand what the problem was though. The variable is entirely enclosed within the while loop, so why would a static variable be necessary? I know static variables are neccessary if I was using the void loop(){ as a loop, but why would it matter in a while loop?

trs_rhys:
but why would it matter in a while loop?

Don't assume that all serial characters are waiting in the buffer just because there is at least one. It is likely the while() finished at least once before the next character was available...

I see. That makes sense. Thanks for the enlightenment. :blush: