Difficulty Level: Intermediate
The ESP32 is a powerful microcontroller with built-in Wi-Fi capabilities, allowing you to create a web server to control devices or display sensor data. In this tutorial, we will set up a simple web server that serves a web page accessible from any device on the same network.
No additional wiring is required for this project if you are only serving a web page. The ESP32 will connect to your Wi-Fi network.
https://dl.espressif.com/dl/package_esp32_index.json
The following code creates a simple web server that serves a webpage with a button to control an LED connected to pin 2 of the ESP32:
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
WiFiServer server(80); // Create a server that listens on port 80
const int ledPin = 2; // LED connected to GPIO 2
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // Turn the LED off
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
server.begin(); // Start the server
}
void loop() {
WiFiClient client = server.available(); // Check for incoming clients
if (client) {
String currentLine = ""; // Variable to store incoming data
while (client.connected()) {
if (client.available()) {
char c = client.read(); // Read a byte
Serial.write(c); // Echo the byte back to the serial monitor
currentLine += c; // Add the byte to the current line
// If the line is complete
if (c == '\n') {
// Send a response to the client
if (currentLine.length() == 0) {
// Send HTML response
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
client.println("ESP32 Web Server ");
client.println("ESP32 Web Server
");
client.println("LED Control:
");
client.println("");
client.println("");
client.println("");
break;
} else if (currentLine.endsWith("GET /toggle")) {
digitalWrite(ledPin, !digitalRead(ledPin)); // Toggle the LED state
}
currentLine = ""; // Clear the current line
}
}
}
client.stop(); // Close the connection
Serial.println("Client Disconnected");
}
}
Follow these steps to test the web server:
In this tutorial, you created a simple web server using the ESP32, enabling you to control an LED via a web interface. This project can be expanded to include various sensors and actuators, allowing for remote monitoring and control of devices over the internet.