ERROR Opening File Problem

Hello everyone. I need help regarding an error when trying to open a file.
The SD card was successfully initialized at setup and the file was already created.
In the main loop, I have a function where I read sensors reading and save them to the same filename when initialized in Setup. The problem here is that usually when the first few times it opens the file to write into it, everything is ok. But then the next few times it opened, it was unable to open the file, then sometimes it managed to open again.

I have about 96 sensors connected to 6 multiplexers (16 each), so the read and write to sd is inside another loop since I need to go through each channel in the multiplexers.
This Arduino project also has a 12v exhaust fan connected to it so I use the 12V adapter to power the exhaust fan and then let it go through a buck converter 12V-5V to power the rest of the components, i.e. Arduino, dht22 sensors, multiplexers, sd module and so on.

When I run the Arduino powered through my laptop, without the exhaust fan, the SD card is was able to open the file without error even once. However, when I unplug it from my laptop and only powers it through the 12v, the problem I addressed above came up.
I also like mention that, previously, the first time I tested and collected my data for a day, the SD file was able to open and write everything. Then the following day, this problem happened.

My full code is here:

#include <SPI.h> // for sdcard

//SD Card Declaration
char fileName[13];
int pinCS = 53; 

#include "RTClib.h" //for rtc and lcd
#include <Wire.h>  //for rtc and lcd
#include <LiquidCrystal_I2C.h> //for rtc and lcd

//I2C LCD and RTC
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); 
RTC_DS3231 rtc;

int button1Pin = 2; //button S1
int redled_button1 = 12;

#define exhaustFan_1 48 // pin that on/off exhaust fan 1
#define exhaustFan_2 49

#include "DHT.h"
#define DHTTYPE DHT22 
DHT dht_mux1(31 , DHTTYPE);
DHT dht_mux2(30 , DHTTYPE);
DHT dht_mux3(41 , DHTTYPE);
DHT dht_mux4(40 , DHTTYPE);
DHT dht_mux5(47 , DHTTYPE);
DHT dht_mux6(14, DHTTYPE);
DHT dht_mux7(5 , DHTTYPE);

int SIG1 = 31; 
int S1[4] = {23,25,27,29};

int SIG2 = 30; 
int S2[4] = {22,24,26,28};

int SIG3 = 41; 
int S3[4] = {33,35,37,39};

int SIG4 = 40; 
int S4[4] = {32,34,36,38};

int SIG5 = 47; 
int S5[4] = {42,43,44,45};

int SIG6 = 14; 
int S6[4] = {18,17,16,15};

int SIG7 = 5; 
int S7[4] = {1,2,3,4};

//TRUTHTABLE S0,S1,S2,S3
int MUXtable[16][4]=
{
  {0,0,0,0}, {1,0,0,0}, {0,1,0,0}, {1,1,0,0},
  {0,0,1,0}, {1,0,1,0}, {0,1,1,0}, {1,1,1,0},
  {0,0,0,1}, {1,0,0,1}, {0,1,0,1}, {1,1,0,1},
  {0,0,1,1}, {1,0,1,1}, {0,1,1,1}, {1,1,1,1}
};



void setup() { //setuploop
  Serial.begin(9600);
  
  pinMode(pinCS, OUTPUT);
  lcd.begin(16,2);
  lcd.backlight();

  if (! rtc.begin()) {
    while (1);
  }
  if (rtc.lostPower()) {
    lcd.print("RTC lost power:");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    delay(300);
  }
  
  lcd.clear();
  if (SD.begin())
  {
    Serial.println("SD is Ready");
    lcd.print("SD is Ready");
  } else
  {
    lcd.print("SD Failed");
    return;
  }
  delay(1000);
  lcd.setCursor(0,0);
  DateTime now = rtc.now();
 
  sprintf(fileName, "%d%d%02d.txt", now.year(), now.month(), now.day());
  Serial.println(fileName);
  File myFile;
  myFile = SD.open(fileName, FILE_WRITE);
  
  if (myFile) {
    // Write to file
    myFile.println("TIME,TRAY,POSITION,TEMPERATURE,AIR FLOW");
    myFile.close(); // close the file
    lcd.setCursor(0,1);
    lcd.print("Header written!");
  }
  // if the file didn't open, print an error:
  else {
    lcd.setCursor(0,1);
    lcd.print("cannot open");
  }
  
  pinMode(button1Pin, INPUT);
  pinMode(redled_button1, OUTPUT);
  
  pinMode(exhaustFan_1, OUTPUT);
  pinMode(exhaustFan_2, OUTPUT);
  digitalWrite(exhaustFan_1, LOW);
  digitalWrite(exhaustFan_2, LOW);

  pinMode(SIG1,INPUT);
  pinMode(SIG2,INPUT);
  pinMode(SIG3,INPUT);
  pinMode(SIG4,INPUT);
  pinMode(SIG5,INPUT);
  pinMode(SIG6,INPUT);
  pinMode(SIG7,INPUT);
  for(int i=0; i<4; i++) 
 {
  pinMode(S1[i],OUTPUT);
  pinMode(S2[i],OUTPUT);
  pinMode(S3[i],OUTPUT);
  pinMode(S4[i],OUTPUT);
  pinMode(S5[i],OUTPUT);
  pinMode(S6[i],OUTPUT);
  pinMode(S7[i],OUTPUT);
 }

  Serial.begin(9600);
  dht_mux1.begin();
  dht_mux2.begin();
  dht_mux3.begin();
  dht_mux4.begin();
  dht_mux5.begin();
  dht_mux6.begin();
  dht_mux7.begin();
  
  delay(1000);

}

