ESP8266 Web Server using SPIFFS with Arduino IDE (NodeMCU) | Random Nerd Tutorials

Filesystem Uploader Plugin

To upload files to the ESP8266 SPI Flash Filesystem (SPIFFS), we’ll use the Filesystem Uploader Plugin. Install the plugin in your Arduino IDE:

Installing Libraries

One of the easiest ways to build a web server using files from the filesystem is using the ESPAsyncWebServer library. 

3d printed enclosure

To give this project a finished look, I’ve 3D printed an enclosure for the 3.2” Nextion display.

The enclosure has enough space to fit the display, the ESP8266 and the 433MHz transmitter.

You can download the .STL file for the Nextion housing for 3.5 inch. Note that for this project, I’ve used the Nextion 3.2”, so you need to resize those files to fit the Nextion 3.2” display.

The enclosure was printed using the Creality 3D CR–10 3D Printer – you can read my full review here.

Advanced web server with data exchange with esp8266

To get more information on all types of web and communication protocols used with Node MCU, Read my eBook NodeMCU: Communication methods and protocols.

There are many ways to make HTML website on ESP8266. You can find more advance examples like this here

Example 1:Simple LED on Off Control from web page.

Example 2:Update part of web page without refresh

Example 3:Advanced Web Site design using Java Script, jQuery and real time update with graphical svg gauges all inside ESP8266

Example 4:Putting these thing in IoT based home automation

Create web page with ajax

How to create a web page in ESP and uploading it read this post ?

Make your HTML page and test it in browser. Then make it header file as shown in below code. DON’T JUST CHANGE THE EXTENSION TO .h

Creating the css file

Create the style.css file with the following content or download all project files here:

Creating the html file

Create an index.html file with the following content or download all project files here:

Creating the node-red flow

You can import the Node-RED flow provided an then make changes, if needed.

To import the Node-RED flow, go the Github repository or click the figure below to see the raw file, and copy the code provided.

Next, in the Node-RED window, at the top right corner, select the menu, and go to Import  > Clipboard.

Then, paste the code provided and click Import.

Here’s the Node-RED flow you should get:

You have four different buttons to control the four different outputs. Each button is subscribed to a specific topic in which the ESP8266 #1 pusblishes messages to change the buttons’ state on Node-RED.

Each Node-RED button publishes on a topic that the ESP8266 #1 and ESP8266 #2 are subscribed to, so that they know when to change the outputs state.

Esp8266 #1 – schematics

Wire an ESP8266 to the Nextion display and to the 433MHz transmitter by following the schematic in the following figure.

  • The Nextion display TX pin should be connected to the ESP8266 RX pin.
  • The Nextion display RX pin should be connected to the ESP8266 TX pin.
  • The 433 MHz transmitter data pin is connected to the ESP8266 GPIO 5 (D1 pin).
  • The 433 MHz transmitter VCC pin is connected to the ESP8266 3V3 pin.

Esp8266 ip address

Open the Arduino serial monitor at a baud rate of 115200.

  • If you’re using ESP8266-01, connect GPIO 0 to VCC and reset your board.
  • If you’re using ESP8266-12E, just press the RESET button.

After a few seconds, the ESP8266 IP address should appear.

Esp8266 nodemcu web server circuit

For practical demonstration purpose, we are controlling through LEDs through a web server. Connection diagram for this functionality is shown below.

We need four LEDs with suitable resistors, NodeMCU, breadboard and jumper wires. One terminal of resistors is connected to the cathode of each LED and other terminal connected to the ground pin. Anodes of the LEDs connected to D1 to D4 pins of NodeMCU respectively.

Get sensor readings

We create three functions to return the sensor readings as strings: the getTemperature(), getHumidity() and getPressure() functions.

Here’s how the getTemperature() function looks like (the other functions are similar).

String getTemperature() {
  float temperature = bme.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  //float temperature = 1.8 * bme.readTemperature()   32;
  Serial.println(temperature);
  return String(temperature);
}

