A demo code using the serial input basics receive with end marker and the strtok() function parse the string array to integers. Enter up to six integer numbers separated by commas, like 11,22,33,44,55,66.
Make sure newline is enabled in serial monitor line endings.
const byte numChars = 32;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;
int number_1;
int number_2;
int number_3;
int number_4;
int number_5;
int number_6;
void setup()
{
Serial.begin(115200);
Serial.println("<Arduino is ready> Enter up to six integer numbers separated by commas");
Serial.println("Like 11,22,33,44,55,66");
Serial.println("make sure newline is enabled in serial monitor line endings");
}
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[8]; // an array of pointers to the pieces of the above array after strtok()
char *ptr = NULL; byte index = 0;
ptr = strtok(receivedChars, ","); // delimiters, semicolon
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
number_1 = atoi(strings[0]);
number_2 = atoi(strings[1]);
number_3 = atoi(strings[2]);
number_4 = atoi(strings[3]);
number_5 = atoi(strings[4]);
number_6 = atoi(strings[5]);
Serial.print("number 1 = ");
Serial.print(number_1);
Serial.print(" number 2 = ");
Serial.print(number_2);
Serial.print(" number 3 = ");
Serial.print(number_3);
Serial.print(" number 4 = ");
Serial.print(number_4);
Serial.print(" number 5 = ");
Serial.print(number_5);
Serial.print(" number 6 = ");
Serial.print(number_6);
Serial.println(); // blank line
newData = false;
}