মূল বিষয়বস্তুতে যান
Learn/Connected ESP32/A web page that controls an LED
Connected ESP32 · Lesson
15 min read

A web page that controls an LED

Serve a tiny page from the ESP32 and switch GPIO2 from your phone.

What You Will Learn

  • Create a WebServer
  • Handle routes
  • Control hardware from a browser
Arduino C++
#include <WiFi.h>
#include <WebServer.h>

WebServer server(80);
const int LED = 2;

void page() {
  server.send(200, "text/html", "<a href='/on'>ON</a> | <a href='/off'>OFF</a>");
}

void setup() {
  pinMode(LED, OUTPUT);
  WiFi.begin("your-network", "your-password");
  while (WiFi.status() != WL_CONNECTED) delay(250);
  server.on("/", page);
  server.on("/on", [] { digitalWrite(LED, HIGH); page(); });
  server.on("/off", [] { digitalWrite(LED, LOW); page(); });
  server.begin();
}

void loop() { server.handleClient(); }

Open the IP address printed in the Serial Monitor on a phone connected to the same network.

This page has no password. Only run it on a network you trust, and never expose it to the internet.

Check Your Understanding

Test what you learned in this lesson

1What must loop() call for the WebServer to answer requests?