Go Down

Topic: Parsing a string to int (Read 586 times) previous topic - next topic

noxasdj

Hey,

I have a problem working with strings, cause I lost that C language lecture, so I don't know how to split and string and put the values inside a integer variables.

I've got a string comming from my serial like this:  51,20,11

And I would like to have in the end: A = 51
                                                 B = 20
                                                 C = 11
where A,B,C are integers.



Code: [Select]
void loop() {
while (Serial.avaiable()>0) {
                 data = Serial.read();
                 char *p = data;
                 char *str;
                 while ((str[i] = strtok_r(p, ",", &p)) != NULL){ // delimiter is the semicolon
                        Serial.println(str);
                }
}
}


The serial output give me:
50
22
11

With this I split my string but I don't know how to save the data to an array  and then convert it to an integer.

Thank you :)

robtillaart


- itoa(s);  // in case of a char array
- String.toint()  // arduino v22 iirc.
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

olikraus

you could use atoi().
Code: [Select]

                while ((str = strtok_r(p, ",", &p)) != NULL){ // delimiter is the semicolon
                       my_int_array[idx++] = atoi(str);
                       Serial.println(str);
               }

Note, that there is a programming mistake inside the while condition (compare you input vs. our output)

Oliver

noxasdj

thank you for your answer, but the problem is that I don't know how to write this. Could you write me how is going to be?

I appreciate your time.

noxasdj

Thank you. Now it's working. Here the code.
Code: [Select]
void loop() {

if (Serial.avaialable()>0) {
                 data = Serial.read();
                 int i = 0;
                 char *p = data;
                 char *str;
                 while ((str = strtok_r(p, ",", &p)) != NULL){ // delimiter is the semicolon
                        my_int_array[i++] = atoi(str);
                }
                a = my_int_array[0];
                b = my_int_array[1];
                c = my_int_array[2];
                Serial.print("A: ");
                Serial.println (a);
                Serial.print("B: ");
                Serial.println (b);
                Serial.print("C: ");
                Serial.println (c);
}
}


One last question, is it possible to print everything at the same time? like Serial.println ("C: " + c)


Groove

Quote
One last question, is it possible to print everything at the same time? like Serial.println ("C: " + c)
No.
Thought there is an iostream-like template around somewhere
Per Arduino ad Astra

Go Up