Serial Monitor printing extra invisible value from file.read()

I have a file, TEST2.TXT, on an SD card that has the following content:

100
200

But when I print out each character to the serial monitor there's a mysterious invisible character at index 3. Index 4 looks to be the '\n' character.

Serial Monitor:

01:04:00.436 -> index 0: 1
01:04:00.436 -> index 1: 0
01:04:00.436 -> index 2: 0
01:04:00.436 -> index 3: 
01:04:00.436 -> index 4: 
01:04:00.436 -> 
01:04:00.436 -> index 5: 2
01:04:00.436 -> index 6: 0
01:04:00.436 -> index 7: 0

What is index 3? Also is there a way to serial print in a way that I can actually see what index 3 is?

Note: The above serial monitor section shows what I see in the serial monitor. But when I copy and paste the serial monitor text, this text editor is interpreting a carriage return at index 3. But why would there be two carriage returns printed differently?

01:04:00.436 -> index 0: 1
01:04:00.436 -> index 1: 0
01:04:00.436 -> index 2: 0
01:04:00.436 -> index 3: 

01:04:00.436 -> index 4: 
01:04:00.436 -> 
01:04:00.436 -> index 5: 2
01:04:00.436 -> index 6: 0
01:04:00.436 -> index 7: 0

Full Code:

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

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  if (!SD.begin(5)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");
  
  myFile = SD.open("test2.txt");
  if (!myFile) {
    // if the file didn't open, print an error:
    Serial.println("error opening file");
  }
  
  if (myFile) {
    byte numOfChar = 0 ;

    while ( myFile.available()) {

      char newChar = myFile.read();
      Serial.print("index ");
      Serial.print(numOfChar);
      Serial.print(": ");
      Serial.println(newChar);

      numOfChar++;

    }
  }
}

void loop() {

}

After reading a bit more I'm thinking one is an '\r' carriage return and one is an '\n' line feed. Not sure which is which. Is there a way to get the serial monitor to print '\n' or '\r' so I can see? This would help with future debugging if possible too.

From the Arduino language reference:

Syntax
Serial.print(val)
Serial.print(val, format)

Also see the example further down that webpage.

1 Like

Thanks @markd833!

I changed printing the character to binary.
Serial.println(newChar, BIN);

12:23:25.677 -> index 3: 1101
12:23:25.710 -> index 4: 1010

Then I can use this table to find the mysterious characters. 1101 is a Carriage Return and 1010 is a Line Feed.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.