If you want to display temperature in Fahrenheit degrees, you just need to uncomment the corresponding line in the getTemperature() function:

float temperature = 1.8 * bme.readTemperature()   32;

To learn more about interfacing the BME280 sensor with the ESP8266, you can read the following tutorial:

How does the project work?

The figure below illustrates how this project works in 4 steps.

Let’s imagine you want to turn Outlet #1 on.

1) When you tap the Outlet #1 ON button, the Nextion display sends information to the ESP8266 via serial communication, so that it knows this button was tapped.

2) The ESP and the Raspberry Pi communicate with each other using MQTT communication protocol.

Похожее:  2-х факторная авторизация в 1xbet и 1хставка

The Raspberry Pi has the Mosquitto broker installed, that receives all the MQTT messages and sends them to the devices subscribed to a particular topic.

When you tap the ON button on the Nextion display, the ESP publishes a “true” message on the topic office/outlet1/buttonState.

3) The Outlet #1 button on the Node-RED is subscribed to this topic, and will receive that message. When it receives that message, it changes the corresponding button state to ON. When this happens, the Node-RED publishes a message on the topic office/outlet1.

4) The ESP is subscribed to this topic, so it knows Node-RED has changed the button state to ON. The ESP8266, then,  sends a 433 MHz signal using a 433 MHz transmitter to turn Outlet #1 on.

This process works similarly to control all the other outputs.

How nodemcu ajax works ?

In ESP8266 NodeMCU we create two pages on server. First that loads as normal webpage and second webpage is behind the scene i.e. AJAX.

AJAX is Based on Internet Standards

AJAX is based on internet standards, and uses a combination of:

How the code works

Continue reading to learn how the code works, or skip to the next section.

First, include the necessary libraries:

#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <FS.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

You need to type your network credentials in the following variables:

const char* ssid = "REPLACE_WITH_YOUR_SSID"; 
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Create an instance that refers to the BME280 sensor called bme:

Adafruit_BME280 bme; // I2C

Next, create a variable that refers to GPIO 2 called ledPin, and a String variable to hold the led state: ledState.

const int ledPin = 2;
String ledState;

Create an AsynWebServer object called server that is listening on port 80.

AsyncWebServer server(80);

Html and java script, ajax basics

AJAX is about updating parts of a web page, without reloading the whole page.

Installing bme280 libraries

In this tutorial, we’ll display readings from a BME280 sensor (Guide with ESP8266). You need to install the following libraries:

You can install these libraries through the Arduino IDE Libraries Manager. Go to Sketch > Include Libraries > Manage Libraries. Then, search for the libraries’ name to install them.

Installing the espasyncwebserver library

This library is not available to download through the Arduino IDE libraries manager. So, you need to follow the next steps to install the library:

  1. Click here to download the ESPAsyncWebServer library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get ESPAsyncWebServer-master folder
  3. Rename your folder from 
  4. ESPAsyncWebServer-master to ESPAsyncWebServer

  5. Move the ESPAsyncWebServer folder to your Arduino IDE installation libraries folder

Alternatively, you can go to Sketch > Include Library > .zip Library and select the previously downloaded library.

Installing the espasynctcp

The ESPAsyncWebServer library also needs the ESPAsyncTCP library to operate properly. Follow the next steps to install the ESPAsyncTCP library:

  1. Click here to download the ESPAsyncTCP library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get ESPAsyncTCP-master folder
  3. Rename your folder from 
  4. ESPAsyncTCP-master to ESPAsyncTCP

  5. Move the ESPAsyncTCP folder to your Arduino IDE installation libraries folder
  6. Finally, re-open your Arduino IDE

Alternatively, you can go to Sketch > Include Library > .zip Library and select the previously downloaded library.

Loop() function

Our loop function is empty as we are building an asynchronous server and it uses an event-driven approach. Therefore, we do not need to call any handling function inside it.

void loop() {

}

Parts required

Here’s the hardware that you need to complete this project:

If you’re using an ESP8266-01, you need an FTDI programmer to upload code.

Prerequisites

