So basically send to arduino values from "a1b1c" to "a200b200c" and I'm trying get from a to b values into "x" integer and from b to c into "y" integer.
The problem is, when i send to arduino data like "a123b456c" then it prints out :
0
0
1
0
2
0
3
0
0
0
0
4
0
5
0
6
0
0
where is the problem and how can i fix it?
char incomingByte = 0;
int x;
int y;
char axis;
String aa;
String bb;
void setup(){
Serial.begin(9600);
}
void loop()
{
if (Serial.available() > 0) {
incomingByte = Serial.read();
if(incomingByte == 97){ // 97 = a
axis = 'x';
}
else if(incomingByte == 98){ // 98 = b
axis = 'y';
}
else if(incomingByte == 99){ // 99 =c
axis = 'n';
}
else {
char ch1 = incomingByte;
if (axis == 'x'){
aa = aa + ch1;
}
else if (axis == 'y'){
bb = bb + ch1;
}
}
x = Str2int(aa);
y = Str2int(bb);
Serial.println(x);
Serial.println(y);
delay(100);
aa = "";
bb = "";
}
}
int Str2int (String Str_value)
{
char buffer[4];
Str_value.toCharArray(buffer, 4);
int int_value = atoi(buffer);
return int_value;
}
Isn't if(incomingByte == 'a'){ simpler and clearer? (it also doesn't need the comment)
Your problem lies in the fact that every time a character becomes available, you read it, assign it to the string, convert the string to a digit, and print it.
Then you reset the string, and start again.
You need to wait until you've received the whole three digit number before converting it.