Default image description

Create a Web Server with ESP32

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.

Components Required

No Ads Available.

Installing ESP32 Board in Arduino IDE

  1. Open the Arduino IDE.
  2. Go to File > Preferences.
  3. In the Additional Board Manager URLs field, add the following URL:
  4. https://dl.espressif.com/dl/package_esp32_index.json
  5. Go to Tools > Board > Board Manager.
  6. Search for "ESP32" and install the package.

Arduino Code

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);
const int ledPin = 2;

void setup() {
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  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();
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    String currentLine = "";
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        currentLine += c;
        if (c == '\n') {
          if (currentLine.length() == 0) {
            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)); } currentLine = ""; } } } client.stop(); Serial.println("Client Disconnected"); } }

How the Code Works

Testing the Web Server

  1. Upload the code to the ESP32 using the Arduino IDE.
  2. Open the Serial Monitor to get the ESP32's IP address.
  3. Enter the IP address in a web browser on the same network as the ESP32.
  4. You should see the web page with a button to toggle the LED.
  5. Press the button on the web page to toggle the LED.

Troubleshooting

Applications

Further Improvements

Conclusion

In this tutorial, we created a simple ESP32 web server to control an LED remotely. This setup can be enhanced for various IoT applications.

Contact Us

If you have any questions or inquiries, feel free to reach out to us at Microautomation.no@icloud.com .

Follow our Socials for the newest updates!