Hi everyone, so I am using bluetooth to send commands to a drinks machine via an app on a phone. The app sends 2 values seperated by a comma (e.g 2 shots and the glass size such as 330). What I have at the moment is using a char variable and have if statements for this, so if a 2 is sent turn on pump 2 for example.
This works great for sending 1 value at a time but I need to be able to send 2.
Any ideas on how to do this because everything I have came across relies on strings such as strtok etc.
Here is an example using the serial input basics tutorial methods for receiving and parsing serial data. Enter, in serial monitor, the glass size and pump number separated by a comma delimiter. The glass size will end up in a numeric variable (int) glassSize and the pump number in the (int) variable pumpNumber to be used for further processing. Serial monitor line endings need to be set to Newline or Both NL & CR.
const byte numChars = 16;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;
int glassSize = 0;
int pumpNumber = 0;
void setup()
{
Serial.begin(115200);
Serial.println("<Arduino is ready> Enter two integer numbers separated by commas");
Serial.println("representiong the glass size and pump number");
Serial.println("Like 330,2");
}
void loop()
{
recvWithEndMarker();
showNewData();
if (newData)
{
parseData();
}
}
void recvWithEndMarker()
{
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (Serial.available() > 0 && newData == false)
{
rc = Serial.read();
if (rc != endMarker)
{
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars)
{
ndx = numChars - 1;
}
}
else
{
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData()
{
if (newData == true)
{
Serial.print("This just in ... ");
Serial.println(receivedChars);
//newData = false;
}
}
void parseData()
{
char *strings[3]; // an array of pointers to the pieces of the above array after strtok()
char *ptr = NULL; byte index = 0;
ptr = strtok(receivedChars, ","); // delimiters, comma
while (ptr != NULL)
{
strings[index] = ptr;
index++;
ptr = strtok(NULL, ",");
}
/*
//Serial.println(index);
// print all the parts
Serial.println("The Pieces separated by strtok()");
for (int n = 0; n < index; n++)
{
Serial.print("piece ");
Serial.print(n);
Serial.print(" = ");
Serial.println(strings[n]);
}
*/
// convert string data to numbers
glassSize = atoi(strings[0]);
pumpNumber = atoi(strings[1]);
Serial.print("glass size = ");
Serial.print(glassSize);
Serial.print(" pump number = ");
Serial.print(pumpNumber);
Serial.println(); // blank line
newData = false;
}