esp8266在网页上显示事实时间
时间: 2023-11-30 18:03:21 浏览: 108
要在网页上显示实时时间,可以使用ESP8266连接到网络并获取网络时间。下面是一个简单的Arduino示例代码,可以从网络时间服务器获取当前时间,并显示在ESP8266的网页上:
```c++
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <TimeLib.h>
#include <ESP8266WebServer.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const int NTP_PACKET_SIZE = 48;
byte packetBuffer[NTP_PACKET_SIZE];
WiFiUDP udp;
ESP8266WebServer server(80);
unsigned int localPort = 8888;
const char* timeServer = "pool.ntp.org";
const int timeZone = 8;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
udp.begin(localPort);
Serial.println("UDP started");
setSyncProvider(getNtpTime);
setSyncInterval(300);
server.on("/", handleRoot);
server.begin();
}
void loop() {
server.handleClient();
}
void handleRoot() {
char buf[100];
sprintf(buf, "%02d:%02d:%02d", hour(), minute(), second());
String html = "<html><body><h1>Current time is: ";
html += buf;
html += "</h1></body></html>";
server.send(200, "text/html", html);
}
unsigned long getNtpTime() {
IPAddress ntpServerIP;
while (udp.parsePacket() > 0);
if (!WiFi.hostByName(timeServer, ntpServerIP)) {
Serial.println("DNS lookup failed");
return 0;
}
Serial.println("Sending NTP request");
memset(packetBuffer, 0, NTP_PACKET_SIZE);
packetBuffer[0] = 0b11100011;
packetBuffer[1] = 0;
packetBuffer[2] = 6;
packetBuffer[3] = 0xEC;
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
udp.beginPacket(ntpServerIP, 123);
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
delay(1000);
int cb = udp.parsePacket();
if (!cb) {
Serial.println("No NTP response");
return 0;
}
Serial.println("NTP response received");
udp.read(packetBuffer, NTP_PACKET_SIZE);
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
unsigned long secsSince1900 = highWord << 16 | lowWord;
const unsigned long seventyYears = 2208988800UL;
unsigned long epoch = secsSince1900 - seventyYears;
epoch += timeZone * SECS_PER_HOUR;
return epoch;
}
```
运行代码后,在浏览器中输入ESP8266的IP地址,即可看到当前的时间。
阅读全文