#include <WiFi.h>
// Server running on port 80
WiFiServer server(80);
// Variables for storing HTTP request and output state
String header;
String outputState = "off";
// Timing variables for client timeout
unsigned long currentTime = millis();
unsigned long previousTime = 0;
const long timeoutTime = 2000;
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Set GPIO 2 as output
pinMode(2, OUTPUT);
// Connect to WiFi
WiFi.begin("soc2019", "socka2019");
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}
// Print connection details
Serial.println("\nWiFi úspešne pripojená!");
Serial.print("IP adresa: ");
Serial.println(WiFi.localIP());
// Start the server
server.begin();
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (client) {
Serial.println("Nový klient");
currentTime = millis();
previousTime = currentTime;
// String to store the request line
String currentLine = "";
while (client.connected() && (currentTime - previousTime <= timeoutTime)) {
currentTime = millis();
// Check if data is available to read
if (client.available()) {
char c = client.read();
Serial.write(c); // Print received characters
header += c;
// If a newline is received
if (c == '\n') {
// If the current line is empty, the request is complete
if (currentLine.length() == 0) {
// Send HTTP response
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println("");
// Handle GPIO on/off requests
if (header.indexOf("GET /2/on") >= 0) {
Serial.println("GPIO 2 ON");
outputState = "on";
digitalWrite(2, HIGH);
} else if (header.indexOf("GET /2/off") >= 0) {
Serial.println("GPIO 2 OFF");
outputState = "off";
digitalWrite(2, LOW);
}
// Send the HTML webpage
client.println("<!DOCTYPE html><html>");
client.println("<head><title>ESP32 Web Server</title>");
client.println("<style>");
client.println("body { font-family: Arial; text-align: center; margin: 20px; }");
client.println(".button { padding: 10px 20px; text-decoration: none; color: white; border-radius: 5px; }");
client.println(".button-on { background-color: green; }");
client.println(".button-off { background-color: red; }");
client.println("</style></head>");
client.println("<body>");
client.println("<h1>ESP32 Web Server</h1>");
client.println("<p>GPIO 2 - State: <strong>" + outputState + "</strong></p>");
if (outputState == "off") {
client.println("<p><a href=\"/2/on\" class=\"button button-on\">ON</a></p>");
} else {
client.println("<p><a href=\"/2/off\" class=\"button button-off\">OFF</a></p>");
}
client.println("</body></html>");
client.println("");
break;
} else {
currentLine = ""; // Clear the current line
}
} else if (c != '\r') {
currentLine += c; // Add character to the current line
}
}
}
// Clear the header and stop the client
header = "";
client.stop();
Serial.println("Klient je odpojený.");
Serial.println("");
}
}