/*
Read 3 comma seperated values into variables from Serial connection
Examples used to create this:
https://forum.arduino.cc/t/decode-comma-separated-values/960564/4
*/
// Serial data variables
// Incoming Serial Data Array
const byte kNumberOfChannelsFromExcel = 3;
// Comma delimiter to separate consecutive data if using more than 1 sensor
const char kDelimiter = ',';
// Interval between serial writes
const int kSerialInterval = 50;
// Timestamp to track serial interval
unsigned long serialPreviousTime;
char* arr[kNumberOfChannelsFromExcel];
// variables to read as comma seperate data:
float value1 = 0, value2 = 0, value3 = 0;
void setup() {
Serial.begin(9600);
Serial.println("<Arduino is ready>");
}
void loop() {
Serial.println("Enter data:");
while (Serial.available() == 0) {} //wait for data available
String line = Serial.readString(); //read until timeout
line.trim(); // remove any \r \n whitespace at the end of the String
if (line.indexOf(',')>=0) {
Serial.print("Received: <"); Serial.print(line); Serial.println(">");
} else {
Serial.println("Line received does not have comma seperated values. Ignoring line.");
return;
}
parseData(line.c_str());
// convert strings to actual values and put in the right variable:
value1 = atof(arr[0]);
value2 = atof(arr[1]);
value3 = atof(arr[2]);
Serial.print("Received: value1="); Serial.print(value1);
Serial.print(" value2="); Serial.print(value2);
Serial.print(" value3="); Serial.print(value3);
Serial.println("");
}
// Seperate the data at each delimeter
void parseData(char data[]) {
char *token = strtok(data, ","); // Find the first delimeter and return the token before it
int index = 0; // Index to track storage in the array
while (token != NULL){ // Char* strings terminate w/ a Null character. We'll keep running the command until we hit it
arr[index] = token; // Assign the token to an array
token = strtok(NULL, ","); // Continue to the next delimeter
index++; // increment index to store next value
}
}