//inmainloop
void loop() {
  int mode = 1; //state airflow route
  
  lcd_showroute(mode);
  switch_exhaustfan(mode);

  record_sensor(mode);
  
  while(1) {
    
    lcd_showroute(mode);
    DateTime now = rtc.now();
    lcd.setCursor(0,1);
    lcd.print("while-min ");
    lcd.print(now.minute());
    
    Serial.print("while-min ");
    Serial.println(now.minute());
    if(now.minute() == 0 || now.minute() == 30 || now.minute() == 20)
    {
      record_sensor(mode);
      lcd.setCursor(0,1);
      lcd.print("DONE!!");
    }
    delay(2000);
  }
}

void switch_exhaustfan(int m)
{
  if(m == 1){
    digitalWrite(exhaustFan_1, HIGH); 
    digitalWrite(exhaustFan_2, LOW); 
    lcd.setCursor(0,1);
    lcd.print("Top Exhaust ON");
  }
  else if(m == 2){
    digitalWrite(exhaustFan_1, LOW); 
    digitalWrite(exhaustFan_2, HIGH); 
    lcd.setCursor(0,1);
    lcd.print("Bottom Exhaust ON");
  }
  delay(500);
}

void lcd_showroute(int m){
  char displaytime[10];
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Mode");
  lcd.setCursor(5,0);
  lcd.print(m);
  lcd.setCursor(7,0);
  DateTime now = rtc.now();
  sprintf(displaytime, "%d:%02d", now.hour(), now.minute()); //convert time object to string
  lcd.print("<");
  lcd.print(displaytime);
  lcd.print(">");

  Serial.print("Mode ");
  Serial.print(m);
  Serial.print(" <");
  Serial.print(displaytime);
  Serial.println(">");
}

void record_sensor(int m){
  digitalWrite(redled_button1, HIGH);
  
  for(int i=0; i<16; i++)
  {
    channel_selection(i);
    read_sensor(i+1, m);
    delay(1000);
  }
  digitalWrite(redled_button1, LOW);
  delay(500);
}


void channel_selection(int j)
{
  digitalWrite(S1[0], MUXtable[j][0]);
  digitalWrite(S1[1], MUXtable[j][1]);
  digitalWrite(S1[2], MUXtable[j][2]);
  digitalWrite(S1[3], MUXtable[j][3]);

  digitalWrite(S2[0], MUXtable[j][0]);
  digitalWrite(S2[1], MUXtable[j][1]);
  digitalWrite(S2[2], MUXtable[j][2]);
  digitalWrite(S2[3], MUXtable[j][3]);

  digitalWrite(S3[0], MUXtable[j][0]);
  digitalWrite(S3[1], MUXtable[j][1]);
  digitalWrite(S3[2], MUXtable[j][2]);
  digitalWrite(S3[3], MUXtable[j][3]);

  digitalWrite(S4[0], MUXtable[j][0]);
  digitalWrite(S4[1], MUXtable[j][1]);
  digitalWrite(S4[2], MUXtable[j][2]);
  digitalWrite(S4[3], MUXtable[j][3]);

  digitalWrite(S5[0], MUXtable[j][0]);
  digitalWrite(S5[1], MUXtable[j][1]);
  digitalWrite(S5[2], MUXtable[j][2]);
  digitalWrite(S5[3], MUXtable[j][3]);

  digitalWrite(S6[0], MUXtable[j][0]);
  digitalWrite(S6[1], MUXtable[j][1]);
  digitalWrite(S6[2], MUXtable[j][2]);
  digitalWrite(S6[3], MUXtable[j][3]);

  digitalWrite(S7[0], MUXtable[j][0]);
  digitalWrite(S7[1], MUXtable[j][1]);
  digitalWrite(S7[2], MUXtable[j][2]);
  digitalWrite(S7[3], MUXtable[j][3]);
}

