Baffling SD Library Behaviour - Datafile Size Zero on Second Sketch?

I am writing a file to an SD card on a 1.8" TFT LCD. I end the sketch with a file.close and then in the same sketch I reopen it for a READ and the size is as it should be. I then close it again and loop until 1==1. At this point I start another sketch that does nothing more than open the file and tell me its size. I get the answer that it is of size zero. I must be doing something bonkers but I can not see what. Code snippets are below:

First Sketch (displays correct size of file):

            tft.print(totalObs);
            tft.println(" Obs");
            tft.print(String(datafile.size()));
            tft.println(" Bytes");
            datafile.flush();
            tft.print(String(datafile.size()));
            tft.println(" Bytes");
            datafile.close();
            datafile = SD.open("datalog.txt", FILE_READ);
    
            // Is the file available?
            if (!datafile) {
                displayError("SD err 03");
                while(1==1) {};
            }
            displayError(String(datafile.size()));    
            datafile.close();
            while (1==1);

[u]Second Sketch (displays zero!)[/u]

    if (!SD.begin(sdCS)) {
        displayError("SD err 01");
        while(1==1) {};
    }
    datafile = SD.open("datalog.txt", FILE_READ);

    // Is the file available?
    if (!datafile) {
        displayError("Err " + String(datafile.size()));    
        while(1==1) {};
    }
    displayError(String(datafile.size()));

It would be much more helpful to see the whole of both programs or cut down but working programs that exhibit the problem.

UKHeliBob:

Hmm. That is a very fair point and I should have done it in the first place. It is an almost max memory script so I have some poking to do.

Wisar

Per the above. Here is a very hacked up version of the sketch from above. I tried to get it to a minimum lines of code but still have the problem surface.

Note that this version works. The file generated is preserved with data in it. If, however, you delete either of the two sections of code marked with comments, the script no longer works and leaves a zero byte file.

I assume that I am corrupting something in memory that is threshold sensitive but can not isolate the problem nor do I know how to even look for it at this point!

// ***************************************************************
//  Class Library Includes
// ***************************************************************
#include <Adafruit_GFX.h>       // Adafruit Graphics-Library
#include <Adafruit_ST7735.h>    // Adafruit ST7735-Library
#include <SPI.h>                // For the SD card reader/writer
#include <SD.h>                 // Ditto

// ***************************************************************
//  Instantiate our classes
// ***************************************************************
// Setup the display
#define tftCS           10      // Tft Pins
#define tftDC           9    
#define tftRST          8    
Adafruit_ST7735 tft = Adafruit_ST7735(tftCS, tftDC, tftRST);

#define sdCS            4       // sd CS pin
File datafile;

/*****************************************************************************/
// ***************************************************************************
// SETUP
// ***************************************************************************
/*****************************************************************************/
char buffer[10];

void setup() {
    Serial.begin(115200);
    
    tft.initR(INITR_BLACKTAB);
    tft.setRotation(1);

    pinMode(tftCS, OUTPUT);
    pinMode(sdCS, OUTPUT);
    
    if (!SD.begin(sdCS)) {
        displayError("SD err 01");
        while(1==1){}
    }
    if (SD.exists("datalog.txt")) {
        if (!SD.remove("datalog.txt")) {
            displayError("SD err 02");
            while(1==1){}
        }
    }
    datafile = SD.open("datalog.txt", FILE_WRITE);

    // If the file is available, write a header record to it:
    if (datafile) {
        datafile.write("*Te*,*Hu*|", 10);
    }
    // If the file did not open, pop up an error:
    else {
        displayError("SD err 03");
        while(1==1){}
    }
}

/*****************************************************************************/
// ***************************************************************************
// PROCESSING LOOP
// ***************************************************************************
/*****************************************************************************/
long obs = 0, totalObs;
int lowT = 99, highT = -99,
    lowH = 99, highH = -99;
int lowT_Range, lowH_Range,
    highT_Range, highH_Range;

int menuState = 1;

void loop() {
    switch (menuState) {
        case 1:
            displayHistory();
            menuState = 3;
            break;

        case 3:
            tft.fillScreen(ST7735_BLACK);
            tft.setTextSize(2);
    	    tft.setCursor(0, 0);
            tft.setTextColor(ST7735_WHITE);
            tft.println("Halted");
            tft.println();
            tft.print(totalObs);
            tft.println(" Obs");
            tft.print(String(datafile.size()));
            tft.println(" Bytes");
            datafile.flush();
            datafile.close();
            while(1==1){}
            datafile = SD.open("datalog.txt", FILE_READ);
    
            // Is the file available?
            if (!datafile) {
                displayError("SD err 03");
                while(1==1) {};
            }
            displayError(String(datafile.size()));    
            datafile.close();
            while (1==1);

    }
    // ***********************************************************
    // **** DELETE CHOICE 1 **************************************
    // ***********************************************************
    // Delay and wait for a button...log observations while waiting
    waitForButton();
    // ***********************************************************
}

