Not able to open file in SD Card to log data with Datalogger Sheild V1.0

Hello everyone,

I'm trying to read and log data from a linear displacement and DHT11 sensor on an LCD and SD Card while using a button to start/stop the reading and loadig.

Here is the code i'm using :

#include <ezButton.h>
#include <RTClib.h>
#include <DHT.h>
#include <DHT_U.h>
#include <Adafruit_ADS1X15.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <SPI.h> 
#include <SD.h>  

#define DHTPIN 3  // Digital pin connected to the DHT sensor dht DHT11; //Sensor object named as DHT
#define DHTTYPE DHT11   // DHT 11


#define LOOP_STATE_STOPPED 0
#define LOOP_STATE_STARTED 1
ezButton button(2);  // create ezButton object that attach to pin 2;

DHT dht(DHTPIN, DHTTYPE);

LiquidCrystal_I2C lcd(0x27, 16, 2);

Adafruit_ADS1115 ads;

RTC_DS1307 RTC;

char daysoftheweek [7][12] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};

int loopState = LOOP_STATE_STOPPED; //button state
int samplingfreq; //sampling frequency [milliseconds]
int sensorValue = 0; //for the raw data
float distance = 0; //for the calibrated distance
float h; // Humidity
float t;//  Temperature as Celsius (the default)

const char* filename = "Displacements.txt";

File dataFile;
DateTime now;

   // the setup routine runs once when you press reset:

void setup() {

   // initialize serial communication at 115200 bits per second:  
  Serial.begin(115200);

     
   // some info to know what is on the Arduino
  Serial.println("KTR-100mm Displacement sensor, DHT11, LCD, Buttons.");
  Serial.print("\n"); //linebreak
  Serial.println("--------------------------------------------------");

   //-----------------Taking care of LCD-------------------
   //NOTE: if you cannot see the text on the LCD, try to change the potmeter on the back of it.
   //Sometimes you just have wrong contrast settings and nothing shows up on the screen because of it.
  lcd.begin(16,2);                      // initialize the lcd
  lcd.backlight(); //initialize backlight
   //------------------------------------------------------
  lcd.clear(); //clear the LCD
  lcd.setCursor(0, 0); //Defining positon to write from first row,first column .
  lcd.print("KTR-100mm"); //some message
  lcd.setCursor(0, 1); //Cursor is moved to the 2nd line of the LCD
  lcd.print("Reading displ."); //You can write 16 Characters per line .
  delay(3000); //wait 3 sec
  
   //  seting pinMode for pin 10 (SD Chipselect)
  pinMode(10, OUTPUT); 

      
    //----Set default------

    dht.begin();  

   // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) ) {
    Serial.println(F("Failed to read from DHT sensor!"));
    lcd.clear(); //clear the LCD
    lcd.setCursor(0, 0); //Defining positon to write from first row,first column .
    lcd.print("DHT failed"); //some message
    // don't do anything more:    
    return;}  

    RTC.begin();

   //check or the Real Time Clock is on
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    // uncomment it & upload to set the time, date and start run the RTC!
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
    
    
   // see if the card is present and can be initialized: 
  if (!SD.begin(10)) {
    Serial.println("Error : Push the reset button");
    lcd.clear(); //clear the LCD
    lcd.setCursor(0, 0); //Defining positon to write from first row,first column .
    lcd.print("SD Card failed"); //some message        
    for (;;); 
  }
  
   //----------------Initializing SD Card---------------------
      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.

 
  //write down the date (year / month / day)
    //prints only the start, so if the logger runs for sevenal days you only findt the start back at the begin.
    now = RTC.now();
    dataFile = SD.open(filename, FILE_WRITE);
    dataFile.print("Start logging on: ");
    dataFile.print(now.year(),DEC);
    dataFile.print('/');
    dataFile.print(now.month(),DEC);
    dataFile.print('/');
    dataFile.print(now.day(),DEC);
    dataFile.println(" ");
    dataFile.println("mm");
    dataFile.println(",");
    dataFile.println("Celsius");
    dataFile.println(",");
    dataFile.println("%");
    dataFile.println(",");
    dataFile.println("Time");
    
    dataFile.close();
  
  
