ESP32 Chapter 8 Part 1: Wi-Fi Web Server

Christovito Hidajat
5 min readMar 22, 2020

--

Hello and Welcome!

Amidst all the chaotic deadlines, made even worse by the Coronavirus outbreak — making me do the social-distancing — it is time to be back exploring and experimenting the beloved ESP32 and its features. Moving on from the previous projects utilizing Bluetooth, this time, a more advanced wireless connection, the WiFi module. Another one to add to the things-you-do-when-you-self-isolate list. Indeed, I am curious about this one.

Web Server

This sub-project instructs us to create a standalone web server using the ESP32, which is able to control two LEDs’ outputs, ON and OFF from the server. Before we start, we require these following components.

  1. The ESP32 board
  2. 2 (two) LEDs
  3. Breadboard
  4. 2 (two) 1k Ohm resistors
  5. Jumper wires

Afterwards, make the circuit diagram based on the schematic diagram below.

source: randomnerdtutorials.com

And here is the slightly long code.

// Import required libraries
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include <Adafruit_Sensor.h>
#include <DHT.h>
// Replace with your network credentials
const char* ssid = "THALIA";
const char* password = "********";
#define DHTPIN 4 // Digital pin connected to the DHT sensor#define DHTTYPE DHT11 // DHT 11DHT dht(DHTPIN, DHTTYPE);// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
String readDHTTemperature() {
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
//float t = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return "--";
}
else {
Serial.println(t);
return String(t);
}
}
String readDHTHumidity() {
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
if (isnan(h)) {
Serial.println("Failed to read from DHT sensor!");
return "--";
}
else {
Serial.println(h);
return String(h);
}
}
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<style>
html {
font-family: Arial;
display: inline-block;
margin: 0px auto;
text-align: center;
}
h2 { font-size: 3.0rem; }
p { font-size: 3.0rem; }
.units { font-size: 1.2rem; }
.dht-labels{
font-size: 1.5rem;
vertical-align:middle;
padding-bottom: 15px;
}
</style>
</head>
<body>
<h2>ESP32 DHT Server</h2>
<p>
<i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
<span class="dht-labels">Temperature</span>
<span id="temperature">%TEMPERATURE%</span>
<sup class="units">&deg;C</sup>
</p>
<p>
<i class="fas fa-tint" style="color:#00add6;"></i>
<span class="dht-labels">Humidity</span>
<span id="humidity">%HUMIDITY%</span>
<sup class="units">%</sup>
</p>
</body>
<script>
setInterval(function ( ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("temperature").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/temperature", true);
xhttp.send();
}, 10000 ) ;
setInterval(function ( ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("humidity").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/humidity", true);
xhttp.send();
}, 10000 ) ;
</script>
</html>)rawliteral";
// Replaces placeholder with DHT values
String processor(const String& var){
//Serial.println(var);
if(var == "TEMPERATURE"){
return readDHTTemperature();
}
else if(var == "HUMIDITY"){
return readDHTHumidity();
}
return String();
}
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
dht.begin();

// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readDHTTemperature().c_str());
});
server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readDHTHumidity().c_str());
});
// Start server
server.begin();
}

void loop(){

}

const char* ssid = “<<your WiFi SSID>>”;
const char* password = “
<<your WiFi password>>”;

Don’t forget to change the WiFi set-up code above. And then, upload the code. Then head to the serial monitor, and press the EN (reset) button on the ESP32 board. It connects to the WiFi, and the serial monitor shows you the ESP32 IP address.

Mine showed 192.168.100.6. Copy this IP address to access the ESP32 web server on any web browser. The web server will look like this.

There are two buttons for each GPIO, 26 and 27 with their states, “State on” or “State off”. The state of both LED purely depends on these two buttons on the web server, when you press ON, the LED connected to the related GPIO will be ON, and the other way around. By watching this video below, you can tell which LED is connected to GPIO 26, and GPIO 27 respectively.

So which LED is connected to GPIO 26 and which one to GPIO 27? Find out only by watching the video :). And also notice that everytime I pressed any button, the state on the serial monitor also changed.

Well, interesting, isn’t it? I didn’t find any meaningful problems, in fact it was quite easy and fun and sort of addictive lol. One of the interesting things is that I could start learning a small bit of HTML programming language on building a web server, as it seemed interesting and important.

But, also, the main thing is, I have been feeling sad about the virus outbreak that I have been staying at home for nearly a week. Thanks to 8 deadlines — and counting — I’ve been fully-occupied all day all night and this project, yes, especially this one, helped me get through all the difficult times a bit. Stay tuned for the very next project!

Christovito Hidajat
18218043

--

--

Responses (1)