I got the SD card reader, and an SD card, formatted it and after wiring it up, I was able to successfully run all of the Example sketches.
My need for the SD reader was for a project where I need to compare an SMS message from a FONA to a file of 1500-2000 words. So I adjusted the last section of the Example Read/Write sketch to add a search function.
The problem is, if I search on the first word in the file, the search is successful and shows a match. But if I look for any other word that is in the file, they are not found. I have also created text files in Notepad, Notepad++ and Excel, and all work exactly the same: If I search for the first word in the file, I find it, any other words are not found. The words can very in length from 3 to 10 letters, so I also tried creating words of uniform length, but that did not change the result.
Also I am attaching a snapshot where you can see that it does match, but when I print out what is in the "buf" variable, there are usually characters from the next word on the list. Is there a special way to create or search a text file? Do I need to (and how would I) search for a carriage return or end of line for each search?
Code: Select all
#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("trial.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to trial.txt...");
myFile.println("test");
myFile.println("testing");
myFile.println("tesla");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
// re-open the file for reading:
myFile = SD.open("trial.txt");
if (myFile) {
Serial.println("trial.txt:");
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
int result = 0;
int k = 0;
char buf[10];
myFile = SD.open("trial.txt");
// read from the file until there's nothing else in it:
while (myFile.available() && result != 1) {
k = k+1;
myFile.read(buf,12);
if(strncmp(buf, "test", 4) == 0)
{
Serial.println(" ");
Serial.println("Match!");
result = 1;
}
Serial.println(k); // Just for keeping track of loop
Serial.print("Buffer: ");Serial.println(buf);
Serial.println(" ");
}
if (result == 0);
{
Serial.println("No Match!");
}
// close the file:
myFile.close();
// }
}
void loop() {
// nothing happens after setup
}