ESP8266 - HTTP server with multiple pages in SPIFFS

Zápisník experimentátora

Hierarchy: ESP8266

In the previous example, we created an HTTP server with three pages. If you look at the source code of the server, you will find the html directory where are the source codes of HTML pages. In this directory I created the design of each page. After designing the pages, I had to copy the source code of each page into c++ source code. Such activity is laborious and inefficient. In this article, we will learn how to omit copying to c++ source code and replace it with the SPIFFS file system.

Using the SPIFFS file system requires the installation of a plugin to upload the contents of the file directory to SPIFFS. See the article I wrote on this topic for details. The HTML files from the previous example are in the data directory in this program.

Used parts

This is a simple project, so we will need some board with the ESP8266 microcontroller, which can be directly connected to USB. To avoid a possible short circuit, you can plug the board into a breadboard.

  • ESP8266 {linkESP8266}
  • Breadboard {linkBreadBoard}

Example

Using SPIFFS greatly simplified the previous program for ESP8266. We could get rid of all HTML page header files, and we could also remove any function that send individual pages to the browser. All this could be simplified into four lines. SPIFFS.begin initializes the file system and the function server.serveStatic sends the page to the browser. You don't even have to worry about setting a content-type that tells your browser what data you're sending to it. The most common file types are automatically recognized.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <FS.h>
#include "arduino_secret.h"

ESP8266WebServer server(80);

void setup(void){
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  SPIFFS.begin();

  server.serveStatic("/", SPIFFS, "/page1.html");
  server.serveStatic("/page2", SPIFFS, "/page2.html");
  server.serveStatic("/page3", SPIFFS, "/page3.html");

  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

Next time

Let's just say what we're going to do next. If you look at network communication, you will see that something has been delivered by ESP8266 to the browser, some of the content has been downloaded from the CDN server, and that the browser has tried to download favicon.ico from ESP8266. But we don't have any such file in SPIFFS. Therefore, the next time we look at creating this file, we will also handle errors on non-existing pages.

Source code

The source code is located on GitHub.


21.05.2019


Menu