🛠 Stocker des journaux dans la flash avec LittleFS
Objectives
Use the LittleFS file system mounted in the ESP32-S2 internal flash: format the partition, create a log file in append mode, record timestamped measurements, and read them back. This technique is useful because flash performs much better with sequential writes than random writes.
Hardware
- ESP32-S2 board and USB cable
- Computer with the "ESP32 LittleFS data upload" plugin (optional for preloading files)
- Sensor or potentiometer on GPIO3 (ADC1) to generate measurements
Complete code
// Journalisation dans LittleFS sur ESP32-S2
#include <LittleFS.h>
const char *CHEMIN_LOG = "/journal.csv";
const uint8_t CAPTEUR_PIN = 3; // ADC1, reste disponible meme avec WiFi
uint32_t compteur = 0;
void setup {
Serial.begin(115200);
delay(500);
if (!LittleFS.begin(true)) { // true = formate si vierge
Serial.println("Echec montage LittleFS");
return;
}
Serial.println("LittleFS monte.");
File f = LittleFS.open(CHEMIN_LOG, "a");
if (!f) { Serial.println("Ouverture impossible"); return; }
if (f.size == 0) f.println("millis;mesure"); // en-tete
f.printf("%lu;demarrage\n", (unsigned long)millis);
f.close;
}
void loop {
compteur++;
if (compteur % 10 == 0) { // une ligne toutes les 10 s
uint16_t brut = analogRead(CAPTEUR_PIN);
File f = LittleFS.open(CHEMIN_LOG, "a");
if (f) {
f.printf("%lu;%u\n", (unsigned long)millis, brut);
f.close;
Serial.println("Ligne ecrite.");
}
}
delay(1000);
}
Expected verification
After the first boot (formatting), the console displays "LittleFS mounted." Every ten seconds, a line "millis;value" is added to the file. Restart the board using the reset button: the file is not erased, the millis timestamp restarts from zero, but previous measurements remain readable via a small reading sketch or the upload plugin.
Common errors
- Writing on every
loopwithout buffering: flash wears out; group writes (every N seconds). - Forgetting
f.close: data remains in the buffer and is lost on the next reset. LittleFS.beginwithout parameters on a blank card: mounting fails; passtrueto allow formatting.- Default partition too small: if your logs grow, choose a partition with more space for the filesystem in the IDE.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht22.inoArduinooled-i2c.inoArduinoserveur-web.inoArduino