A place users can post their projects. If you have a small project and would like your own dedicated place to post and have others chat about it then this is your spot.

User avatar
By ajaybnl
#59867 Hi,
Updated the code. Now it will work good.

I was just finding some good code to write SPIFFS filesystem periodically using Temperature & Humidity Values With Time Date.

I found it nowhere, so i made mine.

Here's a completed project:

Hardware:
DS3231 Module
Esp8266 12E
DHT22

Software side:
Rtclib
Dht lib (Supports DHT11 & DHT22 & More)

The Code starts with Reading File Records and with Forced Offline Mode. Saves Values from DHT22 to SPIFFS Periodocally.

The Code FORMATS the Spiffs on First Use to make a init file (to check its properly formatted).
You can use simple made function to read/write / format the spiffs.

Please feel free to use it. :D

See it:
Image






Code: Select all
/*
Github: http://github.com/ajaybnl
More Source Code on Github
*/
#include <stdio.h>
#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <FS.h>
#include "DHT.h"
#include "RTClib.h"

RTC_DS3231 rtc;

#define DHTPIN D3

#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);


long lastReadingTime = 0;
char results[4];
int fail = 0;
int x1 = 0;
unsigned long timer1 = 0;
int offline = 0;
String sdata;
unsigned long timer2 = 0;
int pdate = 0;


//#####################################################

void setup() {
 
  Serial.begin(115200);

  Serial.println("init...");
 
Serial.println("Spiffs Read: ")
//Read all data of file
  sdata="";
  spiff("data.txt", 1, "");
  Serial.println(sdata);
Serial.println("---------");

  //DHT init
  dht.begin();




  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
  }

  // if (rtc.lostPower()) {
  //   Serial.println("RTC lost power, lets set the time!");
  // following line sets the RTC to the date & time this sketch was compiled
  // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // This line sets the RTC with an explicit date & time, for example to set
  // January 21, 2014 at 3am you would call:
  // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  // }

  DateTime now = rtc.now();

  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(" (");
  Serial.print(now.dayOfTheWeek());
  Serial.print(") ");
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();


}







//#####################################################





void loop() {

//5 sec timer
  if (((millis() - timer2) / 1000) > 5) {

    DateTime now = rtc.now();
    String e = "\r\n";
    String date1;

    date1 = now.day();
    date1 += ":";
    date1 += now.month();
    date1 += ":";
    date1 += now.year();
    date1 += e;

    String time1;

    time1 = now.hour();
    time1 += ":";
    time1 += now.minute();

    //next start write date
    if (now.day() != pdate) {
      Serial.print("Writing Log: Date ");
      Serial.println(date1);
      pdate = now.day();

spiff("data.txt", 0, date1);

    }


    int h = dht.readHumidity();
    int t = dht.readTemperature();

    if (isnan(h) || isnan(t) ) {

      // Serial.println("Sensor Err");

    }


    if (t > 100 || h > 100){t=50;h=50; }// just for test

    String d;
      d = time1;
      d += " T:" ;
      d += t;
      d += " H:" ;
      d += h;
      d += "\r\n";

      Serial.print("Saving = ");
      Serial.print(d);

      // Write Data
      spiff("data.txt", 0, d);


    timer2 = millis();
  }

}






//#####################################################
 // Usage: spiff(FILE_NAME,0=WRITE/1=READ,STRING DATA To Write)
 
 //Write String Data: spiff("data.txt", 0, d);
 //Read String Data in "sdata" Variable spiff("data.txt", 1);
 //#####################################################
long spiff(String file, int read, String value = "") {

  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");
    return (0);
  }



  FSInfo fs_info;
  SPIFFS.info(fs_info);

  //Serial.print("Total Bytes: ");
  //  Serial.println(fs_info.totalBytes);

  // Serial.print("Used Bytes: ");
  // Serial.println(fs_info.usedBytes);

  if ((fs_info.totalBytes - fs_info.usedBytes) < 1000) {
    Serial.println("Memory Full");
    return (0);
  }

//Init the Spiff FS (check if our INIT file exists or not
  File f = SPIFFS.open("init", "r+");

  if (!f) {
    Serial.println("Formatting Spiff...");
    delay(200);
    //Format
    SPIFFS.format();

    //Make a Init File
    File f1 = SPIFFS.open("init", "w+");
    f1.println("init");
    f1.close();
   
    Serial.println("Done");
    delay(200);
  }
//######################################################

//If Reading Check file
  if (read == 1) {
    if (!SPIFFS.exists(file)) {
      Serial.println("File not exists");
      return (0);
    }
  }

//If Reading Open file R or A
  if (read == 1) {
    f = SPIFFS.open(file,  "r+");
  } else {
    f = SPIFFS.open(file,  "a");
  }

  int s = 0;
//if File Exists
  if (f) {
    s = f.size();

    // Serial.printf("File Opened , Size=%d\r\n", s);
//Read
    if (read == 1) {
      sdata = f.readString();

    } else {
      //Write data to file
      f.println(value);
    }
    f.close();
    //Return the size of file
    return (s);
  } else {
    Serial.print("Unable to open file ");
    Serial.println(file);
  }
}
Last edited by ajaybnl on Sun Oct 13, 2019 1:22 pm, edited 1 time in total.
User avatar
By mikekgr
#81508 Dear @ajaybnl
I know that this thread is 3 years old but... looking to implement something in SPIFFS I came across your post + sketch.
I have some question though and if you can, give me your answers. Thanks in advance!
You have done a "spiff" function that can be used as:
Usage: spiff(FILE_NAME,READ/WRITE,STRING DATA)
your function is declared:
long spiff(String file, int read, String value)
so there is int read that doing either reading or writing in a file, correct?
A) at your code:
Code: Select all  if (read == 1) {
    if (SPIFFS.exists(file) == true) {
      Serial.println("File not exists");
      return (0);
    }
  }

you check if the file exist or not but according to my view if the file already exist in the SPIFFS you print ""File not exists" Why? Am I wrong?

B) At your function seems that you have not implemented the "write" part. I can not see where you handle read = 0 that is the writing or where the particular code for writing is? Am I wrong ?

Sorry I am not software engineer so I have these questions.

Thanks and Best Regards,
Mike Kranidis
User avatar
By anyone
#82489 Hey Mike,

A) I think you are correct about SPIFFS.exists
http://arduino.esp8266.com/Arduino/vers ... tml#exists
Returns true if a file with given path exists, false otherwise.


Looking through the code, read mode is only used at the very start of setup.
In other words you never see your data on the serial line.
My guess is that ajaybnl runs without offline mode and the values are sent his other way.


B) On write not being implemented, there are a few blocks where there's if/else.
The else is write.

This says if read == 1 open in read mode, else open in append mode (writing to the end of the file).
Code: Select all//If Reading Open file R or A
  if (read == 1) {
    f = SPIFFS.open(file,  "r+");
  } else {
    f = SPIFFS.open(file,  "a");
  }


if read == 1, read the file, else write the file.
Code: Select all//Read
    if (read == 1) {
      sdata = f.readString();

    } else {
      //Write
      f.println(value);
    }



On not having the knowledge already, we all start(ed) somewhere.