Cannot open SD-File

Hey I’m trying to save some Data to an SD-Card. First I tried it standalone in the setup function as you get it from the arduino examples. But in my program it won’t work. The initialization is ok, also I can see that the file exists but I cannot open it. Maybe somebody can help me. Thanks!

This is what I get from the serialmonitor:

28
29
30
Initializing SD card…initialization done.
test.txt exists.
try to open test.txt
value of myFile=0
error opening test.txt
31
32

#include "Wire.h"
#include <SD.h>

//**************************************constant
#define DS1307_ADDRESS 0x68
#define DS3231_SECONDS 0x00
#define DS3231_MINUTES 0x01
#define DS3231_HOURS   0x02
#define DS3231_DAY     0x03
#define DS3231_DATE    0x04
#define DS3231_MONTH   0x05
#define DS3231_YEAR    0x06

#define NUMBER_OF_MEASUREMENTS 40

File myFile;

//**************************************global vars
double measurement_value[NUMBER_OF_MEASUREMENTS];
String measurement_name[NUMBER_OF_MEASUREMENTS];



//**************************************setup
void setup(){
  pinMode(10, OUTPUT); //needet for sd lib
  Wire.begin();
  Serial.begin(9600);
}



//**********************************************************************************************
//**************************************  main  ***********************************************
//**********************************************************************************************
	 
void loop()
{
  //clock_set_Date(DS3231_SECONDS,0x33);
  Serial.print(clock_get_Date(DS3231_SECONDS));
  Serial.print("\n");
   
  //test
  int i=0;
  for(i=0;i<NUMBER_OF_MEASUREMENTS;i++)
  {
    measurement_value[i] = (double)i; 
  }
   
  if(clock_get_Date(DS3231_SECONDS)== 30)
  {
    save_measurement();
  }

}




//**********************************************************************************************
//**************************************functions***********************************************
//**********************************************************************************************

//**************************************clock
 byte bcdToDec(byte val){
 // Convert binary coded decimal to normal decimal numbers
  return ( (val/16*10) + (val%16) );
}
	 
int clock_get_Date(int i){

  // Set registerpointer to first register
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.write(0);
  Wire.endTransmission();
  delay(500);
  	 
  Wire.requestFrom(DS1307_ADDRESS, 7);
  
  int second = bcdToDec(Wire.read());        
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
  int weekday = bcdToDec(Wire.read()); //0-6 -> sunday - Saturday
  int monthday = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());
  
  switch(i)
  {
    case 0: return second; 
    break;
    case 1: return minute; 
    break;
    case 2: return hour; 
    break;
    case 3: return weekday; 
    break;
    case 4: return monthday; 
    break;
    case 5: return month; 
    break;
    case 6: return year; 
    break;
    default:
    break;
  } 
}

void clock_set_Date(int clockregister, byte value){

  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.write(clockregister);
  Wire.write(value);
  Wire.endTransmission();
}  

//**************************************sd functions

void save_measurement(void)
{
  int i;
 
  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin 
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output 
  // or the SD library functions will not work. 
   
  if (!SD.begin(10)) 
  {
    Serial.println("initialization failed!");
    return;
  }
  else
  {
    Serial.println("initialization done.");
    
    
    if (SD.exists("test.txt")) 
    {
      Serial.println("test.txt exists.");
    }
    else 
    {
      Serial.println("test.txt doesn't exist.");
    }
   
     // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    Serial.println("try to open test.txt");
    myFile = SD.open("test.txt", FILE_WRITE);
   
    Serial.print("value of myFile=");
    Serial.println(myFile);
    
    // if the file opened okay, write to it:
    if (myFile) 
    {
      Serial.print("Writing to test.txt...");
     
      for(i=0;i<NUMBER_OF_MEASUREMENTS;i++)
      {
        myFile.println(measurement_value[i]);
        myFile.println(";\t");
      }
      // close the file:
      myFile.close();
      Serial.println("done.");
    } 
    else 
    {
      // if the file didn't open, print an error:
      Serial.println("error opening test.txt");
    }
  
  }
}

Is your SD card formatted properly - IIRC, I saw some reference suggesting that it's important what you used to format it.

Can you create a simpler sketch and write on a file at all?

Can you write on a file that doesn't already exist?

