Function returns different value with same input every time beeing called...

This is embarrassing as its probably something trivial but…

The following function is supposed to receive a char string of length len and return the actual length of the string entered. The actual string is stored in char array receivedC.

int GetChar(char *receivedC, byte len) {
  
  byte index = 0;
  char inputC = 0;

   if (len>32) return 0;
      
   while(Serial.available()>0) {Serial.read();}     // Clear buffer
   while (index < len ){
   while(Serial.available()<1) {} 
     inputC=Serial.read();
     if ((inputC==13 || inputC==10)  && index>0) {break;}
     receivedC[index]=inputC;
     index++;
     }
     
    for (int x=index; x<len; x++){receivedC[x]='\0';}  // Add null to the reset of empty array
    
    
  return (index);
}

…but its been puzzling me for the past 3 days (!) : The function returns a different number (index) for the same input every time is being called which is either one more or one less the actual number of characters entered.

Thanks.!

if you text is terminated by carriage return (13) and line feed (10) could you be terminating the first line count using carriage return then counting the line feed at the start of the next line as part of the length?

I think you need to ignore 13 and 10 at the start of a line, not buffer them:

      if (inputC == 13 || inputC == 10)
      {
	if (index > 0) // end of line
	  break;
      }
      else  // only buffer if not a CR or LF
      {
	receivedC[index++] = inputC;  // ++ postfix operator, so handy...
      }

(I reformatted it a bit, indentation and readability…)

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

...R