I have a .txt file loaded into the SD card which contains:
SampleTime: 100
SampleInterval : 1000
Phone: 91987654331
I am reading this using the readStringUntil(':'); in Arduino IDE but it reads the whole content together, but I want to split the string and integer and store it in different variables. I want to know how I can split it easily and store it in different variables. Below is my code:
void setup() {
Serial.begin(9600);
if (SDfound == 0) {
if (!SD.begin(4)) {
Serial.print("The SD card cannot be found");
while(1);
}
}
SDfound = 1;
printFile = SD.open("consta.txt");
if (!printFile) {
Serial.print("The text file cannot be opened");
while(1);
}
while (printFile.available()) {
buffer = printFile.readStringUntil(':');
Serial.println(buffer); //Printing for debugging purpose
//do some action here
}
CodePudding user response:
you can use strtok() to split string
// let say buffer = "Ahmed:2000:"
// using ':' as split character
char *value = strtok(buffer, ":");
// now value have the first word before ':' ----> Ahmed
value = strtok(NULL, ":");
//now value contain the second word ----> "2000" as string
then use atoi() to convert from string to int
int number = atoi(value);
CodePudding user response:
You could consider parsing each whole line with the sscanf()
:
Here is an example implementation for how to parse your lines using sscanf()
(for simplicity, I'm ignoring the SD card, and just providing manual c-string literals):
void setup() {
Serial.begin(9600);
char testline_1[] = "SampleTime: 100";
char testline_2[] = "SampleInterval: 1000";
char testline_3[] = "Phone: 91987654331";
// Display initial inputs
Serial.println("===== Initial Inputs =====");
Serial.println(testline_1);
Serial.println(testline_2);
Serial.println(testline_3);
Serial.println();
// Parse data
int sample_time;
int sample_interval;
char phone_number[20];
sscanf(testline_1, "%*s %i", &sample_time);
sscanf(testline_2, "%*s %i", &sample_interval);
sscanf(testline_3, "%*s %s", phone_number);
// Display parsed data
Serial.println("===== Parsed Data =====");
Serial.print("sample_time = "); Serial.println(sample_time);
Serial.print("sample_interval = "); Serial.println(sample_interval);
Serial.print("phone_number = "); Serial.println(phone_number);
Serial.println();
}
void loop() {
}
This is what is output to the Serial Monitor, demonstrating successful parsing of the input:
===== Initial Inputs =====
SampleTime: 100
SampleInterval: 1000
Phone: 91987654331
===== Parsed Data =====
sample_time = 100
sample_interval = 1000
phone_number = 91987654331