button.setDebounceTime(50); // set debounce time to 50 milliseconds  

}


// the loop routine runs over and over again forever:

void loop() { 


 button.loop(); // MUST call the loop() function first

  if (button.isPressed()) {
    if (loopState == LOOP_STATE_STOPPED)
      loopState = LOOP_STATE_STARTED;
    else // if(loopState == LOOP_STATE_STARTED)
      loopState = LOOP_STATE_STOPPED;
  }

  if (loopState == LOOP_STATE_STARTED) {
  
       //read the time
         now = RTC.now();
   //--------------------------Reading data and sending to PC-----------------------------------------
  
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a distance (0 - 100 mm):
  distance = sensorValue * (100.0 / 1023);
  // Read Humidity
  h = dht.readHumidity(); 
  // Read temperature as Celsius (the default)
  t = dht.readTemperature();
  
  //---------------------------------Serial printout-------------------------------------------------
          
          Serial.print("\n"); //linebreak

          Serial.print("Displacement = "); //tab for separation
          Serial.print(distance, 4); //calibrated data (displacement), 4 decimals
          Serial.print(" mm");
          Serial.print("\n"); //linebreak

          Serial.print("Current humidity = ");
          Serial.print(h);
          Serial.print("%  ");
          Serial.print("\t"); //tab for separation
          Serial.print("temperature = ");
          Serial.print(t); 
          Serial.print("C  ");
          Serial.print("\n"); //linebreak

          Serial.print("--------------------------------------------------------------------");  

  //-----------------------------------------LCD Printout------------------------------------------

          lcd.clear(); //clear LCD
          lcd.setCursor(0, 0); //Defining positon to write from first row,first column .
          lcd.print("   ");          
          lcd.print(distance, 4); // calibrated data (displacement), 4 decimals
          lcd.print(" mm");
          lcd.setCursor(0, 1); //Defining positon to write from second row,first column .          
          lcd.print(t);
          lcd.print(" C  ");        
          lcd.print(h);
          lcd.print(" %");

  //-------------------------Writing on SD Card---------------------------------------------------
        // open the file. note that only one file can be open at a time,
       // so you have to close this one before opening another.

     dataFile = SD.open(filename, FILE_WRITE);

  // if the file is available, write to it:
  // log the temperature and time.
  if (dataFile.available()) {

    dataFile.print(distance);
    dataFile.print(",");

    dataFile.print(t);
    dataFile.print(",");

    dataFile.print(h);
    dataFile.print(",");
    
    dataFile.print(now.hour(),DEC);
    dataFile.print(":");
    dataFile.print(now.minute(),DEC);
    dataFile.print(":");
    dataFile.println(now.second(),DEC);
   
    dataFile.close();
    // print to the serial port too:
    Serial.print("\n"); //linebreak
    Serial.println("data stored");
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.print("\n"); //linebreak
    Serial.println("error opening Displacements.txt");
  }
        
delay(50);

  }
}

everything works perfectly exept when it comes to writing data on the sd card i get this error due to not being able to open the file :

KTR-100mm Displacement sensor, DHT11, LCD, ButKTR-100mm Displacement sensor, DHT11, LCD, Buttons.
--------------------------------------------------
Displacement = 99.5112 mm
Current humidity = 71.00% temperature = 22.60C
--------------------------------------------------------------------
error opening Displacements.txt

My sd card is formated at FAT32 but i can't find the problem, tryed a lot for the last couple of days.

any help is apreciated.

Here is the sheild i'm using
image

It's hard to follow. Could you please click Tools->Auto Format and either post it again or edit your first post and put the formatted version there?

Please post a link to the specs of the shield, not a tiny blurry thumbnail!