Before proceeding with this project, make sure you check all the following prerequisites.

Processor()

The processor() function attributes a value to the placeholders we’ve created on the HTML file. It accepts as argument the placeholder and should return a String that will replace the placeholder. The processor() function should have the following structure:

String processor(const String& var){
  Serial.println(var);
  if(var == "STATE"){
    if(digitalRead(ledPin)){
      ledState = "ON";
    }
    else{
      ledState = "OFF";
    }
    Serial.print(ledState);
    return ledState;
  }
  else if (var == "TEMPERATURE"){
    return getTemperature();
  }
  else if (var == "HUMIDITY"){
    return getHumidity();
  }
  else if (var == "PRESSURE"){
    return getPressure();
  }
}

This function first checks if the placeholder is the STATE we’ve created on the HTML file.

if(var == "STATE"){

If it is, then, accordingly to the LED state, we set the ledState variable to either ON or OFF.

if(digitalRead(ledPin)){
  ledState = "ON";
}
else{
  ledState = "OFF";
}

Finally, we return the ledState variable. This replaces the STATE placeholder with the ledState string value.

return ledState;

If it finds the %TEMPERATURE% placeholder, we return the temperature by calling the getTemperature() function created previously.

else if (var == "TEMPERATURE"){
  return getTemperature();
}

The same happens for the %HUMIDITY% and %PRESSURE% placeholders by calling the corresponding functions:

else if (var == "TEMPERATURE"){
  return getTemperature();
}
else if (var == "HUMIDITY"){
  return getHumidity();
}
else if (var == "PRESSURE"){
  return getPressure();
}  

Program to connect to access point and make web server

We need these libraries to make web server.

Похожее:  Личный кабинет Клюква: вход, регистрация, возможности, официальный сайт

ESP8266WiFi.h is required for doing all WiFi related functionalities such as connection, AP, etc.

WiFiClient.h this file is required to send request to web browser

Project overview

You’ll create a physical Node-RED interface with the Nextion display to control four different outlets. Take a look at the figure below:

References:

To get more information on all types of web and communication protocols used with Node MCU, Read my eBook NodeMCU: Communication methods and protocols.

Required components

  1. ESP8266 NodeMCU development board
  2. Four 5mm LEDs
  3. Four 220ohm resistors
  4. Breadboard
  5. Connecting Wires

Setup()

In the setup(), start by initializing the Serial Monitor and setting the GPIO as an output.

Serial.begin(115200);
pinMode(ledPin, OUTPUT);

Initialize the BME280 sensor:

if (!bme.begin(0x76)) {
  Serial.println("Could not find a valid BME280 sensor, check wiring!");
  while (1);
}

Initialize SPIFFS:

if(!SPIFFS.begin()){
  Serial.println("An Error has occurred while mounting SPIFFS");
  return;
}

Wi-Fi connection

Connect to Wi-Fi and print the ESP8266 address:

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.println("Connecting to WiFi..");
}
Serial.println(WiFi.localIP());

Async Web Server

Setup() function

Inside the setup() function, we will open a serial connection at a baud rate of 115200. By using the pinMode() function, the GPIO PINs will be passed as a parameter inside the function which will be configured as output pins. We will initialize all the pins to a LOW state at the time of boot that means all the LEDs will be OFF.

Serial.begin(115200);

pinMode(5,OUTPUT);
digitalWrite(5, LOW);
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
pinMode(0, OUTPUT);
digitalWrite(0, LOW);
pinMode(2, OUTPUT);
digitalWrite(2, LOW);

Starting node-red

To start Node-RED, enter the following in the Terminal window:

[email protected]:~ $ node-red-start

To access Node-RED, open a tab in any browser on the local network and type the following:

Step 1: create a good looking web page

Open your note pad and start writing HTML code. Save as index.htm.

Test your web page

Open your web page in web browser. You can observe that at the top you see Title “My first web page”.  And Web page with Hello World… message.

To see the changes in your HTML code simply change you HTML program and press refresh in browser. It will reflect immediately. This way you can make your webpage test it, then deploy it on ESP8266. It saves your lot of time.

