1
\$\begingroup\$

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();
}
\$\endgroup\$
2
  • \$\begingroup\$ Well what does some sort of manual say about what serial.print() does? I can't even guess what framework you are using, is that Arduino or something else? \$\endgroup\$ Commented Feb 14, 2022 at 18:54
  • \$\begingroup\$ Serial.print((char)file.read()); \$\endgroup\$ Commented Feb 14, 2022 at 19:58

1 Answer 1

1
\$\begingroup\$

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();

\$\endgroup\$
2
  • \$\begingroup\$ 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 ;) \$\endgroup\$ Commented Feb 14, 2022 at 20:37
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Feb 14, 2022 at 22:23

Your Answer

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.