1

I'm using an SD card module with ESP32. My plan is to store configurations such as SSID and passwords.

I tried the function with a text file which contains the text "Hello" and for Serial.write(file.read()); it prints exactly "Hello". But, Serial.print(file.read()); returns 72101108108111. What kind of data type returns read()? I need to convert it into string.

void readFile(fs::FS &fs, const char * path){
  Serial.printf("Reading file: %s\n", path);

  File file = fs.open(path);
  if(!file){
    Serial.println("Failed to open file for reading");
    return;
  }

  Serial.print("Read from file: ");
  while(file.available()){
    //Serial.write(file.read());
    Serial.print(file.read());
  }
  file.close();
}
Null
  • 7,448
  • 17
  • 36
  • 48
kachaya
  • 11
  • 1

1 Answers1

1

That's decimal values of the characters Hello.

72 is decimal for H
101 is decimal for e
108 is decimal for l
111 is decimal for o
See any ascii chart on the internet, eg. This Ascii Chart

Maybe try something like this instead:
Serial.printf("%s\n", file.read());

UPDATE:
As noted in the comments, doing a cast is more memory efficient than using printf().
So Serial.print( (char)file.read() );
and you can also use streams:
Serial<<(char)file.read();

Aaron
  • 7,274
  • 16
  • 30
  • An explicit conversion to `char` is preferable because `printf()` uses lots of program memory... see dandavis' comment. It might not be a big deal on an ESP32, but using `printf()` on an Arduino Uno is close to a no-go ;) – Sim Son Feb 14 '22 at 20:37
  • Doing a cast won’t work as the array of bytes is not null terminated. The streams method is a better and more robust solution. – Kartman Feb 14 '22 at 22:23