ESP8266 SPIFFS File System

ESP8266 - All SPIFFS or what? Or also: A separate file system on our microcontroller

Hello and welcome to my new blog. In a previous post we have briefly about the SPIFFS  spoken. Today we want to take a closer look at what SPIFFS actually is, what options it offers us and how we can use it with our all-rounder microcontroller ESP 8266. First of all, what does SPIFFS actually mean? SPIFFS stands for (S) erial (P) eripheral (I) nterface (F) lash (F) ile (S) ystem and means that our ESP can hold a simple file system in the SPI program memory, which also contains our program code . Files can be created, changed or deleted in this file system. These files can be used or changed by our program code during the runtime, as they have already been created by us. We'll come back to how this is done later. The biggest advantage, however, is that this memory area, once created, is retained with code updates! That an updated program can continue to work with the data that has been saved as a file directly with reference to the file name.

Facility

In order to be able to work with a file system, it must first be initialized with a defined size on our ESP. This size depends on the one hand on the ESP module used (maximum size) and on our configuration.

By default, the ESP-01 modules have 512 KB flash up to 1 MB flash. The ESP-12, ESP-12E and ESP-12F modules (also known as NodeMcu modules) have at least 4 MB flash up to 8 MB flash. We are now using the Arduino IDE to reserve a memory area for our file system from this entire flash:

Before we upload a sketch, we choose the size of our future file system. In the above For example, I chose a 2 MB size for my ESP8266-12. Now we can format our file system for first use with the following code. This step is mandatory for new installations or when reconfiguring the SPIFFS size:

 

#include <SPI.H>
#include <FS.H>           // Include the SPIFFS library

boolean InitalizeFileSystem() {   bool initok = false;   initok = SPIFFS.begin();   if (!(initok)) // Format SPIFS, of not formatted. - Try 1   {     Serial.println("SPIFFS file system formatted.");     SPIFFS.format();     initok = SPIFFS.begin();   }   if (!(initok)) // format SPIFS. - Try 2   {     SPIFFS.format();     initok = SPIFFS.begin();   }   if (initok) { Serial.println("SPIFFS is OK"); } else { Serial.println("SPIFFS is not OK"); }   return initok;
}

void set up() {     SPI.begin();                      // Initialize SPI communication     bool Result  = InitalizeFileSystem(); 

}

void loop() {    }

 

After compiling and uploading, our file system is ready for use. We can create, change and delete files. The files are opened with so-called "Modes", which specify the desired type of access. It says

 • W - for write (writing or creating a new file)
 • R - for read (reading a file)
 • A - for append (adding data to the end of a file)

Use:

A data pointer is used within the file, which indicates the current read / write position within a file. In order to show a practical example and at the same time use as many commands as possible for file operations, we create a file in the following example and add a new entry every 5 seconds. The next time the controller is reset, we delete the file and start again. The file content is output sequentially on the serial interface. Finally the current file size in bytes. +

 

 

#include <SPI.H>
#include <FS.H>           // Use the SPIFFS library

File myfile;                   create a SPIFFS Handling Variable

Boolean InitalizeFileSystem() 
{   Bool initok = False;   initok = SPIFFS.Begin();   If (!(initok)) Format SPIFS, of not formatted. - Try 1   {     Serial.println("Format SPIFFS");     SPIFFS.Format();     initok = SPIFFS.Begin();   }   If (!(initok)) Format SPIFS, of not formatted. - Try 2   {     SPIFFS.Format();     initok = SPIFFS.Begin();   }   If (initok) { Serial.println("SPIFFS is OK"); } else { Serial.println("SPIFFS is not OK"); }   Return initok;
}

Void Setup() 
{   Serial.Begin(9600);     Spi.Begin();                        Bool Result  = InitalizeFileSystem();    If (!(SPIFFS.Exists ("/usage_log.csv") ))  Check if file usage_log.csvschon exized.   {        Myfile = SPIFFS.Open("/usage_log.csv", "w");  Open the file usage_log.csv in the root directory to write (w - write)     If (!Myfile)        {       Serial.println("Failed to write the file");       }     Result = Myfile.println("01.01.1980 12:00:00; Log cleared or deleted");      Result = Myfile.println("01.01.1980 12:00:01; First Entry, second Line");     Myfile.Close();   } else   {    SPIFFS.Remove("/usage_log.csv");  Delete File      Serial.println("File usage_log.csv exized already ! It has been deleted.");   }
}

Void Loop() 
{   Myfile = SPIFFS.Open("/usage_log.csv", "r");  Open the file usage_log.csv in the root directory for reading (r - read)   String Content=Myfile.readStringUntil('n');   Serial.println("Method: readStringUntil:");   while (Myfile.Position()<Myfile.Size())            read file inhbalt line by line to end of file         {           Content =Myfile.readStringUntil('n');           Serial.println(Content);         }    Int Filesize = Myfile.Size();   Myfile.Close();   Serial.Print("File size in bytes:");           output the current file size in bytes   Serial.println(Filesize);                                     output the current file size in bytes   Delay (5000);   Yield();               Call internal ESP8266 functions   Myfile = SPIFFS.Open("/usage_log.csv", "a");  Open file to append data ! (a - append)   Myfile.println("01.01.1980 12:00:xx;Line added.");   Myfile.Close();
}

 

We copy the code into our DIE and upload the sketch to our ESP.
The ESP will start adding entries to the usage_log.csv internal file. We should get an output like this:

The most important commands are

SPIFFS.open("/file name", "r"); Reading a file

SPIFFS.open("/file name", "w"); Writing or re-attachment of a file

SPIFFS.open("/file name", "a"); Add data to the end of a file

A complete reference of the possible commands around SPIFFS and file handling can be found at the following link:

