2

This is a part of my program which reads data from file stored in SD card and displays that on an LCD screen.

 File dataFile = SD.open("1165.txt");
 if (dataFile) {
 Serial.println("File Opened");
 lcd.clear();
 delay( 5 ); //LCD-specific M
 lcd.setCursor( 0,0 );
 while (dataFile.available()) {
 Serial.write(dataFile.read());
 lcd.write(dataFile.read());
 lcd.print(dataFile.read());
 }
 dataFile.close();
 } else {
 // if the file didn't open, print an error:
 Serial.println("error");
 }

When I look at the serial monitor it prints the contents of that file but none of these commands print what is printed in the serial monitor,

lcd.write(dataFile.read());
lcd.print(dataFile.read());

Any ideas?

Nick Gammon
38.9k13 gold badges69 silver badges125 bronze badges
asked Jul 27, 2015 at 18:37

2 Answers 2

2

When you call dataFile.read(), the file pointer is advanced, so you always read different bytes in each read call. Imagine the file like a book with many lines: Each time you read, you advance the current line, so with multiple calls, you never get the same data. The solution is to currently store the last read byte:

while (dataFile.available()) {
 char readByte = dataFile.read();
 Serial.write(readByte);
 lcd.write(readByte);
 lcd.print(readByte);
}

You have two calls for displaying data in the LCD, but be careful that the second call (print) might interpret your data as a number, so just remove the lcd.print(readByte) call altogether to be sure it's printing the raw character.

answered Jul 28, 2015 at 10:05
1

You could also implement a readLine routine, similar to:

void _readLine(File f, char *line)
{
 boolean cr_found = false;
 int p = 0;
 while (f.available()) {
 char b = f.read();
 if(b!='\r' && b!='\n')
 line[p++] = b;
 if(b == '\r') cr_found = true;
 if((b == '\n') && cr_found) break;
 }
 line[p] = '0円';
}

And read the SD file line by line, processing each one of them by its own.

char buffer[32];
while(dataFile.available()) {
 _readLine(dataFile, buffer);
 // do something with buffer
}
answered Oct 22, 2015 at 11:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.