will do

     dataFile = SD.open(filename, FILE_WRITE);

  // if the file is available, write to it:
  // log the temperature and time.
  if (dataFile.available()) {

When opening the file in loop() I think you should not use FILE_WRITE because this will delete the existing file. Is there a FILE_APPEND or similar?
EDIT: sorry, I was wrong about that. Must have been thinking about another, similar library.

Also, in not sure using .available() is the correct thing to do when writing to a file. That is what you would use when reading a file, to see if the end of the file has been reached.

I kust updated with a formatted version of the code

here is the link to the product i used

Try:

dataFile = SD.open(filename, FILE_WRITE);

  // if the file is available, write to it:
  // log the temperature and time.
  if (dataFile) {

so i just leave it if (dataFile)?

1 Like

Formatting is still incorrect....

Yes, look at this page where it says "Returns".

I tried it, still getting same error message.

for the formatting i clicked Tools>>Auto Format and selected the code ... isn't that the way? excuse me i'm a complete noob

Yes, but you have not posted the formatted code. Your original post has not been updated.

is this correct?

#include <ezButton.h>
#include <RTClib.h>
#include <DHT.h>
#include <DHT_U.h>
#include <Adafruit_ADS1X15.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <SPI.h> 
#include <SD.h>  

#define DHTPIN 3  // Digital pin connected to the DHT sensor dht DHT11; //Sensor object named as DHT
#define DHTTYPE DHT11   // DHT 11


#define LOOP_STATE_STOPPED 0
#define LOOP_STATE_STARTED 1
ezButton button(2);  // create ezButton object that attach to pin 2;

DHT dht(DHTPIN, DHTTYPE);

LiquidCrystal_I2C lcd(0x27, 16, 2);

Adafruit_ADS1115 ads;

RTC_DS1307 RTC;

char daysoftheweek [7][12] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};

int loopState = LOOP_STATE_STOPPED; //button state
int samplingfreq; //sampling frequency [milliseconds]
int sensorValue = 0; //for the raw data
float distance = 0; //for the calibrated distance
float h; // Humidity
float t;//  Temperature as Celsius (the default)

const char* filename = "Displacements.txt";

File dataFile;
DateTime now;

   // the setup routine runs once when you press reset:

void setup() {

   // initialize serial communication at 115200 bits per second:  
  Serial.begin(115200);

     
   // some info to know what is on the Arduino
  Serial.println("KTR-100mm Displacement sensor, DHT11, LCD, Buttons.");
  Serial.print("\n"); //linebreak
  Serial.println("--------------------------------------------------");

   //-----------------Taking care of LCD-------------------
   //NOTE: if you cannot see the text on the LCD, try to change the potmeter on the back of it.
   //Sometimes you just have wrong contrast settings and nothing shows up on the screen because of it.
  lcd.begin(16,2);                      // initialize the lcd
  lcd.backlight(); //initialize backlight
   //------------------------------------------------------
  lcd.clear(); //clear the LCD
  lcd.setCursor(0, 0); //Defining positon to write from first row,first column .
  lcd.print("KTR-100mm"); //some message
  lcd.setCursor(0, 1); //Cursor is moved to the 2nd line of the LCD
  lcd.print("Reading displ."); //You can write 16 Characters per line .
  delay(3000); //wait 3 sec
  
   //  seting pinMode for pin 10 (SD Chipselect)
  pinMode(10, OUTPUT); 

      
    //----Set default------

    dht.begin();  

   // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) ) {
    Serial.println(F("Failed to read from DHT sensor!"));
    lcd.clear(); //clear the LCD
    lcd.setCursor(0, 0); //Defining positon to write from first row,first column .
    lcd.print("DHT failed"); //some message
    // don't do anything more:    
    return;}  

    RTC.begin();

   //check or the Real Time Clock is on
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    // uncomment it & upload to set the time, date and start run the RTC!
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
    
    
   // see if the card is present and can be initialized: 
  if (!SD.begin(10)) {
    Serial.println("Error : Push the reset button");
    lcd.clear(); //clear the LCD
    lcd.setCursor(0, 0); //Defining positon to write from first row,first column .
    lcd.print("SD Card failed"); //some message        
    for (;;); 
  }
  
   //----------------Initializing SD Card---------------------
      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.

 
  //write down the date (year / month / day)
    //prints only the start, so if the logger runs for sevenal days you only findt the start back at the begin.
    now = RTC.now();
    dataFile = SD.open(filename, FILE_WRITE);
    dataFile.print("Start logging on: ");
    dataFile.print(now.year(),DEC);
    dataFile.print('/');
    dataFile.print(now.month(),DEC);
    dataFile.print('/');
    dataFile.print(now.day(),DEC);
    dataFile.println(" ");
    dataFile.println("mm");
    dataFile.println(",");
    dataFile.println("Celsius");
    dataFile.println(",");
    dataFile.println("%");
    dataFile.println(",");
    dataFile.println("Time");
    
    dataFile.close();
  
  
button.setDebounceTime(50); // set debounce time to 50 milliseconds  

}


