折腾智能家居的第一步,我推荐就从"用浏览器控制一颗 LED"开始。ESP32 自带 WiFi,不用外加任何模块,几十行代码就能让它变成一台小型网页服务器:手机连上同一 WiFi,浏览器输个 IP,页面上两个按钮,点一下灯就亮。这个例程是后来所有物联网项目的基本功,值得吃透。

原理:ESP32 当服务器,浏览器当客户端
整件事的分工很清楚:ESP32 连上你家路由器后开一个 80 端口的服务器;手机或电脑的浏览器是客户端,向 ESP32 发 HTTP 请求。你每点一次页面上的 ON 或 OFF 按钮,浏览器就发一个带路径的 GET 请求(比如 /26/on),ESP32 检查请求头里有没有这段路径,有就把对应 GPIO 拉高或拉低,顺便把页面重新渲染一遍,按钮状态跟着变。

接线:两颗 LED 两个 GPIO
例程用 GPIO26 和 GPIO27 各控制一颗 LED:LED 长脚(正极)串一颗 220Ω 电阻接 GPIO,短脚接 GND。ESP32 的 GPIO 输出 3.3V,点亮普通 LED 完全够用。
完整代码
下面是完整例程,只需把 SSID 和密码改成你家 WiFi 的。整个例程只用 WiFi.h,不需要装第三方库。提前说明一处写法:页面 HTML 里全是尖括号标签,为了能在这边的编辑器里完整显示,代码用 LT 宏拼出尖括号,粘回 Arduino IDE 直接编译,效果和原版逐字符一致:
/*********
Rui Santos
Complete project details at https://randomnerdtutorials.com
*********/
// Load Wi-Fi library
#include "WiFi.h"
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String output26State = "off";
String output27State = "off";
// Assign output variables to GPIO pins
const int output26 = 26;
const int output27 = 27;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
// 本平台编辑器会剥除代码块内的 HTML 尖括号,用 LT 宏拼接(编译等价写法)
#define LT "<"
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 with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (header.indexOf("GET /26/on") >= 0) {
Serial.println("GPIO 26 on");
output26State = "on";
digitalWrite(output26, HIGH);
} else if (header.indexOf("GET /26/off") >= 0) {
Serial.println("GPIO 26 off");
output26State = "off";
digitalWrite(output26, LOW);
} else if (header.indexOf("GET /27/on") >= 0) {
Serial.println("GPIO 27 on");
output27State = "on";
digitalWrite(output27, HIGH);
} else if (header.indexOf("GET /27/off") >= 0) {
Serial.println("GPIO 27 off");
output27State = "off";
digitalWrite(output27, LOW);
}
// Display the HTML web page
client.println(LT "!DOCTYPE html>" LT "html>");
client.println(LT "head>" LT "meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println(LT "link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println(LT "style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}" LT "/style>" LT "/head>");
// Web Page Heading
client.println(LT "body>" LT "h1>ESP32 Web Server" LT "/h1>");
// Display current state, and ON/OFF buttons for GPIO 26
client.println(LT "p>GPIO 26 - State " + output26State + LT "/p>");
// If the output26State is off, it displays the ON button
if (output26State=="off") {
client.println(LT "p>" LT "a href=\"/26/on\">" LT "button class=\"button\">ON" LT "/button>" LT "/a>" LT "/p>");
} else {
client.println(LT "p>" LT "a href=\"/26/off\">" LT "button class=\"button button2\">OFF" LT "/button>" LT "/a>" LT "/p>");
}
// Display current state, and ON/OFF buttons for GPIO 27
client.println(LT "p>GPIO 27 - State " + output27State + LT "/p>");
// If the output27State is off, it displays the ON button
if (output27State=="off") {
client.println(LT "p>" LT "a href=\"/27/on\">" LT "button class=\"button\">ON" LT "/button>" LT "/a>" LT "/p>");
} else {
client.println(LT "p>" LT "a href=\"/27/off\">" LT "button class=\"button button2\">OFF" LT "/button>" LT "/a>" LT "/p>");
}
client.println(LT "/body>" LT "/html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}代码结构分三块:setup 里连 WiFi 并打印分配到的 IP 地址;loop 里 server.available() 检查有没有客户端连进来,把收到的 HTTP 请求头存进 header 字符串;收到完整请求后先判断路径再返回 HTML 页面。页面样式写得很朴素,绿色 ON 按钮、灰色 OFF 按钮,状态互切。
烧录与验证
Arduino IDE 里开发板选 ESP32 Dev Module,改好 WiFi 信息后烧录。上传完打开串口监视器,波特率 115200,按一下 ESP32 的 RST 键,等它连上路由器后会把 IP 地址打出来:

确保手机连在同一个 WiFi 下,浏览器输入这个 IP,就能看到控制页面:

点 ON,GPIO26 的 LED 应该立刻亮起,页面按钮变成灰色 OFF,串口里也能看到 New Client 和 GPIO 26 on 的日志:

几个踩坑点
一是手机和 ESP32 必须在同一网段,连了访客网络或开了 AP 隔离的 WiFi 就互相看不见;二是点按钮瞬间会有轻微延迟,例程是靠浏览器重新请求来刷新状态的,属正常;三是这个例程只服务局域网,别把路由器端口映射到公网——例程没有任何鉴权,暴露公网等于家里开关向全网开放。想远程控制,下一步该研究的是加密码登录或直接上 MQTT。
搞懂这版之后可以升级两个方向:把网页改成 AJAX 无刷新控制,或者接入 WebSocket 实时推送状态。ESP32 的算力应付这些绰绰有余,架子已经搭好,随便折腾。











LT宏这招不错,其他站抄代码经常被剥得缺胳膊少腿。
AP隔离那个坑太真实了,公司WiFi就是连不上,换了手机热点秒通。
建议下一篇写WebSocket版,AJAX版也想要。
GPIO26/27在有些板子上接了PSRAM,用之前最好查下引脚表。