4.- App sends three values separated by comma. Arduino receives them and separates them.
-
In this example we will use the same App as in the previous example.
-
We assume that the App wants to send these numbers separated by commas to the Arduino: 126,3,58
-
An asterisk will be added indicating end of message. [126,3,58*]
-
In this case it is necessary to indicate the end of the message (example with asterisk) since we can send any number.
-
Arduino will receive that text and separate it by the comma.
-
Check Serial Monitor.
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
char caracter;
String palabra;
String red;
String green;
String blue;
int ind1;
int ind2;
int ind3;
void setup() {
Serial.begin(9600);
}
void loop() {
if(Serial.available()) {
caracter = Serial.read();
palabra = palabra + caracter;
if(caracter == '*') {
palabra = palabra.substring(0, palabra.length() - 1); // Delete last char *
Serial.println(palabra);
ind1 = palabra.indexOf(',');
red = palabra.substring(0, ind1);
ind2 = palabra.indexOf(',', ind1+1 );
green = palabra.substring(ind1+1, ind2);
ind3 = palabra.indexOf(',', ind2+1 );
blue = palabra.substring(ind2+1);
Serial.print("red = ");
Serial.println(red);
Serial.print("green = ");
Serial.println(green);
Serial.print("blue = ");
Serial.println(blue);
Serial.println();
palabra = "";
delay(10);
}
}
}
ooooooooooooooo000000o000000ooooooooooooooo
Another way to split the data in with this getValue function:
Serial.println(palabra);
red = getValue(palabra,',',0);
green = getValue(palabra,',',1);
blue = getValue(palabra,',',2);
(...)
///////////////// Function Split by char ////////////////
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}