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?

1

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.

0

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.