如何实现Arduino网页标题每5秒更新?server.send重复发送失效排查
解决Arduino网页每5秒更新标题的问题
你的问题核心是对HTTP请求-响应模式的理解偏差,加上代码里的错误用法导致的:
为什么原代码无法工作?
HTTP是请求-响应模型——客户端(浏览器)发一次请求,服务器(Arduino)返回一次响应,server.send()执行完就意味着这次请求的会话彻底结束了。你在server.send()之后加delay()再调用server.send(),这时候已经没有对应的客户端请求了,自然不会有任何效果。而且delay()会阻塞Arduino的主循环,导致它无法处理其他客户端请求,这也是非常不推荐的写法。
正确的实现思路
要实现网页标题每5秒更新,需要客户端主动轮询服务器获取最新数据,同时服务器端用非阻塞的方式切换要发送的内容(避免用delay())。具体分两步:
- Arduino端:每次收到客户端请求时,返回当前要显示的内容;同时定时切换内容(用
millis()而非delay(),保证主循环不阻塞)。 - 网页端:用JavaScript定时向Arduino发起请求,拿到新数据后更新页面标题。
完整代码示例
Arduino 代码
#include <WiFi.h> #include <WebServer.h> // 替换成你的WiFi信息 const char* ssid = "YourWiFiSSID"; const char* password = "YourWiFiPassword"; WebServer server(80); String currentTitle = "Nice to see you what's your name?"; unsigned long lastUpdateTime = 0; const unsigned long updateInterval = 5000; // 5秒 // 处理根路径请求,返回当前标题 void handleRootRequest() { // 返回JSON格式的字符串 server.send(200, "application/json", "\"" + currentTitle + "\""); } void setup() { Serial.begin(115200); // 连接WiFi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nWiFi connected!"); Serial.print("Arduino IP: "); Serial.println(WiFi.localIP()); // 注册请求处理函数 server.on("/", handleRootRequest); server.begin(); } void loop() { server.handleClient(); // 处理客户端请求,必须放在循环里 // 非阻塞式切换标题,避免阻塞主循环 unsigned long currentTime = millis(); if (currentTime - lastUpdateTime >= updateInterval) { lastUpdateTime = currentTime; // 切换标题内容 if (currentTitle == "Nice to see you what's your name?") { currentTitle = "Hello, How are you?"; } else { currentTitle = "Nice to see you what's your name?"; } } }
网页代码(可存为HTML文件,或嵌入Arduino SPIFFS)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title id="dynamicTitle">Loading...</title> <script> // 替换成你的Arduino IP地址 const arduinoIP = "http://192.168.1.100"; // 每5秒请求一次新标题 setInterval(() => { fetch(arduinoIP) .then(res => res.json()) .then(newTitle => { document.getElementById("dynamicTitle").textContent = newTitle; }) .catch(err => console.log("请求失败:", err)); }, 5000); </script> </head> <body> <h1>页面标题会每5秒自动更新</h1> </body> </html>
为什么这样能工作?
- Arduino端用
millis()做定时,不会阻塞主循环,能一直响应客户端的请求;每次收到请求就返回当前的标题内容。 - 网页端用
setInterval定时发起HTTP请求,每次都能拿到Arduino最新的标题文本,然后通过JavaScript更新页面的<title>标签。 - 完全符合HTTP的请求-响应规则,不会出现原代码里的无效
server.send()调用。
内容的提问来源于stack exchange,提问作者BenjiProgramming
相关产品推荐
相关产品推荐

