11th October 2023 / 02:00 PM
I managed to set up a webserver on the ESP32. The site running on it has 2 buttons: One to turn the attached LED on, one to turn it off. The local IP is printed to the serial monitor. You can also read if the LED is currently on or off in the serial monitor.
Here is the code used for this project:
#include <WiFi.h>
const char* ssid = "SSID"; // Entering WiFi SSID
const char* pass = "PASSWORD"; // Entering WiFi Password
WiFiServer server(80); // Creating a webserver on Port 80
const int ledPin = 14; // LED-PIN
bool ledStatus = LOW; // The initial state of the LED (OFF)
void setup() {
pinMode(ledPin, OUTPUT); // Setting the LED-PIN to output
Serial.begin(115200); // Starting the serial communication
WiFi.begin(ssid, pass); // Starting to establish a connection to the WiFi network
while (WiFi.status() != WL_CONNECTED) delay(500); // Waiting until the connection is established
// Print the IP address in the requested format
Serial.print("The ESP32's local IP-Address is: ");
Serial.println(WiFi.localIP());
server.begin(); // Starting up the webserver on Port 80
}
void loop() {
WiFiClient client = server.available(); // Checking if a Client is connected
if (client) {
String req = client.readStringUntil('\r'); // Reading the client's HTTP request up to the line break ('\r')
// Checking whether the request contains "/on" to turn on the LED or "/off" to turn it off
ledStatus = req.indexOf("GET /on") >= 0 ? HIGH : req.indexOf("GET /off") >= 0 ? LOW : ledStatus;
// Sending an HTTP response to the client (containing HTML)
client.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close\n");
// HTML contents
client.print("HTML HERE");
client.stop(); // Quitting the Client-connection
digitalWrite(ledPin, ledStatus); // Executing the command based on the client's request (controlling the LED / LED-PIN)
// Reporting the LED status in the Serial Monitor
Serial.println("LED is now " + String(ledStatus == HIGH ? "ON" : "OFF"));
}
}
The HTML looks like this: