ESP32 is a powerful microcontroller, widely used in IoT projects, and can run a web server allowing electronic devices to be controlled over the web. This guide will walk you through the procedure of creating a simple web server on an ESP32 chip that will enable a user to control an LED remotely.
Before we begin, ensure you have the following equipment:
Note: This tutorial assumes that you have a basic understanding of the Arduino IDE and PHP programming.
The next step is to connect the LED to the ESP32. For this, connect the LED's anode (long leg) to the GPIO 23 of the ESP32 through a 220-ohm resistor. Connect the LED's cathode (short leg) directly to the GND.
#include <WiFi.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
WiFiServer wifiServer(80);
void setup() {
Serial.begin(115200);
delay(1000);
pinMode(23, OUTPUT);
digitalWrite(23, LOW);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("...");
}
Serial.println(WiFi.localIP());
wifiServer.begin();
}
void loop() {
WiFiClient client = wifiServer.available();
if (client) {
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
if (request.indexOf("/LED=ON") != -1) {
digitalWrite(23, HIGH);
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(23, LOW);
}
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.print("<html><body><h1>Hello from ESP32!</h1></body></html>");
delay(1);
client.stop();
Serial.println("Client disconnected");
Serial.println("");
}
}
To upload the code:
On successful upload:
/LED=ON or /LED=OFF.What can you do with an ESP32 web server?
Can multiple clients connect to the ESP32 web server at the same time?
Can the ESP32 server be accessed outside the local network?
Remember, coding is about exploration and creativity. Once you've got the basics down with this LED example, you can expand on this project by adding more functionalities to your web server.
This guide has demonstrated how to create a basic web server on an ESP32 to control an LED over the internet. The possibilities are endless with this, as the functionality can be adapted and expanded for many other applications, from home automation to industrial machine control.
Enjoy coding!