HTML Web Page
HTML Web Page

Tools you need

only NodeMCU, Laptop and USB cable

Upload your own html code as web page

We have learned how to create web server and its basics, now we want to upload our HTML web page. It’s very simple, just replace “hello from esp8266” with HTML code.

server.send(200, "text/plain", "hello from esp8266!");

First we take webpage code in separate header file name it as “index.h”, our web page is now a array of characters stored in variable MAIN_page. Do not use comments in this file. It is HTML data as a character array not a program. Now HTML code is in a header file .h not .html file.

What is ajax?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

What you will learn?

  1. ESP8266 Ajax web page update without refresh.
  2. Sending data to ESP NodeMCU without page refresh.
  3. Getting data from ESP8266 NodeMCU without page refresh and update it in web page dynamically. such as ADC values or temperature readings.

Подключение модуля esp8266 к плате stm32f103c8: схема и программа

//Interfacing ESP8266 Wi-Fi with STM32F103C8

//CIRCUIT DIGEST

//NOTE: Serial is serial monitor with baud rate(9600)

//NOTE: Serial2 (TX2, RX2)is connected with ESP8266(RX,TX)respectively with baud rate (9600)

Stringwebpage=“”;                                   //переменная типа String для хранения символов

inti=,k=,x=;                                         // переменные целого типа

StringreadString;                                   // переменная для считывания символов                      

booleanNo_IP=false;                                 //логическая переменная

StringIP=“”;                                         //строковая переменная для хранения данных

chartemp1=‘0’;                                      // переменная символьного типа

Stringname=“<p>Circuit Digest</p><p>A community of electrical and electronics students, engineers and makers</p>”;   //String with html notations

Stringdata=“<p>Data Received Successfully…..</p>”;     //String with html

voidcheck4IP(intt1)                                     // функция для проверки ip адреса ESP8266

{

  intt2=millis();

  while(t2 t1>millis())

  {

    while(Serial2.available()>)

    {

      if(Serial2.find(“WIFI GOT IP”))

      {

        No_IP=true;

      }

    }

  }

}

voidget_ip()                                           // функция для получения IP адреса

{

  IP=“”;

  charch=;

Похожее:  Личный кабинет всероссийский Банк развития регионов (ВББР): вход, регистрация, возможности, официальный сайт

  while(1)

  {

    Serial2.println(“AT CIFSR”);                   //GET IP AT COMMAND

    while(Serial2.available()>)        

    {

      if(Serial2.find(“STAIP,”))                   //This finds the STAIP that is the STATIC IP ADDRESS of ESP8266

      {

        delay(1000);

        Serial.print(“IP Address:”);

        while(Serial2.available()>)

        {

          ch=Serial2.read();                      //Serial2 reads from ESP8266 (чтение с последовательного порта from ESP8266)

          if(ch==‘ ‘)

          break;

          IP =ch;

        }

      }

      if(ch==‘ ‘)

      break;

    }

    if(ch==‘ ‘)

    break;

    delay(1000);

  }

  Serial.print(IP);                                // выводим IP адрес в окно монитора последовательной связи

  Serial.print(“Port:”);

  Serial.println(80);

}

voidconnect_wifi(Stringcmd,intt)                  // функция для подключения ESP8266 к сети wifi с помощью AT команд

{

  inttemp=,i=;

  while(1)

  {

    Serial.println(cmd);                  //Sends to serial monitor

    Serial2.println(cmd);                 //sends to ESP8266 via serial communication

    while(Serial2.available())

    {

      if(Serial2.find(“OK”))

      i=8;

    }

    delay(t);

    if(i>5)

    break;

    i ;

  }

  if(i==8)

  Serial.println(“OK”);

  else

  Serial.println(“Error”);

}

voidwifi_init()                                //This function contains AT commands that passes to connect_wifi()

