Split incoming serial data

i want to split data coming from serial port, i have tried this code , code works fine except that aongwith data it shows comma(,)

String readString;
String data;
String v;
String i;
String w;
String h;
int ind1; // , locations
int ind2;
int ind3;
int ind4;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
        Serial.print("wait");

}

void loop() {
  if (Serial.available() >0) {
    char c = Serial.read();  //gets one byte from serial buffer
    if (c == '*') {
      
     ind1 = readString.indexOf(',');
      v = readString.substring(0, ind1);
      ind2 = readString.indexOf(',', ind1+1);   //finds location of second ,
      i = readString.substring(ind1+1, ind2+1);
      ind3 = readString.indexOf(',',ind2+1);
      w = readString.substring(ind2+1,ind3+1);
      ind4 = readString.indexOf(',',ind3+1);
      h = readString.substring(ind3+1); //captures remain part of data after last ,
      Serial.print("volt ");
      Serial.println(v); 
      Serial.print("amp: ");
      Serial.println(i);
    Serial.print("power: ");
      Serial.println(w);
      Serial.print("fre: ");
      Serial.println(h);
            
      
      
      
      
      readString="";
    }else { 
      
      readString += c; } //makes the string readString
      }
      }

when i send the data 1,2,3,4*
it print the value of
v=1
i=2, comma is coming along with data
w=3, comma is coming along with data
h=4

i dont know whats wrong wth the code anyone if correct the code?

v works. i doesn't. Study closely the two lines which put values into those two variables.

It is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. This can happen after the program has been running perfectly for some time. Just use cstrings - char arrays terminated with '\0' (NULL).

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example.

...R

MorganS:
v works. i doesn't. Study closely the two lines which put values into those two variables.

v and h both works ok, 'i' and 'w' has commas, i have tried all possibilities but still un successfull

     i = readString.substring(ind1+1, ind2+1);

So did "all possibilities" include removing the second "+1" from this line?

1 Like