If you know how to use itbase of fireWhen it comes to retrieving and updating data in real-time databases, it is a well-known annoying problem that data is destroyed in the process.NodeMCUIt will reboot So here we are going to learn how to fix it with the help ofLittleFS.This problem also exists in Arduino, but to solve it in Arduino we useEEPROM🇧🇷 It is a non-volatile memory to which data is written. Non-volatile here means that data is not lost as soon as the power supply is interrupted. Therefore, the data is permanently recorded and is not changed unless the user chooses to do so. This data can be electrically erased and overwritten, hence the name "Electrically Erasable Programmable Read Only Memory". For EEPROM (or E2PROM), think of it as a computer hard drive or see previousEEPROM projects and articles.
but plates likeNodeMCUThey have flash memory, which is more advanced than EEPROMs. In EEPROM, data is stored as bytes and therefore storing large amounts of data becomes complex and thethe number of read and write operations is limited🇧🇷 In flash memory, it's like a USB stick (stick), which has many more read and write cycles than EEPROM. Also, using a file system allows us to create files and folders, and users have control to rename or delete what they create. Despitefile systemit is stored in the same flash chip as the program, when a new sketch is programmed it does not changefile systemContents. there are twofile systemsto use the flash built into the ESP8266. one andSPECIAL OFFERSand the other islittle🇧🇷 SPIFFS is currently deprecated and may be removed in future versions of the ESP core. So let's meet LittleFS. In this tutorial we are going to clarify your understanding of LittleFS and how it works. In our previous articles, we usedESP8266jbase of firemany cool projects to do likeIoT-based AC fan speed control via smartphone with NodeMCU and Google FirebasejRGB night light based on ESP8266 and Neopixel LED strips controlled by Blynk app, you can consult them if you are interested in this type of project.
Understand how data is stored in NodeMCU flash memory (Write to LittleFS)
In this section, we will discuss the process of reading and writing data to a small FS file system. This will give you a basic idea of how the overall system works.
Write data to NodeMCU flash memory (write data to LittleFS):
Writing data to the LittleFS file system is very simple. To write data to the LittleFS file system, we have our very simple code, which we'll talk about later. The code is written in such a way that the user can write the data to the serial monitor so that the data can be easily saved. After writing the data we want, we must press 'log in(Make sure baud rate = 115200 and no end of line is selected.) Anything written is considered data and storedLittleFS file system🇧🇷 The LittleFS filesystem is mounted on the ESP8266's flash memory. In addition to writing data to the LittleFS file system, it can also be used to read and delete data. It does this by writing code to take input from the user and perform the function requested by the user. If the user types "D", the file will be deleted. (NOTE: case sensitive. Any errors like “DD” or “dD” instead of “D” will be considered as input data and will overwrite the existing data.) To read the data, we need to press “R”, to read the file. (NOTE: Case sensitive. Any errors like "RR" or "rR" instead of "R" will be considered input data and will overwrite existing data.)
Reading data from NodeMCU flash memory (LittleFS read):
If you try to read the data without writing anything first, the LCD will display an error message saying "No data saved". Reading data from NodeMCU flash memory is not complex at all. This one "read data ()” to read the data and “lcd.write (arquivo.read());The ” function is used to print the data on the LCD screen. We will discuss all the main features in the item code section.
Delete NodeMCU flash memory data (Delete from LittleFS):
To remove data from LittleFS, a simple function called "LittleFS.remove();" Used. This function deletes the contents of the archive, the path of which must be specified by the user. We will talk about this later in the article.
Components needed to build the LittleFS test circuit with ESP8266
- Tela LCD 16x2
- I2C-Modul (PC8574T - 8-Bit-Remote-I/O-Expander for I2C-Bus)
- circuit board
- Jumper wires (male to female)
The 16X2 LCD display module:
Let's start with first16x2-LCD-Display-Grundlagenand displays a simple message on the LCD screen. What representsLCDThis is an inexpensive way to view text output from microcontrollers/development boards. A 16x2 LCD screen can display 16 characters on each line and has 2 of those lines. If more lines of information need to be displayed, messages on the LCD display can be scrolled.Now when it comes to displaying information more than "ON or OFF", there is a limitation with the LEDs andseven segment displaysas they can indicate ON or OFF status or alphanumeric characters. This limitation is easily circumvented by using LCDs, but they occupy most of the microcontroller or NodeMCU pins. To avoid this we use an I2C module; Using an I2C module, the LCD interface can be achieved with only 4 pins.
LCD screen interface with ESP8266. This is the base project and using it we can read data from LittleFS. As we can see from the pinout diagram, we need to connect 8 LCD data pins to NodeMCU, which leaves no NodeMCU pins for other applications. Then we use the I2C module as shown below.
i2c lcd driver module,attached to the back of the LCD is shown in the photo below. We created a separate article for that.Interface LCD 16X2 com ESP32 usando I2C, you can refer to it if you want to know more about it.
LittleFS test circuit with ESP8288 and I2C LCD - Scheme
The complete schematic diagram forLittleFS is based on ESP8266, I2C LCD and NodeMCUThe test circuit is shown below.
First connect the I2C module to the LCD. Solder the female header pins to the LCD and connect the I2C module so that all four I2C pins (GND, VCC, SDA, SCL) are pointing. Now,to power the circuit, connect the I2C module's GND pin to the ESP8266's GND, and connect the I2C module's VCC to the ESP8266's Vin pin. (These two pins supply power to the LCD.) Connect the I2C module's SDA to the ESP8266's D2 pin and connect the I2C module's SCL to the ESP8266's D1 pin.
Arduino code to test LCD and write data to LittleFS on ESP8266
The complete Arduino code for reading and writing data to the LittleFS database is shown below, but before we start our code, we need to include all the necessary libraries in the Arduino IDE. Since we are using an I2C LCD and LittleFS, we need to download and install both libraries. Download links are provided below.
Arduino-LiquidCrystal-I2C-Bibliotheko GitHub
Biblioteca LittleFSo GitHub
Now that we've downloaded the files, we need to install them.LiquidCrystal_I2C.hlibrary and theBiblioteca LittleFS.For that we must goArduino-IDE--->Sketch--->include library--->Add to. ZIP library---> and select this zip file and pressOpen.
For convenience, the code is divided into two parts, the first part of the code is for checking the operation of the I2C display only, and in the second part, we implement Little FS.
Testing LCD 16X2 I2C with Arduino:
We'll start our code by including all the necessary libraries. First we record themLiquidCrystal_I2C.hlibrary and then we need to include thisfio.hlibrary as we will be using I2C
#incluir <LiquidCrystal_I2C.h>#include <Kabel.h>
Then we declare all the necessary variables. Since we are using a 16X2 screen, let's define the height and width of the LCD screen.
int lcdColunas = 16;int lcdLinhas = 2;
The next line of code configures the LCD with the settings defined above.
LiquidCrystal_I2C lcd (0x27, Säulen-LCD, Filas-LCD);
Next we have our configuration function. In the setup function, we initialize the LCD and turn on the LCD backlight.
empty structure(){lcd.init();LCD backlight();}
in the empty circuit„.setCursor“The function is used to place the cursor at the desired position. Since we received the message "Hello world!" In the first column, first line, we indicate the position„(0,0)“
loop void() {lcd.setCursor (0, 0);lcd.print("Hello Welt!");delay(1000);
The lcd.print function prints any given message. Here we show"Hello Welt!". delay(1000);' creates a delay of 1 second. This ensures that the displayed message remains long enough for us to see it properly.
lcd. Clear ();
This function clears the screen to print a new message.
lcd.setCursor (0,1);
Now, to create a little animation, let's put the cursor in the first column, the second row. After the message appears on the first line for a second, it moves to the second line.
lcd.print("Hello Welt!");delay(1000);
After reaching the second line, print the same message for viewing, and the delay will ensure that the message is also displayed on the second line for 1 second.
lcd. Clear ();
This will clear the screen so you can conveniently print messages next time. This is not required, but it is good practice to write a program this way.
This completes the first part of compiling the code and loading the code, if everything works fine you will get a hello world message on your screen. In the next part we will implement LittleFS
Write, read and erase in LittleFs with 16x2 LCD and ESP8266:
The circuit for using LittleFS to write, read and delete files from flash memory remains the same as it was previously for displaying "Hello World".
#include <LiquidCrystal_I2C.h>#include <Kabel.h>#include "SmallFS.h"
The above libraries are needed to work with LCD, I2C and LittleFS.
int lcdColunas = 16;int lcdLinhas = 2;
Here you define the number of columns and rows for the LCD. In our case 16x2, which means 16 columns and 2 rows.
LiquidCrystal_I2C lcd (0x27, Säulen-LCD, Filas-LCD);
This function is used to set the LCD address, number of columns and rows.
void LearnData();invalid recording data (string data);cancel remove data();
These are working prototypes. Use user defined function to read data in flash memory"learnData()"🇬🇧 In the same way"record data"y"delete data' are user-defined functions for reading, writing, and deleting LittleFS data.
invalid configuration() {Serial.begin (115200);lcd.init();LCD backlight();
Next we have our configuration function. In the setup function, we start the serial monitor and set the baud rate to 115200.lcd.initThe ” function initializes the LCD and the backlight function turns on the LCD backlight.
lcd.setCursor (0, 0);lcd.print("Small demo of FS");delay(1000);
As before, this places the cursor in the first column, first line and prints the message "Little FS Demo" and waits a second. The delay is used to stabilize the system.
if(!LittleFS.begin()){Serial.println("An error occurred while mounting LittleFS");
This part of the program is used because if Little FS fails to start, an error message should be displayed to inform the user that Little FS failed to start.
lcd. Clear ();lcd.print("Failed to assemble");delay(1000);give back;}LearnData();}
When LittleFS mounts and initializes correctly, we use this snippet to read the save data
loop void() {if (Serial.available()){data string = Serial.readString();Serial.println(data);
Next we have our loop function. In the loop function, we declare a "if statement"which is triggered when some data is received from the serial monitor window. The data is then read and converted into a string of "Data", and to read the string we use "serial.readString() function🇧🇷 Data printed on the screen is written to the flash memory of the nodeMCU."Series.available"The function receives user information from the serial monitor and stores it in the "Data" string. It then checks which command the user entered.
if (data =="D"){delete data();Serial.println("File deleted!");give back;}
If the user typed "D", theturn on„delete data' to delete the file and display the message 'File deleted!'. Message on the LCD screen.
if not (data == "R"){LearnData();Give back;}
Likewise, if the user typed "R", theturn onthe function "read data' to read the file from flash memory.
Serial.println("Writing data...");writeData(data);Serial.println("Finished writing data!");}}invalid read data(){File file = LittleFS.open("/SavedFile.txt", "r");
Create another function called"learnData()"🇧🇷 Create a file object and pass the file path and the letter "r" to indicate that the file will be read. To read the data, first the file must be accessed, that's why it is used. This will open the LittleFS file and the text file stored in it.
if (!file) {Serial.println("No data saved!");lcd. Clear ();lcd.print("No data saved!");give back;}
Now we need to check if the file opens. In this case, we check the file data with a "while loop" and "file.available()' because the file.read() function generates one character at a time. Therefore, use the "write.series” to print one character at a time. This one "eThe condition " checks if the file exists. Otherwise, a message that says "No data saved!” on the serial monitor and clears the LCD screen and displays the same message.
lcd. Clear ();lcd.print("Saved data:");lcd.setCursor (0,1);while(file.available()){lcd.write (arquivo.read());}lcd.setCursor (0,0);file.close();}
If the file is found, then the "clear LCD' clears the LCD screen and displays the message 'Data saved:'. To indicate that it is about to read data from flash memory and the second line, it starts displaying the message. Thus, the cursor is placed at the position of the first column, second line, and the file is read from the flash memory and written to the LCD. After displaying, the cursor position is reset and the "file.close function" closes the file.
void writeData (dados da string){//Open the fileFile file = LittleFS.open("/SavedFile.txt", "w");//Write to filefile.print(data);delay(1);// close the filefile.close();
Inside the "writeData" function, we first create a file in which you want to store the data. To do this, use "File file = LittleFS.open()" in it, enter the path where it should be saved. I just say "/SavedFile.txt". If the file already exists, the data in the file will be overwritten, or if it doesn't exist, a new file called SaveFile.txt will be created. The second parameter of this function is 'w', indicating that it writes to a file. 🇧🇷writing functionThe write function to flash memory with LittleFs is called. 🇧🇷SmallFs' is open to access the saved text file. For "file.print' is used to write the data. The one second delay is used to allow time, which helps to save the data correctly, and "file.close' is used to close the file after writing.
Serial.println("Save successful");lcd. Clear ();lcd.print("Saved data:");// put the cursor in the first column, second linelcd.setCursor (0,1);// Print the data on the LCD screenlcd.print(data);// Reset the cursor positionlcd.setCursor (0,0);}
No monitor serial "write successfullyThe message is displayed. Then the LCD will be cleared to print "save data:Then the cursor is moved to the position (0,1) to print the written data on the LCD screen. Then the cursor position is reset to (0,0).
cancel remove data(){//delete fileLittleFS.remove("/ArchivoGuardado.txt");lcd. Clear ();lcd.print("Deleted Data");}
Create another custom function called deleteData(). Here, use the snippet "LittleFS.remove("/SavedFile.txt");" where "/SavedFile.txt" is the path of the file to be deleted. 🇧🇷delete dataThe function is to delete the file. Therefore, the saved text file is accessed first and then deleted. Then a message"deleted data' is printed on the LCD screen.
LittleFS expected output:As there is no data to display for the first time, the LCD will display “No Data Saved”.
Once data has been entered via Serial Monitor, data can be read by typing "R" or deleted by typing "D" into Serial Monitor.
The figure above shows writing new data to Little Fs from Serial Monitor. The new data we enter here is "new data 123", but you can use any data you choose. It can be a combination of alphanumeric characters.
Similarly, we can read and delete data with "R" and "D". In the image above we delete the data with D and then when we try to read the data again it says: No data saved.
We also connected an LCD to the nodemcu to display the stored data, as you can see in the images above, the LCD shows the status of the data stored in the flash memory of the nodemcu.
When the NodeMCU is disconnected and reconnected, it reads from the NodeMCU's flash memory. Now disconnect the NodeMCU from the PC and reconnect it. This should directly invoke the read function and display the data stored in flash memory. As you can see, we can see the message "No data saved" on the screen.
Saving sensor input in Little Fs
Now that we understand the basics of storing and retrieving data in LittleFS, we can try to get information from the sensor and try to store it in LittleFS. Since this is an introduction to the Little Fs, let's take a look at storing data in the Sensor's Little Fs. Proper circuit connection needs to be done (connect the sensor of your choice to the NodeMCU as per the sensor requirements).
Explanation of code to get sensor info and save using Little Fs
The code is written in such a way that inputs from any basic sensor (eg DHT11 or LDR sensor) can be saved. The code doesn't change much from the previous one where we write, read and erase through the serial monitor. The code gets information from the sensor every 5 seconds and stores it through Little Fs. Data is read/displayed on the LCD screen only whenFileThe command is given through the serial monitor.
#include <LiquidCrystal_I2C.h>#include <Kabel.h>#include "SmallFS.h"
The above libraries are needed to connect LCD to NodeMCU along with I2C module and Little Fs.
int lcdColunas = 16;int lcdLinhas = 2;
These two lines determine the number of columns and rows on the LCD screen.
int Sensormesswert;
Here, use the appropriate data type like Float/Double/Long/Int/Short based on the sensor type.
unsigned long lastSensorWriteTime = 0;
This is used to track Little's access time per sensor. This snippet basically keeps checking the sensor input.
LiquidCrystal_I2C lcd (0x27, Säulen-LCD, Filas-LCD);
This is used to define the LCD address, number of columns and lines for displaying messages.
void LearnData();invalid recording data (string data);cancel remove data();
These are working prototypes. These functions are used to read, write and delete data as in the above code.
invalid configuration() {Serial.begin (115200);
Start the serial monitor and set the baud rate to 115200.
lcd.init();LCD backlight();lcd.setCursor (0, 0);lcd.print("Small demo of FS");delay(1000);
Loslcd.intThe function initializes the LCD screen.lcd back lightThe function turns on the backlight andlcd.setCursorThe function places it in the first column, first row.
if(!LittleFS.begin()){Serial.println("An error occurred while mounting LittleFS");lcd. Clear ();lcd.print("Failed to assemble");delay(1000);give back;}LearnData();}
As in the previous code, if Little Fs fails to start, the user is notified of this by printing messages on the serial monitor and LCD screen. Otherwise, data is read per callread dataOccupation.
loop void() {learnSensorValue();if (Serial.available()){data string = Serial.readString();Serial.println(data);
This takes user input to the serial monitor and stores it in a string.
if (data =="D"){delete data();Serial.println("File deleted!");give back;}if not (data == "R"){LearnData();give back;}
"D" deletes the file and "R" reads the data
Serial.println("Writing data...");writeData(data);` Serial.println("Data writing complete!");}
This writes data and prints it to the serial monitor.
if((millis() - lastSensorWriteTime) > 5000){writeData(String (sensorReading));lastSensorWriteTime = milliseconds();}}
This part of the code should write sensor data in Little Fs every five seconds..First, the condition is checked if 5 seconds have elapsed. If the condition is true, the sensor reading is stored in a string and theSensorWriteTimeit updates
invalid read data(){File file = LittleFS.open("/SavedFile.txt", "r");if (!file) {Serial.println("No data saved!");lcd. Clear ();lcd.print("No data saved!");give back;}
read dataThe function, as in the code above, opens the file and checks if it exists and prints "No data saved!" if no data is saved.
lcd. Clear ();lcd.print("Saved data:");lcd.setCursor (0,1);while(file.available()){lcd.write (arquivo.read());}lcd.setCursor (0,0);file.close();}
The cursor is placed in the first column, second row. The stored data is retrieved and displayed on the LCD screen, and then the cursor position is reset. And the file will be closed.
void writeData (dados da string){File file = LittleFS.open("/SavedFile.txt", "w");file.print(data);delay(1);file.close();
This interrupt function is used to open the file, write the recovered data to Little Fs, cause a delay of one second and close the file.
Serial.println("Save successful");lcd. Clear ();lcd.print("Saved data:");lcd.setCursor (0,1);lcd.print(data);lcd.setCursor (0,0);}
A message will be displayed to confirm that the recording was successful, the LCD screen will be cleared and the stored data will be retrieved and displayed, and then the cursor position will be set to the beginning.
cancel remove data(){LittleFS.remove("/ArchivoGuardado.txt");lcd. Clear ();lcd.print("Deleted Data");}
This snippet is used to remove the data, the data will also be removedaFunction .removeand a message will appear after the LCD screen is cleared.
void lerSensorValue(){/*Read your sensor value here!*/}
Depending on the sensor used, enter the corresponding code here to read the sensor value and save it in thesensorLecturaVariable.
This concludes our LittleFS projects. If you have any questions about the project, you can leave a comment below or use ourWentfor a quick response.
FAQs
Does ESP8266 have flash memory? ›
The on-board flash chip of the ESP8266 has plenty of space for your webpages, especially if you have the 1MB, 2MB or 4MB version. SPIFFS let's you access the flash memory as if it was a normal file system like the one on your computer (but much simpler of course): you can read and write files, create folders ...
What is the use of flash memory of the NodeMCU? ›But boards like NodeMCU have a flash memory that is more advanced than EEPROMs. In EEPROM, data is stored as bytes, and hence, storing large amounts of data will be complex and the number of reads and writes is limited.
How do you use LittleFs? ›Just open the serial monitor and type the data and press 'enter' (Make sure that the Baud rate = 115200 and no line ending is selected). whatever is typed is taken as the data and it is saved to LittleFs file system. The LittleFs file system is mounted on Flash memory of ESP8266.
How many times can write EEPROM in ESP8266? ›One important thing to note is that the EEPROM has a limited size and life span. The memory cells can be read as many times as necessary but the number of write cycles is limited to 100,000.
Does ESP8266 have EEPROM? ›EEPROM Emulation
As the esp8266 does not come with real EEPROM we emulate it using the built-in flash memory. Depending on the esp8266 model the amount of flash memory can vary from 512KiB to 4MiB. While for example, the esp-01 comes with 512KiB or 1MiB flash memory, the esp-12f has 4MiB built-in.