{

      connect_wifi(“AT”,100);                   //Sends AT command with time(Command for Achknowledgement) (команда подтверждения)

      connect_wifi(“AT CWMODE=3”,100);          //Sends AT command with time (For setting mode of Wifi) (команда для установки режима Wifi)

      connect_wifi(“AT CWQAP”,100);            //Sends AT command with time (for Quit AP)

      connect_wifi(“AT RST”,5000);             //Sends AT command with time (For RESETTING WIFI) (команда для сброса настроек Wifi)

      check4IP(5000);

      if(!No_IP)

      {

        Serial.println(“Connecting Wifi….”);

        connect_wifi(“AT CWJAP=”Pramo”,”pokemon08″”,7000);         //provide your WiFi username and password here (используйте в этой команде имя пользователя и пароль для своей WiFi сети)

      }

      else

        {

        }

      Serial.println(“Wifi Connected”);

      get_ip();

      connect_wifi(“AT CIPMUX=1”,100);                          //Sends AT command with time (For creating multiple connections) (команда для создания нескольких соединений)

      connect_wifi(“AT CIPSERVER=1,80”,100);                    //Sends AT command with time (For setting up server with port 80) (команда для установки номера порта 80)

}

voidsendwebdata(StringwebPage)       // функция для передачи данных веб-страницы на локальный сервер

{

    intii=;

     while(1)

     {

      unsignedintl=webPage.length();

      Serial.print(“AT CIPSEND=0,”);

      Serial2.print(“AT CIPSEND=0,”);

      Serial.println(l 2);

      Serial2.println(l 2);

      delay(100);

      Serial.println(webPage);                        // передаем данные веб-страницы в окно монитора последовательной связи

      Serial2.println(webPage);                       //передаем данные веб-страницы на  ESP8266

      while(Serial2.available())

      {

        if(Serial2.find(“OK”))

        {

          ii=11;

          break;

        }

      }

      if(ii==11)

      break;

      delay(100);

     }

}

voidsetup()

{

   Serial.begin(9600);                //begins serial monitor with baud rate 9600 (для целей отладки)

   Serial2.begin(9600);               //begins serial communication with esp8266 with baud rate 9600 (Change according to your esp8266 module) (для связи с модулем esp8266)

   wifi_init();

   Serial.println(“System Ready..”);

}

voidloop()

{

  k=;

  Serial.println(“Please Refresh your Page”);

  while(k<1000)

  {

    k ;

   while(Serial2.available())

   {

    if(Serial2.find(“0,CONNECT”))

    {

      Serial.println(“Start Printing”);

      Send();

      Serial.println(“Done Printing”);

      delay(1000);

    }

  }

  delay(1);

}

}

voidSend()              // функция, содержащая данные для передачи на локальный сервер

{

      webpage=“<h1>Welcome to Circuit Digest</h1><body bgcolor=f0f0f0>”;

      sendwebdata(webpage);

      webpage=name;

      sendwebdata(webpage);

      delay(1000);

      webpage=“<a href=”http://circuitdigest.com/””;

      webpage =“”>Click Here to get into circuitdigest.com</a>”;

      webpage =data;

      sendwebdata(webpage);

      Serial2.println(“AT CIPCLOSE=0”);                  // закрываем соединение сервера

}

Initiating connection

To start the server, we will call the begin() on our server object.

server.begin();

Results

To see the result first get the IP address from serial monitor, Open serial monitor and press reset. It sends IP and shows its connection status, if it is not able to connect it will show “……..” dots in serial monitor. Check you ssid and password.

//SSID and Password of your WiFi router
const char* ssid = "your_ssid";
const char* password = "password";

Once connected it will show following

Connection IP Assigned
Connection IP Assigned

Open web browser and enter this IP (192.168.2.2), to use domain name read this post, Make sure that your laptop or phone must be connected to the same network. You can see this web page which is we have created in all the devices which are connected to the WiFi router, where the ESP8266 is connected.

HTML Web Page
HTML Web Page

In next post we will see how to make ESP8266 Web Server and Access point.

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 4,00 из 5)
Загрузка...

Добавить комментарий

Ваш адрес email не будет опубликован.

Adblock
detector