I'm using pyserial (python serial module) to send data to my arduino trough UART.
Here is the message my arduino receives:
40/-20/3
and i want to split at the "/" to get 3 integers
but i have no idea how to do this.
please help!
I'm using pyserial (python serial module) to send data to my arduino trough UART.
Here is the message my arduino receives:
40/-20/3
and i want to split at the "/" to get 3 integers
but i have no idea how to do this.
please help!
Welcome to the forum
Take a look at the strtok() function
void setup()
{
Serial.begin(115200);
char message[] = "40/-20/3";
char * ptr;
ptr = strtok(message, "/");
int i_1 = atoi(ptr);
ptr = strtok(NULL, "/");
int i_2 = atoi(ptr);
ptr = strtok(NULL, "/");
int i_3 = atoi(ptr);
Serial.println(i_1);
Serial.println(i_2);
Serial.println(i_3);
}
void loop()
{
}
Thanks, i will! ![]()
you could use sscanf(), e.g.
void setup() {
Serial.begin(115200);
while(!Serial.available());
char text[50]={0};
Serial.readBytesUntil('\n',text,50);
Serial.println(text);
int i,j,k;
sscanf(text,"%d/%d/%d", &i,&j,&k);
Serial.println(i);
Serial.println(j);
Serial.println(k);
}
void loop() {}
a run gives
21:19:55.801 -> 40/-20/3
21:19:55.801 -> 40
21:19:55.801 -> -20
21:19:55.801 -> 3
in practice the result returned by sscanf() should be checked to ensure the expected number of conversions was sucessful - in the above case 3
You could consider using the text parser library. For example,
#include <textparser.h>
TextParser parser("/");
void setup() {
Serial.begin(9600);
}
void loop() {
char line[80];
if (not Serial.readBytesUntil('\n', line, sizeof(line))) {
return;
}
int values[3];
parser.parseLine(line, values);
for (int const& t: values) {
Serial.println(t);
}
}
If you want these values to be assigned to separate variables instead, you can use the following:
int value1, value2, value3;
parser.parseLine(line, value1, value2, value3);
Mixing of types is also supported.