A Web Server from ESP-32

Andreana Hartadi Suliman
6 min readApr 3, 2022

--

Welcome to the next step of the Embedded System tutorial! I do think that every piece of information we can acquire from ESP-32 sensors, both internal and external, should be informed in a comfortable way for users to read. Basically, nowadays many humans use smart devices. So in this article, we will transform the information from ESP-32 into a web server.

The components that you will need are :

  1. ESP-32

2. Micro USB Cable

3. Breadboard

4. BMP 280

5. Male to Male Cable

6. WI-FI Connection

7. LED

8. Resistor 330 Ohm

Follow this picture to assembly the components :

For the jumper wire, connect the positive line of LED with GPIO23 on ESP-32, VCC on BMP280 with 3v3, GND to breadboard negative line, and GND on BMP, SDA to GPIO22, SCL to GPIO21, and resistor with LED negative line.

You have to install the Adafruit BMP280 library by clicking Tools > Manage Library.

Copy and paste this code to Arduino IDE.

#include <Wire.h>
#include <WiFi.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>
#define BMP_SCK (13)
#define BMP_MISO (12)
#define BMP_MOSI (11)
#define BMP_CS (10)Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK);// Replace with your network credentials
const char* ssid = "xxxxxxxx";
const char* password = "xxxxxxxx";// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String outputState = "off";
// Assign output variables to GPIO pins
const int output = 23;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
Serial.begin(115200);
while ( !Serial ) delay(100); // wait for native usb
Serial.println(F("BMP280 test"));
unsigned status;
//status = bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID);
status = bmp.begin(0x76);
if (!status) {
Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
"try a different address!"));
Serial.print("SensorID was: 0x"); Serial.println(bmp.sensorID(),16);
Serial.print(" ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
Serial.print(" ID of 0x56-0x58 represents a BMP 280,\n");
Serial.print(" ID of 0x60 represents a BME 280.\n");
Serial.print(" ID of 0x61 represents a BME 680.\n");
while (1) delay(10);
}
/* Default settings from datasheet. */
bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */
Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */
Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */
Adafruit_BMP280::FILTER_X16, /* Filtering. */
Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */

// Initialize the output variables as outputs
pinMode(output, OUTPUT);
// Set outputs to LOW
digitalWrite(output, LOW);

// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();

// turns the GPIOs on and off
if (header.indexOf("GET /23/on") >= 0) {
Serial.println("LED on");
outputState = "on";
digitalWrite(output, HIGH);
} else if (header.indexOf("GET /23/off") >= 0) {
Serial.println("LED off");
outputState = "off";
digitalWrite(output, LOW);
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the table
client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial;}");
client.println("table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }");
client.println("th { padding: 12px; background-color: #0043af; color: white; }");
client.println("tr { border: 1px solid #ddd; padding: 12px; }");
client.println("tr:hover { background-color: #bcbcbc; }");
client.println("td { border: none; padding: 12px; }");
client.println(".sensor { color:#FF0000; font-weight: bold; padding: 1px; }");
// CSS to style the on/off buttons
client.println("<style>html { font-family: Sans-serif; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #0043af; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #ff0000;}</style></head>");

// Web Page Heading
client.println("</style></head><body><h1>Room Monitoring and Controlling System</h1>");
client.println("<table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>");
client.println("<tr><td>Temperature on Celcius</td><td><span class=\"sensor\">");
client.println(bmp.readTemperature());
client.println(" *C</span></td></tr>");
client.println("<tr><td>Temperature on Fahrenheit</td><td><span class=\"sensor\">");
client.println(1.8 * bmp.readTemperature() + 32);
client.println(" *F</span></td></tr>");
client.println("<tr><td>Pressure</td><td><span class=\"sensor\">");
client.println(bmp.readPressure() / 100.0F);
client.println(" hPa</span></td></tr>");
client.println("<tr><td>Approximate Altitude</td><td><span class=\"sensor\">");
client.println(bmp.readAltitude(1013.25));
client.println(" m</span></td></tr>");
// Display current state, and ON/OFF buttons for GPIO 23
client.println("<p>Fan State " + outputState + "</p>");
if (outputState=="off") {
client.println("<p><a href=\"/23/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/23/off\"><button class=\"button button2\">OFF</button></a></p>");
}
client.println("</body></html>");

// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}

change this part to your personal wifi or password.

// Replace with your network credentials
const char* ssid = "xxxxxxxx";
const char* password = "xxxxxxxx";

Upload the code to your ESP32 board. Don’t forget to select the right board and COM port.

After uploading the code press the EN button on your ESP32, open your serial monitor, and check if your ESP32 is connected or not by checking your IP address on your serial monitor:

Now open your browser on your device that is connected to the same network as your ESP32. Type the IP address on your browser and enter.

Now you should see the picture above and try to press the on button. After pressing the ON button, the LED will turn on. If your press the OFF button, the LED will turn off.

Now you already reached the end of this tutorial. Hope you enjoy it!

18220027 — Andreana Hartadi Suliman

--

--

Andreana Hartadi Suliman

If we are afraid of failure, it means we have limited our ability. — Hi, nice to see you here. Have a good day!