Hello,
I'm new to Arduino. I'm trying to read some data from the SD card module and do some action if that read data is equal to a string value. But with this code, its not happening. If anyone can please tell me a way to do that.
here is the code that I used.
#include <SD.h>
#include <SPI.h>
File printFile;
String buffer;
boolean SDfound;
void setup() {
Serial.begin(9600);
pinMode(10,OUTPUT);
digitalWrite(10, HIGH);
if (SDfound == 0) {
if (!SD.begin(10)) {
Serial.print("The SD card cannot be found");
while(1);
}
}
SDfound = 1;
// Serial.print("The SD card found");
printFile = SD.open("test.txt");
if (!printFile) {
Serial.print("The text file cannot be opened");
while(1);
}
while (printFile.available()) {
buffer = printFile.readStringUntil('\n');
Serial.println(buffer); //Printing for debugging purpose
if (buffer == "4652"){ // checking string
Serial.println("found");
}
}
printFile.close();
}
void loop() {
//empty
}
What output are you getting on Serial Monitor? Not much point in having all that debug output if you don't show us what you get. You can select the text in Serial Monitor and copy and paste it right to here.
You may have a trailing '\r' remaining with readStringUntil('\n'). String.trim() will remove spaces, but not the trailing characters.
Rather than stripping the end characters and then making a text comparison to a number, it is more simple to convert the String from text to a number with String.toInt() and making an integer comparison.
while (printFile.available()) {
buffer = printFile.readStringUntil('\n');
Serial.println(buffer); //Printing for debugging purpose
if (buffer.toInt() == 4652){ // checking integer
Serial.println("found");
}
Note that this works only for integers (besides 0).
if you want to recognize "0" and say you receive "Error" then as "Error" can't be parsed into an int, the the toInt() method returns 0
Also if you want to recognize a text string like "OK" or a floating point number "12.23" then it won't work.
It would be better for you to understand why it was not working in the first place (I suspect there is trailing carriage return '\r' that you can't see in the buffer)