/* Rui Santos & Sara Santos - Random Nerd Tutorials https://RandomNerdTutorials.com/esp32-web-server-beginners-guide/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ #include #include // Replace with your network credentials const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD"; // Assign output variables to GPIO pins const int output26 = 26; const int output27 = 27; String output26State = "off"; String output27State = "off"; // Create a web server object WebServer server(80); // Function to handle turning GPIO 26 on void handleGPIO26On() { output26State = "on"; digitalWrite(output26, HIGH); handleRoot(); } // Function to handle turning GPIO 26 off void handleGPIO26Off() { output26State = "off"; digitalWrite(output26, LOW); handleRoot(); } // Function to handle turning GPIO 27 on void handleGPIO27On() { output27State = "on"; digitalWrite(output27, HIGH); handleRoot(); } // Function to handle turning GPIO 27 off void handleGPIO27Off() { output27State = "off"; digitalWrite(output27, LOW); handleRoot(); } // Function to handle the root URL and show the current states void handleRoot() { String html = ""; html += ""; html += ""; html += "

ESP32 Web Server

"; // Display GPIO 26 controls html += "

GPIO 26 - State " + output26State + "

"; if (output26State == "off") { html += "

"; } else { html += "

"; } // Display GPIO 27 controls html += "

GPIO 27 - State " + output27State + "

"; if (output27State == "off") { html += "

"; } else { html += "

"; } html += ""; server.send(200, "text/html", html); } void setup() { Serial.begin(115200); // Initialize the output variables as outputs pinMode(output26, OUTPUT); pinMode(output27, OUTPUT); // Set outputs to LOW digitalWrite(output26, LOW); digitalWrite(output27, LOW); // Connect to Wi-Fi network Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected."); Serial.println("IP address: "); Serial.println(WiFi.localIP()); // Set up the web server to handle different routes server.on("/", handleRoot); server.on("/26/on", handleGPIO26On); server.on("/26/off", handleGPIO26Off); server.on("/27/on", handleGPIO27On); server.on("/27/off", handleGPIO27Off); // Start the web server server.begin(); Serial.println("HTTP server started"); } void loop() { // Handle incoming client requests server.handleClient(); }