🛠 Stocker des journaux dans la flash avec LittleFS

ESP32-S2 · intermediaire · Schéma : IMG-esp32-s2-intermediaire-3-esp32-s2-littlefs-logs.svg — ESP32-S2 dont la puce de flash embarquée est mise en évidence avec une icône de fichier journal, un capteur analogique sur GPIO3 et le câble USB vers la console série.

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials