Problem reading data in sd card.

Hello guys,
currently i’m working on a school project that retrieve data from text file that stored in sd card. I’m using sparkfun sd card shield and arduino mega 2560. The SPI pin i follow the configuration below:

Shield pin 10 –> Mega pin 53
Shield pin 11 –> Mega pin 51
Shield pin 12 –> Mega pin 50
Shield pin 13 –> Mega pin 52

data in text file from sd card like picture i attach together in this post and here is my code so far :

#include <SD.h>

File myFile;

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


  Serial.print("Initializing SD card...");
 
   pinMode(53, OUTPUT);
   
  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  
 
  
  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
 
    
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
    	Serial.write(myFile.read());
    delay (1000);
    }
    // close the file:
    myFile.close();
  } else {
  	// if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop()
{


  
char val = myFile.read();
if ( val == 'H'){
  digitalWrite (31, HIGH);
}else {
  digitalWrite (31, LOW);}
}

i already connect the pin 31 to the LED but the LED seems not working (on/off) according to the data in text file. so if anyone can help me it would be great. Thank you.

Capture.PNG

You open the file in setup(), read everything in the file and print it to the serial port. Then, you close the file.

Then, in loop(), you try to read from a file that is not opened. How can you expect that to work?

PaulS:
You open the file in setup(), read everything in the file and print it to the serial port. Then, you close the file.

Then, in loop(), you try to read from a file that is not opened. How can you expect that to work?

Hello PaulS,
i'm very new with the sd programming, so that i could just delete the line for closing the file and it should be work or is it another alternative way to make the code work?

i could just delete the line for closing the file and it should be work

No. You still read all the data in setup(), so there is nothing left to read in loop(). Why are you doing that?

Why not toggle the LED in setup() if you are going to read the file there?

thank you PaulS for the info, the LED now can be control with the way i want.