Try it without the String array - the SD library uses RAM - perhaps you're running out.

Not the issue, but the compiler is likely complaining behind the scenes that clock_get_Date doesn't have a return value for all paths of execution.

Hello Bill, thanks for your reply!

I did some tests now. First what I can say is that the initialization of the sdcard must be in the setup. Second I did some tests relating the RAM. With the Memoryfree.h (http://playground.arduino.cc/Code/AvailableMemory) I could find out that I have the following situations.

wire.h active Number of doubleVars= 4 Freememory (bevore opening file )= 634 Freememory (after opening file )= 603 =>> program working

wire.h inactive Number of doubleVars= 40 Freememory (bevore opening file )= 301 Freememory (after opening file )= 270 =>> program working

wire.h active Number of doubleVars= 40 Freememory (bevore opening file )= 130 Freememory (after opening file )= 130 =>> program NOT working

So I think it is proven that you're right with your idea that I running out of RAM.

By the way I'm using a Arduino Nano and the Programsize is now 20kb so there are only 10kb left and there are many functions not implemented at this time. I think I need another solution. Maybe a Mega2560 or sth.

*double AND String vars!

sorry for my English

I have a similar problem.
first recorded on a SD card makes a nice.
when I want to re-write the card would not open file
I get
value of myFile=0

it is possible to have a problem with RAM?

code:
   if (tm.Hour == 7 && tm.Minute == 5 ) {
    
     
myFile = SD.open("podatki.txt", FILE_WRITE);
unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
   previousMillis = currentMillis;  
 // if the file opened okay, write to it:
if (myFile) {
  
  scale.power_up();
        scale.set_gain(32);
scale.set_scale(5594.f);  
meri =(scale.get_units(10));
float kga = meri;
kga = kga-1489.1;
if (kga < 0)
{
kga=0;
}
kg = kga; 
   Serial.println(myFile);
   Serial.print("Writing to podatki.txt...");
   myFile.print(tmYearToCalendar(tm.Year));
   myFile.print(".");
   myFile.print(tm.Month);
   myFile.print(".");
   myFile.print(tm.Day);
   myFile.print(".");
   myFile.print(" ");
   myFile.print(tm.Hour);
   myFile.print(":");
   myFile.print(tm.Minute);
   myFile.print(" ");
   myFile.print(kg);
   myFile.print(" kg");
   myFile.println();
   myFile.close();
}
}
// Serial.println(myFile);
}

//tmElements_t tm;
// RTC.read(tm);
//bbscale.power_down();

if (tm.Hour == 7 && tm.Minute == 49 ) {


 myFile = SD.open("podatki.txt", FILE_WRITE);

 
unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
   previousMillis = currentMillis;  
 // if the file opened okay, write to it:
if (myFile) {
  
  scale.power_up();
        scale.set_gain(32);
scale.set_scale(5594.f);  
meri =(scale.get_units(10));
float kga = meri;
kga = kga-1489.1;
if (kga < 0)
{
kga=0;
}
kg = kga; 
   Serial.println(myFile);
   Serial.print("Writing to podatki.txt...");
   myFile.print(tmYearToCalendar(tm.Year));
   myFile.print(".");
   myFile.print(tm.Month);
   myFile.print(".");
   myFile.print(tm.Day);
   myFile.print(".");
   myFile.print(" ");
   myFile.print(tm.Hour);
   myFile.print(":");
   myFile.print(tm.Minute);
   myFile.print(" ");
   myFile.print(kg);
   myFile.print(" kg");
   myFile.println();
   myFile.close();
}
else
{
Serial.println(myFile);
Serial.println("ne odpre file");
Serial.println(myFile);
myFile = SD.open("podatki.txt", FILE_WRITE);
// return;
}
}
}