void read_sensor(int k, int m)
{
  float h[6];
  float t[6]; 
  DateTime now = rtc.now();
  File newFile;
  newFile = SD.open(fileName, FILE_WRITE);
  
  char timenow[10], write_line[40], temp[5];
  float temporary[6];
  
  h[0] = dht_mux1.readHumidity();
  t[0] = dht_mux1.readTemperature();
  
  h[1] = dht_mux2.readHumidity();
  t[1] = dht_mux2.readTemperature();
  
  h[2] = dht_mux3.readHumidity();
  t[2] = dht_mux3.readTemperature();
  
  h[3] = dht_mux4.readHumidity();
  t[3] = dht_mux4.readTemperature();
  
  h[4] = dht_mux5.readHumidity();
  t[4] = dht_mux5.readTemperature();
  
  h[5] = dht_mux6.readHumidity();
  t[5] = dht_mux6.readTemperature();

  for(int i=0; i<6; i++)
  {
    lcd.setCursor(0,1);
    lcd.print("                     ");
    lcd.setCursor(0,1);
    lcd.print("(");
    lcd.print(k);
    lcd.print(")");
    lcd.setCursor(4,1);
    lcd.print("T");
    //lcd.setCursor(1,1);
    lcd.print(i+1);
    //lcd.setCursor(2,1);
    lcd.print("CH");
    //lcd.setCursor(5,1);
    lcd.print(k);
    
    if(!isnan(t[i]))
    {
      lcd.setCursor(11,1);
      lcd.print("OK!");
    }
    else
    {
      lcd.setCursor(11,1);
      lcd.print("FAIL!");
    }
    delay(500);
  }
  
  delay(1000);
  
  if (newFile) { 
    sprintf(timenow, "%d:%02d:%02d", now.hour(), now.minute(), now.second()); //convert time object to strin

    for(int i=0; i<6; i++)
    {
      
      //dtostrf(t[i], 3, 2, temp); //convert temperature float object to string
  
      //sprintf(write_line, "%s,%d,%02d,%.2f,%d", timenow, i+1, k, t[i], m); 
      //newFile.println(write_line);
      
      newFile.print(timenow);
      newFile.print(",");
      newFile.print(i+1);
      newFile.print(",");
      newFile.print(k);
      newFile.print(",");
      newFile.print(t[i]);
      newFile.print(",");
      newFile.println(m);

      Serial.print(timenow);
      Serial.print(",");
      Serial.print(i+1);
      Serial.print(",");
      Serial.print(k);
      Serial.print(",");
      Serial.print(t[i]);
      Serial.print(",");
      Serial.println(m);
      
    }
    newFile.close(); // close the file
    lcd.setCursor(0,1);
    lcd.print("Data is now saved.");
    Serial.println("Data is now saved.");
  }
  else {
    lcd.setCursor(0,1);
    lcd.print("Error opening file");
    Serial.println("Error opening file");
  }
}
  
  
type or paste code here

Post your code according to the in the stickies at the top of the forums.
No one here is likely to download a code file.

updated.

First - your code can't possibly compile- look at the last line.
Second - verbose use of comments might help anyone without your thought process understand what you are trying to do.
Third - what is while(1) doing in loop()? I don't see any way out of the while{} loop.

Do you not understand loop()?

You have blocking code inside of loop(). A while statement is blocking code and the housekeeping instructions performed in the background with each iteration of loop() don't happen. This can make a very unstable program.

Also you never close the file. Removing the power without closing the file is going to corrupt the SD card. You might even have to get it reformatted.

Actually, I close the file every time it opens, inside the if statement.

That pretty clearly indicates noise problems in the power supply. Your 12V to 5V converter may not be working well. Try adding a 1000 uF cap across the 5V input to the Arduino.

Actually, I close the file every time it opens, inside the if statement.

This is a mistake too. Opening the file, writing one record and closing it again vastly increases the time to do I/O, the current draw and the SD card error rate.

Close the file when you are done collecting data. Issuing a flush() command from time to time helps keep the system up to date.

First - your code can't possibly compile- look at the last line.

The file compiles just fine. The last line is not from my file, will delete it.

Third - what is while(1) doing in loop()? I don't see any way out of the while{} loop.

Well, my intention was that the Arduino collects and saves data at every 30 minutes interval but at the same time, I want the Arduino to collect the data every time it starts up.
I understand loop() but for what I was trying to achieve this was what I could do best at the time. I didn't know this could make it a very unstable program. I guess there's another way to do it.

Thank you for your input.

Thank you for the information! This is all new to me, will keep it in mind when trying to fix it later.

Also, if you have any idea as to why no problem occurs in opening and closing the file when I connect the Arduino to my laptop directly instead of from the 12-5v buck converter?

Power supply noise, explained in post #8. Apply 5V to the Arduino 5V pin, not Vin.

1 Like

Is that in the read_sensor function? The one that gets called only once at the start of the loop function and never ever again because after that you enter the endless while loop?

Yes. The file is open in the read_sensor function and the file is also closed in the same function in the if statement when the file is successfully open.

Thank you for your input!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.