void logObservation() {
    totalObs++;
    
	String(padInt(5, 4) + "," + padInt(5, 4) + "|").toCharArray(buffer, 10);
    datafile.write(buffer, 10);

	return;
}

/*****************************************************************************/
// ***************************************************************************
// DISPLAY HISTORY
// ***************************************************************************
/*****************************************************************************/
void plotObservations() {
	long o = 1;
	int eof = false;
	while (!eof) {
        Serial.print(o);
	    if (datafile.seek(o++ * 10)) {
	        for (int i = 0; i<10; i++) {
	            buffer[i] = datafile.read();
	        }
            Serial.print(" - ");
            Serial.println(buffer);
			if (buffer[4] == ',') {
            }
            else {
                eof = true;
            }
		}
	    else {
	        eof = true;
	    }
	}
}

void plotObservation(long o, int t, int h) {

}

void displayHistory() {
    int running = true;
    while (running) {
        tft.fillScreen(ST7735_BLACK);
        // Left Y Axis Bar
        tft.fillRect(0, 0, 15, 120, ST7735_RED);
        // Right Y Axis Bar
        tft.setTextSize(1);
        tft.fillRect(145, 0, 15, 120, ST7735_GREEN);
    
        // ***********************************************************
        // **** DELETE CHOICE 2 **************************************
        // ***********************************************************
        // Axis labels
        tft.setRotation(0);
        tft.setTextSize(1);
        tft.setTextColor(ST7735_WHITE);
        tft.setCursor(22, 4);
        tft.print(lowT_Range);
        tft.setCursor(60, 4);
        tft.print("Temp");
        tft.setCursor(110, 4);
        tft.print(highT_Range);

        tft.setTextColor(ST7735_BLACK);
        tft.setCursor(22, 150);
        tft.print(lowH_Range);
        tft.setCursor(65, 150);
        tft.print("Hum");
        tft.setCursor(110, 150);
        tft.print(highH_Range);
        tft.setRotation(1);
        // ***********************************************************
        // ***********************************************************
    
        // Footer
        tft.setTextSize(1);
        tft.fillRect(0, 110, 160, 10, ST7735_WHITE);
        tft.setTextColor(ST7735_BLACK);
        tft.setCursor(30, 112);
        tft.print(totalObs);
        tft.print(" Obs (");
        tft.print((float)totalObs / 2 / 60); 
        tft.print(" hrs)"); 
    
        plotObservations();
        
        // Delay and wait for a button...log observations while waiting
        if (waitForButton()) {
        }
        running = false;
    }
}

/* ************************************************************************
Add ability to force size of decimal result and to pad left with optional character
************************************************************************ */
String padInt(int in, int size) {
    return("0000");
}

/* ************************************************************************
Display an error message
************************************************************************ */
void displayError(String message) {
    tft.fillScreen(ST7735_BLACK);
    tft.setTextSize(2);
    tft.setTextColor(ST7735_RED);
	tft.println("ERR");
    tft.setTextSize(1);
    tft.setTextColor(ST7735_WHITE);
	tft.println("\n\n" + message);
	delay(10000);
}

/* ************************************************************************
Delay for 'n' seconds waiting for a button press returning true if pressed
************************************************************************ */
int waitForButton() {
    logObservation();
    logObservation();
    logObservation();
    return(true);
}

The target for this sketch is an Nano connected to a 1.8" TFT with an SD card reader/writer.

Rebuilt the hardware back to breadboard. Testing to date has been on a circuit board built to purpose from the breadboard. Wired the same as the circuit board schematic yet the breadboard version works. It is using a different display. Could it be the display or is a short circuit on the PCB a possibility. Will continue to experiment (and to talk to myself).

[Final Update]

Took display and Arduino from working breadboard configuration and installed on another PCB and IT DOES NOT WORK! Same problem as described above. Obviously a problem with the PCB. I can not see a difference between them though.

Am going to repost this as a hardware problem in the hardware section of the forum as I hope someone else may have seen a similar situation and be able to advise on an approach to diagnose/solve.