It's hard to say without seeing all the code, but it looks like you have the possibility of failing to close the file after you have opened it. Once the file is open, closing it depends on the result of this line:

  if(currentMillis - previousMillis > interval) {

It would probably be better if the open depended on that line too.

whole code

#include "HX711.h"
HX711 scale(2, 3); 

#include <HX711.h>
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <SD.h>
File myFile;
File myFilenic;

// interval zapisovanja na SD
long previousMillis = 0;       
long interval = 6000;
// interval

// interval tipke
long previousMillist = 0;       
long intervalt = 1000;
// interval

// interval delovanja
long previousMillism = 0;       
long intervalm = 30000;
// interval

//float meritve[6];
float meri;
float kg=0.0;
float kga=0.0;
float kga2=0.0;
//int stm = 0;

const int buttonPin = 9; 
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0; // previous state of the button

//RTC_Millis rtc;
LiquidCrystal_I2C lcd(0x27, 16, 2);


void setup() {
 Serial.begin(9600);
    
lcd.begin();
//lcd.backlight();
    
    pinMode(10, OUTPUT);
  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
     lcd.setCursor(0, 1);
     lcd.print("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  if (SD.exists("podatki.txt")) {
    Serial.println("podatki.txt exists.");
  }
  else {
     Serial.println("Creating podatki.txt...");
  myFile = SD.open("podatki.txt", FILE_WRITE);
  myFile.close();
  }
  // open a new file and immediately close it:
   myFilenic = SD.open("nic.txt", FILE_WRITE);
  myFilenic.close();
  // Check to see if the file exists:
  if (SD.exists("podatki.txt")) {
    Serial.println("podatki.txt exists.");
  }
  else {
    Serial.println("podatki.txt doesn't exist.");
  }
  myFilenic.close();   
}

void loop() {
  
  // intervala delovanje/spanje
  
 unsigned long currentMillism = millis(); //spremenjen interval za delno uspavanje
 if (currentMillism < intervalm) {    

lcd.backlight();
  
//   Serial.println(intervalm);
 
     ///tipka
 buttonState = digitalRead(buttonPin);
  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {  
     buttonPushCounter++;
    }
  }
  lastButtonState = buttonState;
 ////tipka
  lcd.setCursor(0, 0); // displej nastavitve pozicije
lcd.backlight();

  if (buttonPushCounter % 2 == 0) {
//   scale.set_gain(128);
      scale.set_gain(32);
scale.set_scale(5594.f);  
meri =(scale.get_units(10));
float kga = meri;
kga = kga-1489.1;
if (kga < 0)
{
kga=0;
}
 kg = kga;  
 lcd.print(kg, 1);  
   lcd.print("kg  ");

 } 
    else 
  {
    
          scale.set_gain(32);
scale.set_scale(5594.f);  
meri =(scale.get_units(10));
float kga = meri;
kga = kga-1489.1;
    
 if (buttonState == HIGH) {
   kga2 = kga;
   }
    kg = kga - kga2;
    
lcd.print(kg, 1);
  lcd.print("kg-");
  lcd.print(" ");//zbriše ostanek številke
  }

     // datum 
lcd.setCursor(0, 1);
 tmElements_t tm;
 RTC.read(tm);
  
    lcd.print(tm.Hour);
    lcd.print(':');
    lcd.print(tm.Minute);
    lcd.print(':');
    lcd.print(tm.Second);
    lcd.print("  ");
    lcd.print(tm.Day);
    lcd.print('/');
    lcd.print(tm.Month);
    lcd.print("   "); 
   
    if (tm.Hour == 7 && tm.Minute == 22 && tm.Second == 30) {
 myFile = SD.open("podatki.txt", FILE_WRITE);
 unsigned long currentMillis = millis();
   if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;  
  // if the file opened okay, write to it:
 if (myFile) {
   
         scale.set_gain(32);
scale.set_scale(5594.f);  
meri =(scale.get_units(10));
float kga = meri;
kga = kga-1489.1;
if (kga < 0)
{
kga=0;
}
 kg = kga; 
 
    Serial.print("Writing to podatki.txt...");
    myFile.print(tmYearToCalendar(tm.Year));
    myFile.print(".");
    myFile.print(tm.Month);
    myFile.print(".");
    myFile.print(tm.Day);
    myFile.print(".");
    myFile.print(" ");
    myFile.print(tm.Hour);
    myFile.print(":");
    myFile.print(tm.Minute);
    myFile.print(" ");
    myFile.print(kga);
    myFile.print(" kg");
    myFile.println();
 myFile.close();
 }
}
}
   if (tm.Hour == 22 && tm.Minute == 47 && tm.Second == 30) {
 myFile = SD.open("podatki.txt", FILE_WRITE);
 unsigned long currentMillis = millis();
   if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;  
  // if the file opened okay, write to it:
 if (myFile) {
   
         scale.set_gain(32);
scale.set_scale(5594.f);  
meri =(scale.get_units(10));
float kga = meri;
kga = kga-1489.1;
if (kga < 0)
{
kga=0;
}
 kg = kga; 
 
   Serial.println(myFile);
    Serial.print("Writing to podatki.txt...");
    myFile.print(tmYearToCalendar(tm.Year));
    myFile.print(".");
    myFile.print(tm.Month);
    myFile.print(".");
    myFile.print(tm.Day);
    myFile.print(".");
    myFile.print(" ");
    myFile.print(tm.Hour);
    myFile.print(":");
    myFile.print(tm.Minute);
    myFile.print(" ");
    myFile.print(kga);
    myFile.print(" kg");
    myFile.println();
 myFile.close();
 }
}
}// konec zapisovanja na SD  
}// konec intervala delovanje/spanje
  
  else
  {
   lcd.clear();
   lcd.setBacklight(LOW);
   scale.power_down();
   
   
// Serial.println(kga2);

//  Serial.println(buttonPushCounter);

         buttonState = digitalRead(buttonPin);
         if (buttonState == HIGH) {
        intervalm = currentMillism + 30000; //spremenjen interval za delno uspavanje
      
        lcd.backlight();
        delay(1500);
           // buttonPushCounter++; 
         }
             
 tmElements_t tm;
 RTC.read(tm);
               
    if (tm.Hour == 7 && tm.Minute == 5 ) {
     
      
 myFile = SD.open("podatki.txt", FILE_WRITE);
 unsigned long currentMillis = millis();
   if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;  
  // if the file opened okay, write to it:
 if (myFile) {
   
   scale.power_up();
         scale.set_gain(32);
scale.set_scale(5594.f);  
meri =(scale.get_units(10));
float kga = meri;
kga = kga-1489.1;
if (kga < 0)
{
kga=0;
}
 kg = kga; 
    Serial.println(myFile);
    Serial.print("Writing to podatki.txt...");
    myFile.print(tmYearToCalendar(tm.Year));
    myFile.print(".");
    myFile.print(tm.Month);
    myFile.print(".");
    myFile.print(tm.Day);
    myFile.print(".");
    myFile.print(" ");
    myFile.print(tm.Hour);
    myFile.print(":");
    myFile.print(tm.Minute);
    myFile.print(" ");
    myFile.print(kg);
    myFile.print(" kg");
    myFile.println();
    myFile.close();
 }
}
// Serial.println(myFile);
}

