esp8266在网页上显示时间
时间: 2023-11-30 09:03:21 浏览: 111
Ardunio ESp8266+0.94寸OLED(SPI) 显示网络时间
要在ESP8266的网页上显示时间,可以使用ESP8266的内部时钟来获取当前时间,并将其显示在网页上。下面是一个简单的Arduino示例代码,可以实现这个功能:
```c++
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <TimeLib.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
ESP8266WebServer server(80);
void handleRoot() {
String html = "<html><body><h1>Current time is: ";
html += getTimeStr();
html += "</h1></body></html>";
server.send(200, "text/html", html);
}
String getTimeStr() {
String str = "";
int hour = hour();
int minute = minute();
int second = second();
if (hour < 10) {
str += "0";
}
str += String(hour) + ":";
if (minute < 10) {
str += "0";
}
str += String(minute) + ":";
if (second < 10) {
str += "0";
}
str += String(second);
return str;
}
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");
setSyncProvider(getNtpTime);
setSyncInterval(300);
server.on("/", handleRoot);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
unsigned long getNtpTime() {
// 获取网络时间的代码,同上
}
```
运行代码后,在浏览器中输入ESP8266的IP地址,即可看到当前的时间。
阅读全文