Unknown length of rx/tx input

I have this method to get the incomming data, and save it. inData is a char array for 20 elements.

void modtag() {
  while (Serial.available() < 1) //Venter på en byte
  {
    //do nothing
  }

  char index_ = 0; // Index into array; where to store the character
  char inChar = 'a'; // Where to store the character read
  
  while (index_ < 19) // One less than the size of the array
  {
    inChar = Serial.read(); // Read a character
    if(inChar == 'я'){
      break;
    }
    inData[index_] = inChar; // Store it
    index_++; // Increment where to write next
  }

  inData[index_] = '\0'; // Null terminate
}

However, sometimes the input will only be 5 characters, and when printing inData, it will look something like this: 42.00яяяяяяяяяяяяя. And my break functions doesn’t seem to work.

How do I solve this?

Try to "memset(inData, 0, 20)" as the first thing in "modtag()". Also remember that Danish letters are non-ascii, so they are not valid in an array of char, so make sure that only valid ascii letters are transmitted ('я' is not valid ascii, so checking for it is useless). If none of this works, please post your entire sketch since other factors may cause your problem (referencing bad memory etc.).

Thanks for replying, but that didn't fix the problem :confused:
And I forgot to remove that danish comment haha

The letter 'я' is unicode and it does not even fit in a single byte / char. Usually these things happen when you a referencing bad memory, inData is declared locally and references globally etc. Post your entire sketch if you want bedre hjælp :slight_smile:

Instead of checking for an illegal character you should check whether there is a character to read, maybe:

while ((Serial.available(()) && (index_ < 19) )

BTW, I think the index should be int or byte instead of char.

Thanks I got your idea to work, just before posting my whole code :smiley:

If your incoming data was terminated with '/0', you could use the strlen() function -

char myD[6];

void setup() {
Serial.begin(115200);
myD[0] = '4';
myD[1] = '2';
myD[2] = '.';
myD[3] = '0';
myD[4] = '\0';
myD[5] = '\0';

}



void loop() {

Serial.print(myD);
Serial.print(" = ");
Serial.print(strlen(myD));
Serial.println(" character length");
delay(1000);
}

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

...R

Completely misread the purpose of your code, thought you where expecting 20 bytes per message and just got unwanted garbage. Since Serial.read() returns -1 if nothing is received, you could also just have modified "if(inChar == 'я')" to "if(inChar != -1)" and have achieved the same :slight_smile:

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

...R

... a much better option; leave it to Robin to cut through the haze.