Wrong value received on Serial communication.

Hi Members.
I have written a simple UART serial communication program. I am getting continuous data over serial port and showing it on serial monitor. But don’t know sometime why it’s the shows wrong values. Or it seems like that sometime the received value is overwriting on each other or it just not receiving the whole character correctly.
Pls see in this picture

Here’s the receiver code

#include <SoftwareSerial.h>

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
int val=0,speed_mot = 0;

void setup() {
 
  Serial.begin(38400);
  inputString.reserve(200);
}

void loop() {
while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
   if (stringComplete) {
    int index;
    //Serial.println(inputString);
    index = inputString.lastIndexOf(',');
    inputString.remove(index);                                                             
     index = inputString.lastIndexOf(',');
     val = inputString.substring(index+1).toInt();
     inputString.remove(index);   
     index = inputString.lastIndexOf(',');
     speed_mot = inputString.substring(index+1).toInt();
     inputString.remove(index);
    inputString = "";
    stringComplete = false; 
  }
   Serial.print("Val:  ");
   Serial.print(val); Serial.print("  speed_mot:  ");Serial.println(speed_mot);
   delay(30);
 }

Well if I show the received data in “if(stringComplete == true)” condition it receive correct values every time.
My English is not so good so sorry in advance and thanks to all of you too in advance.

wrongserialdata1.PNG

wrongserialdata3.PNG

what does the continuous flow of data looks like?

don't use the String class... read Serial Input Basics

and know the C functions to handle char arrays: stdlib.h string.h

In 30ms (your delay) in theory 120 bytes can arrive (at 38k4). That will overflow the software buffer in the hardware serial class.

Try without delay.

Hi sterretje. Initially i have started with without delay itself and the result was same.

If the received line is correct and the parsed integers are wrong then the problem is in the parsing.

I notice that when you use '.lastIndexOf()' you never check for the return value '-1' indicating "Not Found". You should check for such error conditions for those cases when an input character is missed.

Perhaps you should be printing out the substrings as you are parsing so you can see if anything is not acting like you think it should.