In this tutorial we are making ESP32 as both Station and Access point and web server. We have seen how to connect to WiFi Router and make web server in previous post.
What you will Learn?
- Making ESP32 as Access Point
- ESP32 as Station
- ESP32 as both Station and Access Point at the same time
- ESP32 as web server with HTML web page
- Using Java Scripts in ESP32
- Using CSS in ESP32
A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers’ HTTP clients.
To implement web server on ESP32, there are two ways to make your first web server first connect to your WiFi router or make ESP32 as access point.
Web Server Step by Step
As we know that all web servers have a HTML web page to be served.
Step 1: Creating web server on ESP32
ESP can acts as access point and it can connect to access point or both.
First we make program to connect to WiFi hot spot (Access Point)
Program to connect to Access point and Make web server
We need these libraries to make web server.
WiFi.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
WebServer.h it handles all HTTP protocols
#include <WiFi.h> #include <WiFiClient.h> #include <WebServer.h>
Define your SSID and Password of your WiFi router, where the ESP32 connects
//SSID and Password for ESP32 const char* ssid = "your_ssid"; const char* password = "password";
Web server is on port 80, you can use other ports also, default HTTP port is 80, to open web page with different port number you have to enter port number after IP address. Ex. For port number 81 you have to type 192.168.2.2:81 in browser.
ESP8266WebServer server(80); //Server on port 80
There are two ways to make web server one is to connect to WiFi hot spot or make ESP as hot spot (Access Point). In this tutorial we are making ESP as AP.
ESP as Access Point
You may find that ESP is also visible as hot spot in previous example; you can hide its AP (Access point) using this command at the beginning of setup.
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi network
In some application you may find that both AP and connection to WiFi router are useful for making configuration you use ESP8266 AP and for data sending to cloud use WiFi connectivity in that case use this command and both connections. This way you can access ESP web page with two different IP address.
WiFi.mode(WIFI_AP_STA); //Both hotspot and client are enabled
Third way is only access point, default is all AP and STA are enabled, to get only AP use this command.
WiFi.mode(WIFI_AP); //Only Access point
To start ESP as Access point you have to use this simple command
WiFi.softAP(ssid, password); //Start HOTspot removing password will disable security
To get IP address i.e. assigned to ESP32 by your WiFi router use this command
IPAddress myIP = WiFi.softAPIP(); //Get IP address
Web Server Handling
When client request a web page by entering ESP32 IP address which data to be sent is handled by subroutine and that subroutine name is defined in server.on(path,subroutine_name).
server.on("/", handleRoot); //Which routine to handle at root location
Example: If you have two pages you can define like this
Server.on(“/”,root); //192.168.2.2 (IP of ESP) this is root location
Server.on(“/page1”,First_page); //”192.168.2.2/page1” this is first page location
Server.on(“/page2”,Second_page); //”192.168.2.2/page2” this is second page location
You have three subroutines that handle client requests.
To start the server use this command
server.begin(); //Start server
In main loop we handle client request
server.handleClient(); //Handle client requests
This subroutine is called when you enter IP address in web browser and hit enter. This routine sends the test “hello from esp32” to web browser.
void handleRoot() { server.send(200, "text/plain", "hello from esp32!"); }
Complete Program for HTML web Server from esp32 as Access Point
index.h
Make separate header file for storing HTML code. keep this index.h file near to ino file
const char MAIN_page[] PROGMEM = R"=====( <!DOCTYPE html> <html> <style> body { text-align:center; font-family: helvetica; } canvas { border: 2px solid rgb(151, 149, 149); } </style> <body> ESP32 web server demo <h1>circuits4you.com</h1> <h3>Simple Snake Game</h3> <canvas id="stage" height="400" width="520"></canvas><br> use arraow keys to play </body> </html> <script> /** * Namespace */ var Game = Game || {}; var Keyboard = Keyboard || {}; var Component = Component || {}; /** * Keyboard Map */ Keyboard.Keymap = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; /** * Keyboard Events */ Keyboard.ControllerEvents = function() { // Setts var self = this; this.pressKey = null; this.keymap = Keyboard.Keymap; // Keydown Event document.onkeydown = function(event) { self.pressKey = event.which; }; // Get Key this.getKey = function() { return this.keymap[this.pressKey]; }; }; /** * Game Component Stage */ Component.Stage = function(canvas, conf) { // Sets this.keyEvent = new Keyboard.ControllerEvents(); this.width = canvas.width; this.height = canvas.height; this.length = []; this.food = {}; this.score = 0; this.direction = 'right'; this.conf = { cw : 10, size : 5, fps : 1000 }; // Merge Conf if (typeof conf == 'object') { for (var key in conf) { if (conf.hasOwnProperty(key)) { this.conf[key] = conf[key]; } } } }; /** * Game Component Snake */ Component.Snake = function(canvas, conf) { // Game Stage this.stage = new Component.Stage(canvas, conf); // Init Snake this.initSnake = function() { // Itaration in Snake Conf Size for (var i = 0; i < this.stage.conf.size; i++) { // Add Snake Cells this.stage.length.push({x: i, y:0}); } }; // Call init Snake this.initSnake(); // Init Food this.initFood = function() { // Add food on stage this.stage.food = { x: Math.round(Math.random() * (this.stage.width - this.stage.conf.cw) / this.stage.conf.cw), y: Math.round(Math.random() * (this.stage.height - this.stage.conf.cw) / this.stage.conf.cw), }; }; // Init Food this.initFood(); // Restart Stage this.restart = function() { this.stage.length = []; this.stage.food = {}; this.stage.score = 0; this.stage.direction = 'right'; this.stage.keyEvent.pressKey = null; this.initSnake(); this.initFood(); }; }; /** * Game Draw */ Game.Draw = function(context, snake) { // Draw Stage this.drawStage = function() { // Check Keypress And Set Stage direction var keyPress = snake.stage.keyEvent.getKey(); if (typeof(keyPress) != 'undefined') { snake.stage.direction = keyPress; } // Draw White Stage context.fillStyle = "white"; context.fillRect(0, 0, snake.stage.width, snake.stage.height); // Snake Position var nx = snake.stage.length[0].x; var ny = snake.stage.length[0].y; // Add position by stage direction switch (snake.stage.direction) { case 'right': nx++; break; case 'left': nx--; break; case 'up': ny--; break; case 'down': ny++; break; } // Check Collision if (this.collision(nx, ny) == true) { snake.restart(); return; } // Logic of Snake food if (nx == snake.stage.food.x && ny == snake.stage.food.y) { var tail = {x: nx, y: ny}; snake.stage.score++; snake.initFood(); } else { var tail = snake.stage.length.pop(); tail.x = nx; tail.y = ny; } snake.stage.length.unshift(tail); // Draw Snake for (var i = 0; i < snake.stage.length.length; i++) { var cell = snake.stage.length[i]; this.drawCell(cell.x, cell.y); } // Draw Food this.drawCell(snake.stage.food.x, snake.stage.food.y); // Draw Score context.fillText('Score: ' + snake.stage.score, 5, (snake.stage.height - 5)); }; // Draw Cell this.drawCell = function(x, y) { context.fillStyle = 'rgb(170, 170, 170)'; context.beginPath(); context.arc((x * snake.stage.conf.cw + 6), (y * snake.stage.conf.cw + 6), 4, 0, 2*Math.PI, false); context.fill(); }; // Check Collision with walls this.collision = function(nx, ny) { if (nx == -1 || nx == (snake.stage.width / snake.stage.conf.cw) || ny == -1 || ny == (snake.stage.height / snake.stage.conf.cw)) { return true; } return false; } }; /** * Game Snake */ Game.Snake = function(elementId, conf) { // Sets var canvas = document.getElementById(elementId); var context = canvas.getContext("2d"); var snake = new Component.Snake(canvas, conf); var gameDraw = new Game.Draw(context, snake); // Game Interval setInterval(function() {gameDraw.drawStage();}, snake.stage.conf.fps); }; /** * Window Load */ window.onload = function() { var snake = new Game.Snake('stage', {fps: 100, size: 4}); }; </script> )=====";
WebServer.ino code
/* * ESP32 Web Server Demo using Accesspoint * https://circuits4you.com * 21-11-2018 */ #include <WiFi.h> #include <WiFiClient.h> #include <WebServer.h> #include "index.h" //Web page header file WebServer server(80); //Enter your WiFi SSID and PASSWORD const char* ssid = "........."; const char* password = "........."; //=============================================================== // This routine is executed when you open its IP in browser //=============================================================== void handleRoot() { String s = MAIN_page; //Read HTML contents server.send(200, "text/html", s); //Send web page } //=============================================================== // Setup //=============================================================== void setup(void){ Serial.begin(115200); Serial.println(); Serial.println("Booting Sketch..."); //ESP32 As access point IP: 192.168.4.1 WiFi.mode(WIFI_AP); //Access Point mode WiFi.softAP("ESPWebServer", "12345678"); //Password length minimum 8 char //Comment below code if you are using Access point only //ESP32 connects to your wifi ----------------------------------- WiFi.mode(WIFI_STA); //Connectto your wifi WiFi.begin(ssid, password); Serial.println("Connecting to "); Serial.print(ssid); //Wait for WiFi to connect while(WiFi.waitForConnectResult() != WL_CONNECTED){ Serial.print("."); delay(1000); } //If connection successful show IP address in serial monitor Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); //IP address assigned to your ESP //---------------------------------------------------------------- server.on("/", handleRoot); //This is display page server.begin(); //Start server Serial.println("HTTP server started"); } //=============================================================== // This routine is executed when you open its IP in browser //=============================================================== void loop(void){ server.handleClient(); delay(1); }
Results
After uploading program take your mobile turn on WiFi and in WiFi setting Scan for hot spot you will find “ESPWebServer” hot spot connect to it with password “12345678” as we have given in program. After connecting to ESP hot spot, Open web browser in mobile phone and enter IP 192.168.4.1 you will see “HTML snake game”. IP address can be found in serial monitor.
Open web browser and enter the IP
Web Server results In next post we will see how to make ESP8266 Web Server and Load HTML Web Page.
The article was very informative and helpful.
But I do have a point of confusion.
in the index.h file you have this construct–
const char MAIN_page[] PROGMEM = R”=====(
…
)=====”;
I understand that PROGMEM forces it to program memory,
but the R”=====( … )=====” is something I’ve not seen before.
It appears to allow you to spread the string definition over several lines in the file, but how does it work?
Where is it defined?
Is it part of C++ or an Arduino SDK macro?
Thanks for the help
Leon
This =====(…. )===== syntax allows you to use double quotes and single quotes in string data,
Its like escape characters.