One of the most fun things about the ESP32: it serves a web page you open from your phone, so you can see the temperature and switch the light on, with no app and no external server.
The idea in two lines
When you type an address into the browser, the phone sends a request to that device saying "I want the page /". The ESP32 acts as a server: it waits for requests on port 80, and each path (/ and /toggle) has a function that replies. The reply can be an HTML page, just numbers, or a "go to another page" instruction.
The code
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "your-network";
const char* pass = "your-password";
WebServer server(80);
const int LED = 2;
bool ledOn = false;
void handleRoot() {
String html = "<meta name='viewport' content='width=device-width'>";
html += "<h1>Circuits Nerd</h1>";
html += "<p>LED: " + String(ledOn ? "ON" : "OFF") + "</p>";
html += "<a href='/toggle'><button>Toggle</button></a>";
server.send(200, "text/html", html);
}
void handleToggle() {
ledOn = !ledOn;
digitalWrite(LED, ledOn);
server.sendHeader("Location", "/");
server.send(303);
}
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) delay(300);
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.on("/toggle", handleToggle);
server.begin();
}
void loop() {
server.handleClient();
}
Replying with 303 after toggling sends the browser back to the home page, so a refresh won't send /toggle again.
Trying it
- Upload the code and open the Serial Monitor at 115200.
- It prints an IP such as
192.168.1.50. - Open it in your phone's browser, while on the same network.
Prefer a name to a number? The ESPmDNS library lets you open esp32.local (it works on most devices, though not on some older Android devices):
#include <ESPmDNS.h>
// in setup, after connecting:
MDNS.begin("esp32");
Adding a sensor reading
Read the sensor inside handleRoot and put it in the HTML. To make the page refresh by itself, add this at its top:
<meta http-equiv='refresh' content='5'>
That's the easiest way, but the whole page reloads and flickers.
Better: numbers that update without reloading
Have the ESP32 answer a /data path with just the numbers (in JSON format), and the page has a few lines of JavaScript that ask every two seconds:
void handleData() {
String json = "{\"t\":" + String(temp, 1) + ",\"h\":" + String(hum, 0) + "}";
server.send(200, "application/json", json);
}
// in setup:
server.on("/data", handleData);
And in the HTML:
<p>Temp: <b id='t'>--</b> C</p>
<script>
setInterval(async () => {
const r = await fetch('/data');
const d = await r.json();
document.getElementById('t').textContent = d.t;
}, 2000);
</script>
Now only the number changes, and the page stays still. Keep the sensor reading itself in the loop at intervals with millis, with handleData returning the latest value, so the reply is instant.
Sending a number from the page
For example a motor speed or an LED's brightness from a slider. The page sends /set?pwm=128, and the ESP32 reads it:
void handleSet() {
if (server.hasArg("pwm")) {
int v = constrain(server.arg("pwm").toInt(), 0, 255);
analogWrite(LED, v);
}
server.send(200, "text/plain", "OK");
}
constrain matters: anyone can type a strange number into the address, so make sure the value is within the allowed range before using it.
No router: access point (AP) mode
On farmland or in a workshop with no Wi-Fi, the ESP32 can create a network by itself:
WiFi.softAP("CircuitsNerd", "12345678"); // password at least 8 characters
Serial.println(WiFi.softAPIP()); // usually 192.168.4.1
Connect to the network from your phone and open 192.168.4.1. This is also used for a first-time setup page: the user enters their network name and password, and they're saved with Preferences.
If the Wi-Fi drops
The router restarts, or the signal weakens. Add this to the loop:
static unsigned long tCheck = 0;
if (millis() - tCheck > 10000) {
tCheck = millis();
if (WiFi.status() != WL_CONNECTED) WiFi.reconnect();
}
Tips
- Don't put a long
delayin the loop, or the server will be slow to reply. See millis instead of delay. - Fix the IP in the router (DHCP reservation) so it doesn't change.
- If the page is large, store it as a
const char[]or in LittleFS files. - Power: Wi-Fi draws high current pulses (up to 300–500 mA momentarily). A weak supply or a thin USB cable causes resets. See choosing a power supply.
- If you need a server that handles several people at once smoothly, the ESPAsyncWebServer library is more capable, but a bit more complex.
Recurring problems
| Problem | Usual cause |
|---|---|
| It never connects to the network | The network is 5 GHz only, and the ESP32 supports 2.4 GHz |
| The IP isn't printed | Wrong password, or a different speed in the Serial Monitor |
| The page won't open | The phone is on another network or on mobile data |
| It works for a while then stops | The Wi-Fi dropped with no reconnect, or the supply is weak |
| The reply is slow | A delay in the loop |
Security
This method works on the local network only, and anyone on the Wi-Fi can open the page. Don't open a port on the router to reach it from outside. If you need control from anywhere, use a secure cloud service or MQTT with encryption. And if you're controlling 220 V appliances with a relay, mind electrical safety.
You can put a simple username and password on the page:
if (!server.authenticate("admin", "pass123")) return server.requestAuthentication();
That stops guests on the network from playing with it, but the password is sent unencrypted, so it's no substitute for the advice above.
FAQ
How many phones can open the page at once? A few is normal, because each request finishes quickly. If there are many, or they ask every second, the async library is better.
Can I run an AP and connect to a router at the same time? Yes, with the WIFI_AP_STA mode, but both must be on the same channel.