
给 ESP32 找入门项目,网页控 LED 基本是绕不开的第一课:不装 App、不写上位机,浏览器输个 IP 就能开灯关灯。这次把 Random Nerd Tutorials 的经典教程完整过了一遍,对应代码放在 GitHub 仓库 RuiSantosdotme/ESP32-Course 里,走 jsdelivr 镜像拉取很稳。Arduino 框架,依赖只有 ESP32 核心包自带的 WiFi.h,零第三方库,复现门槛很低。
这篇教程的思路值得先说一句:它没有用任何 Web 框架,就是 WiFiServer 在 80 端口裸收 HTTP 请求,自己解析请求头、自己拼 HTML 回回去。代码总共一百五十来行,把「一个 Web 服务器到底在干什么」拆得明明白白,比一上来就上 ESPAsyncWebServer 更适合打底。
备料与接线
器件清单很简单:一块 ESP32 DEVKIT DOIT 开发板(教程用的是 36 引脚版)、两颗 LED、两个 330 欧电阻、面包板加几根杜邦线。没有其他模块。

接线是两路完全对称的输出:GPIO26 串 330 欧电阻接第一颗 LED 正极,负极回 GND;GPIO27 同样处理第二颗。教程特意提醒,不同厂家的 DEVKIT 引脚排布有差异,上手前先核对自己板子的引脚图,别按丝印想当然。

代码骨架:全局变量与 setup
完整代码可以在 jsdelivr 镜像取原文件(RuiSantosdotme/ESP32-Course 仓库 code/WiFi_Web_Server_Outputs 目录),下面按逻辑分四段拆。平台正文会把成对的半角尖括号当标签吞掉,所以头文件的 include 按编译等价写法改成了引号形式,两种写法在 Arduino 工具链下搜索路径等价;网页下发段的 HTML 标签用全角尖括号显示,抄写时改回半角即可,其余逐字符与源码一致。
/*********
Rui Santos
Complete project details at http://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;全局部分四样东西:WiFi 凭据、80 端口的 WiFiServer 对象、一个存请求头的字符串、两个 GPIO 的状态变量。开头就把两个引脚的初始状态定成 off,后面网页显示和 digitalWrite 全靠这两个变量撑着。
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();
}setup 里先把两个引脚拉低,再 WiFi.begin 连家里路由,连上后串口(115200)会打出分配到的局域网 IP——这个 IP 就是后面浏览器要访问的地址,抄下来。最后 server.begin() 起服务。容易卡住的地方就一个:WiFi 连不上多半是 2.4G/5G 频段问题,ESP32 只认 2.4GHz,很多家路由默认双合一。
路由逻辑:靠请求头字符串匹配
loop 的前半段是收请求:server.available() 有新客户端就连上,逐字节读进 header 字符串,同时留一份 currentLine 判断空行——HTTP 请求头以空行结尾,读到空行就开始回响应。这里还设了 2000 毫秒超时,防止浏览器握着连接不放把 loop 卡死。
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();真正的「路由」其实朴素得很:在收到的请求头里 indexOf 找 GET /26/on 这类路径字符串,命中哪条就切哪个引脚。没有路由表、没有回调注册,但对两个开关的场景完全够用,而且一眼能看懂整条链路。
// 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);
}网页下发:手拼 HTML 与按钮状态
响应头之后就是往客户端写 HTML。页面结构很简:一个标题、每个 GPIO 一行状态文字加一个按钮,按钮本质是 a 标签套 button 样式,点了就向 /26/on 或 /26/off 发起新请求,服务器收到后改引脚电平并重新渲染页面。按钮颜色靠内联 CSS 区分,on 状态显示灰底 OFF,off 状态显示绿底 ON。下面这段是网页下发部分的原文,HTML 标签的尖括号临时转成全角显示(正文排版会吞半角成对尖括号),照抄时改回半角即可:
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<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("<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;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
// Display current state, and ON/OFF buttons for GPIO 26
client.println("<p>GPIO 26 - State " + output26State + "</p>");
// If the output26State is off, it displays the ON button
if (output26State=="off") {
client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
}
// Display current state, and ON/OFF buttons for GPIO 27
client.println("<p>GPIO 27 - State " + output27State + "</p>");
// If the output27State is off, it displays the ON button
if (output27State=="off") {
client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/27/off\"><button class=\"button button2\">OFF</button></a></p>");
}
client.println("</body></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("");
}
}有几个细节复现时值得留意。viewport 那行让页面在手机上不缩成小字,实测手机浏览器体验比很多入门项目好;link 的 href 是 data: 空图标,省掉一次 404 请求。这套「请求来了现拼现发」的模式没有 WebSocket,页面不会自动刷新状态,两个设备同时开页面会互相看到旧状态,点一下按钮就同步回来了。

上传、局域网访问与进阶方向
Arduino IDE 里选对板型(DOIT ESP32 DEVKIT V1)和串口,上传后打开串口监视器按板上的 EN 键复位,等 WiFi connected 和 IP address 两行出来。手机连同一个 WiFi,浏览器输入那个 IP,就能看到控制页。

跑通之后想往深走,两条路都顺。一条是换 ESPAsyncWebServer 这类异步库,事件式路由、页面状态自动更新,还能顺手上 WebSocket;另一条是把字符串匹配的路由改成正规的处理函数注册,为后面加传感器接口做准备。原教程页面底部还挂着同系列的家庭自动化方向(Web Relay、物理按钮联动),仓库里都有对应目录,照着目录名找就行。整个项目没有外部依赖,烧录即用,作为局域网服务类玩法的第一个台阶很合适。











照着这篇跑通了,顺手记个坑:ESP32 死活连不上 WiFi 最后发现是路由器把 2.4G 和 5G 合成一个名字,把 5G 关掉立刻就好了,文章里提到这个点真不是废话。
indexOf 匹配请求头这段讲得清楚,第一次看明白所谓路由其实就是字符串查找。
两颗 LED 换成继电器就能控台灯了,思路直接平移。
串口打印的 IP 每次重启会不会变?家里路由 DHCP 老给新地址的话建议去后台绑个静态,不然天天换 IP 挺烦。