I would like to store data from a sensor in my esp32 using spiffs in arduino

1k Views Asked by At

I would like to know how to store data from a sensor for 24 hours in my esp32? the problem I have is that on my serial monitor the text is displayed by using spiffs but when opening the text document there is nothing. I also tried to save by using preferences but there not enugh space and i found it's better to use spiffs for long data.

the code :

//#include "SPIFFS.h"
#include <heltec.h>
#include <DHT12.h>
SSD1306Wire  aff(0x3c, SDA_OLED, SCL_OLED, RST_OLED, GEOMETRY_64_32);
DHT12 dht12;

void setup() {

  Serial.begin(115200);
  dht12.begin();
  aff.init();
  aff.flipScreenVertically();
  aff.setFont(ArialMT_Plain_10);
}

void loop() {
  float temp = dht12.readTemperature();
  float hum = dht12.readHumidity();
  Serial.println(temp);
  
  aff.clear();
  aff.drawString(0, 0, "Temp:" + (String)temp + "�C");
  aff.drawString(0, 10, "Hum:" + (String)hum + "%");
  aff.display();

   if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }

  //--------- Write to file
  File fileToWrite = SPIFFS.open("/test.txt", FILE_WRITE);

  if (!fileToWrite) {
    Serial.println("There was an error opening the file for writing");
    return;
  }

  if (fileToWrite.print("ORIGINAL LINE")) {
    Serial.println("File was written");;
  } else {
    Serial.println("File write failed");
  }

  fileToWrite.close();

  //--------- Apend content to file
  File fileToAppend = SPIFFS.open("/test.txt", FILE_APPEND);

  if (!fileToAppend) {
    Serial.println("There was an error opening the file for appending");
    return;
  }

  if (fileToAppend.println(temp)) {
    Serial.println("File content was appended");
  } else {
    Serial.println("File append failed");
  }

  fileToAppend.close();

  //---------- Read file
  File fileToRead = SPIFFS.open("/test.txt");

  if (!fileToRead) {
    Serial.println("Failed to open file for reading");
    return;
  }

  Serial.println("File Content:");

  while (fileToRead.available()) {

    Serial.write(fileToRead.read());
  }

  fileToRead.close();
  delay(3000);
}
1

There are 1 best solutions below

0
On

First of all you need a SPIFFS partition configured. Looks like you're using Arduino IDE as I don't see a #include <Arduino.h> at the time. Suggest you try using PlatformIO - as it will work with many boards.

https://community.platformio.org/t/solved-choose-1m-spiffs-partition-on-esp32/20935

There appears to be some logic errors in your code - your logic quits if opening for FILE_WRITE fails, or if FILE_APPEND files. Try opening with FILE_APPEND always - if the file isn't present, and you have a partition, the data should be written...

IIRC opening for append should succeed even if the file isn't present, so worth experimenting.