//tmElements_t tm;
// RTC.read(tm);
//bbscale.power_down();

 if (tm.Hour == 7 && tm.Minute == 49 ) {
 

  myFile = SD.open("podatki.txt", FILE_WRITE);
 myFile = SD.open("podatki.txt", FILE_WRITE);
  
  Serial.println(myFile);
  
 unsigned long currentMillis = millis();
   if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;  
  // if the file opened okay, write to it:
 if (myFile) {
   
   scale.power_up();
         scale.set_gain(32);
scale.set_scale(5594.f);  
meri =(scale.get_units(10));
float kga = meri;
kga = kga-1489.1;
if (kga < 0)
{
kga=0;
}
 kg = kga; 
    Serial.println(myFile);
    Serial.print("Writing to podatki.txt...");
    myFile.print(tmYearToCalendar(tm.Year));
    myFile.print(".");
    myFile.print(tm.Month);
    myFile.print(".");
    myFile.print(tm.Day);
    myFile.print(".");
    myFile.print(" ");
    myFile.print(tm.Hour);
    myFile.print(":");
    myFile.print(tm.Minute);
    myFile.print(" ");
    myFile.print(kg);
    myFile.print(" kg");
    myFile.println();
    myFile.close();
 }
 else
 {
 Serial.println(myFile);
 Serial.println("ne odpre file");
 Serial.println(myFile);
 myFile = SD.open("podatki.txt", FILE_WRITE);
// return;
 }
}
// Serial.println(myFile);
}
}
}// konec - void loop()ž

// Serial.println(myFile);
 
void print2digits(int number) {
  if (number >= 0 && number < 10) {
    Serial.write('0');
  }
  Serial.print(number);
}

(Good try - Next time, use code tags, not quote tags. Moderator)

works, thanks for the advice.