http://arduino.esp8266.com/Arduino/versions/2.0.0/doc/filesystem.html#file-system-object-spiffs

 

SPIFFS Plugin

The ESP Arduino IDE Plugin is an Arduino IDE plugin that uploads files from the "Data" subfolder of a sketch to an existing SPIFFS file system. To do this, the existing SPIFFS files IM ESP are deleted and replaced with the files from the "data" folder. To do this, we download the Zip file under https://github.com/esp8266/arduino-esp8266fs-plugin and unzip it anywhere. The now unpacked "esp8266fs.jar" is now placed under the following folder structure that we created before: My Files->Documents->Arduino->Tools->ESP8266FS->Tool. After a reboot, a new sub-item is created under Tools -> ESP8266 Sketch Data Upload":

Have fun experimenting & until the next post!

Esp-8266Basics software

3 comments

georg

georg

hallo,
ich habe mit interesse Ihre erklärungen zum SPIFFS system gelesen, es wäre übertrieben wenn ich behaupten würde alles verstanden zu haben…
diesen code habe ich mir nach einem beispiel hier für meine bedürfnisse angepasst, er funktioniert auch:
-———————————
//board: ESP8266 Boards /node mcu 1.0

#include
#include // Nutze die SPIFFS library
int FileSize_frequency;

String sliderValue_frequency = “4”;
String sliderValue_frequency_alt;

File myfile_frequency; // erstelle eine SPIFFS Handling Variable

void setup()
{
Serial.begin(115200);
SPI.begin();

bool Result_frequency = InitalizeFileSystem(); if (!(SPIFFS.exists (“/frequency_config.csv”) )) //Prüfe ob Datei frequency_config.csv schon exisiert. { myfile_frequency = SPIFFS.open(“/frequency_config.csv”, “w”); //Öffne die Datei frequency_config.csv im Root Verzeichnis zum schreiben (w – write) if (!myfile_frequency) { Serial.println(“Fehler beim schreiben der Datei”); } Result_frequency = myfile_frequency.println(“sliderValue_frequency”); Result_frequency = myfile_frequency.println(sliderValue_frequency); myfile_frequency.close(); } else { SPIFFS.remove(“/frequency_config.csv”); //Lösche Datei Serial.println(“Datei frequency_config.csv war schon vorhanden, sie wurde gelöscht.”); }

}

void loop()
{
myfile_frequency = SPIFFS.open(“/frequency_config.csv”, “r”); //Öffne die Datei usage_log.csv im Root Verzeichnis zum lesen (r – read)

while (myfile_frequency.position() < myfile_frequency.size()) // lese Dateiinhalt Zeile für Zeile bis um Ende der Datei { String content = myfile_frequency.readStringUntil(‘\n’); Serial.println(content); } FileSize_frequency = myfile_frequency.size(); myfile_frequency.close(); Serial.print(“Dateigroesse in Bytes:”); // gebe die aktuelle Dateigröße in Bytes aus Serial.println(FileSize_frequency); // gebe die aktuelle Dateigröße in Bytes aus delay (5000); yield(); // interne ESP8266 Funktionen aufrufen if (sliderValue_frequency != sliderValue_frequency_alt) //die config_frequency soll nur einmal bei sich änderndem “sliderValue_frequency” geändert werden { myfile_frequency = SPIFFS.open(“/frequency_config.csv”, “a”); // Öffne Datei um Daten anzuhängen ! (a – append) //myfile_frequency.println(“sliderValue_frequency”); myfile_frequency.println(sliderValue_frequency); myfile_frequency.close(); sliderValue_frequency_alt = sliderValue_frequency; }

}boolean InitalizeFileSystem()
{
bool initok = false;
initok = SPIFFS.begin();
if (!(initok)) // Format SPIFS, if not formatted. – Try 1
{
Serial.println(“Format SPIFFS”);
SPIFFS.format();
initok = SPIFFS.begin();
}
if (!(initok)) // Format SPIFS, if not formatted. – Try 2
{
SPIFFS.format();
initok = SPIFFS.begin();
}
if (initok)
{
Serial.println(“SPIFFS ist OK”);
}
else
{
Serial.println(“SPIFFS ist nicht OK”);
}
return initok;
}
-———————————————
nun muss ich zwei variable in zwei dateien ins SPIFFS schreiben: frequency und power. Die beiden sketsche funktionieren einzeln sehr gut. Der versuch, die beiden sketche in eines zu integrieren scheitern mit einer Exception 9. Ich habe alle stellen, wo es mir notwendig schien entsprechend geändert und wie gesgt – einzeln funktionieren die sketche. Könnten Sie mir bitte einen tipp geben, woran das liegen könnte? Ich würde vermuten es liegt an diesen beiden zeilen:
-—————————-
bool Result_power = InitalizeFileSystem();
bool Result_frequency = InitalizeFileSystem();
-———————————-
ich kann ein system nicht 2x initialiseren, ohne dass was durcheinander gerät, denke ich…

vielen dank
gruss georg

Andre

Andre

Hallo,
in der neusten Arduino IDE funktiniert SPIFFS nicht mehr, es wird im Moment auch nicht weiterentwickelt und soll zuküntig aus dem ESP2866 core entfernt werden. LittleFS dient als Ersatz und ich konnte es mit der neusten Arduino IDE verwenden. Unter folgendem Link findet ihr weitere Infos.
https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html

Viele Grüße,
André

Stumpfbrumme

Stumpfbrumme

Danke das war hilfreich!

Leave a comment

All comments are moderated before being published

Recommended blog posts

  1. Install ESP32 now from the board manager
  2. Lüftersteuerung Raspberry Pi
  3. Arduino IDE - Programmieren für Einsteiger - Teil 1
  4. ESP32 - das Multitalent
  5. OTA - Over the Air - ESP programming via WLAN