I have a program that is sending data from an RTC and an accelerometer to an SD card for logging. However, when I run it the code, it works for a few cycles, then gives me an error. I have included the loop part of my code and the output from the serial monitor below.
I have tried changing the rate at which it checks data to every 5 seconds instead of every 1, and it did not make a difference. I have also tried changing the chip select pin that my SD reader is connected to, but it also did not make a difference.
Both the amount of time it runs before it fails and the number of cycles it runs before it fails vary from time to time. When I was running it and having it just output to the serial monitor, I was not encountering a problem, it showed up after I started sending to the SD card instead. Any suggestions?
void loop() {
unsigned long currentMillis = millis();
if((currentMillis - previousMillis) > 1000){
myFile = SD.open("current.txt", FILE_WRITE);
if (myFile) {
Serial.println("File found. Recording data to file...");
myFile = SD.open("current.txt", FILE_WRITE);
myFile.print(CollarID);
myFile.print(", ");
readDateTime(); //sends a datetime value to the SD card
readXYZ(); //sends accelerometer data to the SD card
myFile.close();
Serial.println("done.");
previousMillis = currentMillis;
} else {
Serial.println("Error opening file.");
}
}
}