5

I have a text file on an SD card, and I am trying to print the lines to the serial monitor.

This Code Works:

#include <SPI.h>
#include <SD.h>

File myFile;

void setup()
{
  Serial.begin(9600);


  Serial.print("Initializing SD card...");

  pinMode(10, OUTPUT);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  myFile = SD.open("c.txt");
  if (myFile) {
    Serial.println("c.txt:");

    while (myFile.available()) {
      Serial.write(myFile.read());  //THIS LINE RIGHT HERE
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening c.txt");
  }
}

void loop()
{
}

However, if I replace the line Serial.write(myFile.read()); with Serial.println(myFile.read());, then the code doesn't return the correct lines.

It should return numbers similar to this (albeit 3000 of them):

564
564
564
564
564
564
564
464
564
664
564

If I use Serial.println it returns numbers like this (and it doesn't stop at 3000 lines):

13
10
54
54
52
13
10
53
54
52

And if I try to do int(myFile.read()) then the integer becomes the wrong numbers (returned by println), not the right ones (returned by write).\

How do I get a number returned by Serial.write(myFile.read()); to be an integer?

4

The text file contains the sequential ascii values that spell out the data, not binary data. println in printing the numerical value of each byte. For example, the 10's println prints are '\n' characters. write is printing the ascii character associated with the binary value (the new line). You need to parse the ascii characters into numbers.

Luckily for you the SD library inherits from the Stream class, so it will have the same parseInt function most often used to parse ints from the serial monitor.

You probably want to set myFile.setTimeout(0) first because the file isn't slowly getting characters from the serial bus, so the timeout would just slow you down.

Then you should be able to parse and print out the ascii integers with something like this:

int val = myFile.parseInt();
Serial.println(val);
  • I couldn't ask for a better answer! – user3151828 Jan 18 '15 at 13:11

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.