Wow. Thanks for reading through the code carefully. Indeed, you found some errors that I had glossed over entirely (RTC started twice... for example)
Implementing your suggestion about opening the SD card in the Setup (only) resolved my write-to-card problem entirely. I have also cleaned up the code now to remove superfluous serial-write and comments.
Thanks for your help, and kind regards....the working code appears below:
#include "HX711.h"
#include "SD.h"
#include "RTClib.h"
RTC_PCF8523 rtc;
#define SD_FAT_TYPE 3
#define PIN_SPI_CS 4
#define FILE_NAME "udata.csv"
HX711 scale;
const int chipSelect = 10;
File myFile;
uint8_t dataPin = 2;
uint8_t clockPin = 3;
float f;
int i; // iteration counter
int j; // pre-set, total number of iterations to perform
// code for setting up SD and checking RTC
void setup() {
Serial.begin(115200);
delay(3000);
while (!Serial) { ; } // wait for serial port to connect.
Serial.println("Initializing Serial Port.");
i = 1;
j = 20; // number of iterations to perform
// SETUP RTC MODULE
if (!rtc.begin()) {
Serial.println(F("Couldn't find RTC"));
while (1)
;
}
// Setup SD card
if (!SD.begin(chipSelect)) {
Serial.println("SD Card initialization failed, or not present!");
while (1)
;
}
Serial.println("SD Card initialization done.");
// setup the HX711 module
scale.begin(dataPin, clockPin);
scale.set_scale(2340); // scale output from the 1 kg beam so that output is in Gram units
scale.tare();
// open the SD card-file and check
myFile = SD.open(FILE_NAME, FILE_WRITE);
if (myFile) {
Serial.println(F("File is open"));
} else {
Serial.print(F("SD Card: error on opening file "));
Serial.println(FILE_NAME);
return;
}
}
void loop() {
if (i <= j) {
Serial.println(F("Collect data & writing log to SD Card"));
Serial.println(F("iteration:"));
Serial.println("writing date stamp");
DateTime now = rtc.now();
if (myFile) {
myFile.print(now.year(), DEC);
myFile.print('-');
myFile.print(now.month(), DEC);
myFile.print('-');
myFile.print(now.day(), DEC);
myFile.print(' ');
myFile.print(" , ");
myFile.print(now.hour(), DEC);
myFile.print(':');
myFile.print(now.minute(), DEC);
myFile.print(':');
myFile.print(now.second(), DEC);
Serial.println(now.second(), DEC);
myFile.print(" , "); // CSV delimiter between timestamp and data
Serial.println("reading & writing weight");
f = scale.get_units(5);
Serial.println(f);
myFile.print(f);
myFile.write("\n"); // new line
}
delay(1500);
} else if (i > j) {
myFile.print("end-of-test");
myFile.write("\n");
myFile.close();
Serial.println(F("File is closed"));
exit(0);
}
i = (i + 1);
}