// the loop routine runs over and over again forever:

void loop() { 


 button.loop(); // MUST call the loop() function first

  if (button.isPressed()) {
    if (loopState == LOOP_STATE_STOPPED)
      loopState = LOOP_STATE_STARTED;
    else // if(loopState == LOOP_STATE_STARTED)
      loopState = LOOP_STATE_STOPPED;
  }

  if (loopState == LOOP_STATE_STARTED) {
  
       //read the time
         now = RTC.now();
   //--------------------------Reading data and sending to PC-----------------------------------------
  
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a distance (0 - 100 mm):
  distance = sensorValue * (100.0 / 1023);
  // Read Humidity
  h = dht.readHumidity(); 
  // Read temperature as Celsius (the default)
  t = dht.readTemperature();
  
  //---------------------------------Serial printout-------------------------------------------------
          
          Serial.print("\n"); //linebreak

          Serial.print("Displacement = "); //tab for separation
          Serial.print(distance, 4); //calibrated data (displacement), 4 decimals
          Serial.print(" mm");
          Serial.print("\n"); //linebreak

          Serial.print("Current humidity = ");
          Serial.print(h);
          Serial.print("%  ");
          Serial.print("\t"); //tab for separation
          Serial.print("temperature = ");
          Serial.print(t); 
          Serial.print("C  ");
          Serial.print("\n"); //linebreak

          Serial.print("--------------------------------------------------------------------");  

  //-----------------------------------------LCD Printout------------------------------------------

          lcd.clear(); //clear LCD
          lcd.setCursor(0, 0); //Defining positon to write from first row,first column .
          lcd.print("   ");          
          lcd.print(distance, 4); // calibrated data (displacement), 4 decimals
          lcd.print(" mm");
          lcd.setCursor(0, 1); //Defining positon to write from second row,first column .          
          lcd.print(t);
          lcd.print(" C  ");        
          lcd.print(h);
          lcd.print(" %");

  //-------------------------Writing on SD Card---------------------------------------------------
        // open the file. note that only one file can be open at a time,
       // so you have to close this one before opening another.

     dataFile = SD.open(filename, FILE_WRITE);

  // if the file is available, write to it:
  // log the temperature and time.
  if (dataFile) {

    dataFile.print(distance);
    dataFile.print(",");

    dataFile.print(t);
    dataFile.print(",");

    dataFile.print(h);
    dataFile.print(",");
    
    dataFile.print(now.hour(),DEC);
    dataFile.print(":");
    dataFile.print(now.minute(),DEC);
    dataFile.print(":");
    dataFile.println(now.second(),DEC);
   
    dataFile.close();
    // print to the serial port too:
    Serial.print("\n"); //linebreak
    Serial.println("data stored");
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.print("\n"); //linebreak
    Serial.println("error opening Displacements.txt");
  }
        
delay(50);

  }
}

From the SD library documentation:

The library supports FAT16 and FAT32 file systems on standard SD cards and SDHC cards. It uses short 8.3 names for files.

1 Like

Formatting is still incorrect. Look here:

  pinMode(10, OUTPUT); 

      
    //----Set default------

    dht.begin();  

These code lines should be at the same level of indentation. Auto Format should have fixed that, and all the other incorrect indentation.

@markd833 is correct, I think. The file also fails to open in setup() but there is no check for failure there, like the check in loop().

That was the problem, once i changed the name into "Disp" it worked perfectly, thank you

indeed ... for the formatting i keep doing it but nothing changes, don't know why :cry: