我想使用arduino中的spiffs在我的esp32中存储传感器的数据



我想知道如何从传感器存储数据24小时在我的esp32?我的问题是,在我的串行监视器上,文本是通过使用spiffs显示的,但当打开文本文档时,什么也没有。我也试图通过使用首选项来节省,但没有足够的空间,我发现对长数据使用spiffs更好。

代码:

//#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);
}

首先需要配置一个SPIFFS分区。看起来你正在使用Arduino IDE,因为我没有看到#include在当时。建议您尝试使用PlatformIO -因为它可以与许多板一起工作。

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

你的代码中似乎有一些逻辑错误——如果打开FILE_WRITE失败,或者FILE_APPEND文件失败,你的逻辑退出。尝试使用FILE_APPEND always打开-如果文件不存在,并且您有分区,则应该写入数据…

IIRC打开append应该成功,即使文件不存在,所以值得尝试。

最新更新