🛠 Journaliser un capteur dans LittleFS
Objectives
Store measurements on the ESP32's internal 4 MB flash without an SD card, using the LittleFS file system (the official successor to SPIFFS, which is now deprecated). You will learn how to format, create a folder tree, open a file in append mode, and write a CSV log.
Hardware
- 1 ESP32 DevKit v1 board (4 MB flash, default partition scheme)
- The sensor is simulated by software in this example (can be replaced by a real SHT31)
Complete code
#include <LittleFS.h>
void ecrireLigne(const String& ligne) {
File f = LittleFS.open("/logs/capteur.csv", "a");
if (!f) { Serial.println(F("Ouverture en echec")); return; }
f.println(ligne);
f.close;
}
void setup {
Serial.begin(115200);
if (!LittleFS.begin(true)) { // true = formater si la partition est vide
Serial.println(F("Formatage LittleFS..."));
LittleFS.begin(true);
}
if (!LittleFS.exists("/logs")) LittleFS.mkdir("/logs");
}
void loop {
float t = 20.0f + 5.0f * sin(millis / 30000.0f); // capteur simule
ecrireLigne(String(millis / 1000) + "," + String(t, 2));
File f = LittleFS.open("/logs/capteur.csv", "r");
String derniere = f.readStringUntil('\n');
f.close;
Serial.printf("Derniere ligne du CSV : %s\n", derniere.c_str);
delay(5000);
}
Expected verification
The console displays the first line of the CSV while the file grows in append mode; after several minutes, /logs/capteur.csv contains a "seconds,temperature" line every 5 seconds. The content survives a power cut.
Common errors
- Forgetting the true parameter in LittleFS.begin(true) on a never-formatted flash: begin fails and open returns an invalid file.
- Writing every 10 ms: flash supports a limited number of cycles, group measurements (one packet per minute, for example).
- Data partition too small due to an OTA partition scheme: adjust the Partition Scheme in the Tools menu.
- Reusing SPIFFS code without changing anything: the APIs look similar, but SPIFFS is deprecated and fragments much more.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht22.inoArduinooled-i2c.inoArduinoserveur-web.inoArduino